?
Solved

a better, more reliable wheel scrolling script... maybe a refactor?

Posted on 2008-10-06
7
Medium Priority
?
956 Views
Last Modified: 2013-11-11
Hello, I'm looking to work on my script that I wrote based off a bunch of different articles and plug-ins all patched together to work for me... It's not pretty by any means... but it does work ... I think it's a little heavy and not very concise as it should be... but I'm still learning :-) almost 1 year yeah!!... so I was wanting to refactor I think... see if there was more of a fully jQuery way may-be... at least a shorter faster version I could turn this into... thanks for the help...
jeremyBass

$(function() {function handle(delta) {
    if (delta < 0) {
        $(".SA").scrollTo({
            top: '+=65px',
            left: '+=0px'
        },
        {
            offset: -0
        });
    } else {
        $(".SA").scrollTo({
            top: '-=65px',
            left: '+=0px'
        },
        {
            offset: -0
        });
    }
}
function wheel(event) {
    var delta = 0;
    if (!event) event = window.event;
    if (event.wheelDelta) {
        delta = event.wheelDelta / 120;
        if (window.opera) delta = -delta;
    } else if (event.detail) {
        delta = -event.detail / 3;
    }
    if (delta) handle(delta);
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}
if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel; (function(h) {
    var m = h.scrollTo = function(b, c, g) {
        h(window).scrollTo(b, c, g)
    };
    m.defaults = {
        axis: 'y',
        duration: 1
    };
    m.window = function(b) {
        return h(window).scrollable()
    };
    h.fn.scrollable = function() {
        return this.map(function() {
            var b = this.parentWindow || this.defaultView,
            c = this.nodeName == '#document' ? b.frameElement || b: this,
            g = c.contentDocument || (c.contentWindow || c).document,
            i = c.setInterval;
            return c.nodeName == 'IFRAME' || i && h.browser.safari ? g.body: i ? g.documentElement: this
        })
    };
    h.fn.scrollTo = function(r, j, a) {
        if (typeof j == 'object') {
            a = j;
            j = 0
        }
        if (typeof a == 'function') a = {
            onAfter: a
        };
        a = h.extend({},
        m.defaults, a);
        j = j || a.speed || a.duration;
        a.queue = a.queue && a.axis.length > 1;
        if (a.queue) j /= 2;
        a.offset = n(a.offset);
        a.over = n(a.over);
        return this.scrollable().each(function() {
            var k = this,
            o = h(k),
            d = r,
            l,
            e = {},
            p = o.is('html,body');
            switch (typeof d) {
            case 'number':
            case 'string':
                if (/^([+-]=)?\d+(px)?$/.test(d)) {
                    d = n(d);
                    break
                }
                d = h(d, this);
            case 'object':
                if (d.is || d.style) l = (d = h(d)).offset()
            }
            h.each(a.axis.split(''),
            function(b, c) {
                var g = c == 'x' ? 'Left': 'Top',
                i = g.toLowerCase(),
                f = 'scroll' + g,
                s = k[f],
                t = c == 'x' ? 'Width': 'Height',
                v = t.toLowerCase();
                if (l) {
                    e[f] = l[i] + (p ? 0 : s - o.offset()[i]);
                    if (a.margin) {
                        e[f] -= parseInt(d.css('margin' + g)) || 0;
                        e[f] -= parseInt(d.css('border' + g + 'Width')) || 0
                    }
                    e[f] += a.offset[i] || 0;
                    if (a.over[i]) e[f] += d[v]() * a.over[i]
                } else e[f] = d[i];
                if (/^\d+$/.test(e[f])) e[f] = e[f] <= 0 ? 0 : Math.min(e[f], u(t));
                if (!b && a.queue) {
                    if (s != e[f]) q(a.onAfterFirst);
                    delete e[f]
                }
            });
            q(a.onAfter);
            function q(b) {
                o.animate(e, j, a.easing, b &&
                function() {
                    b.call(this, r, a)
                })
            };
            function u(b) {
                var c = 'scroll' + b,
                g = k.ownerDocument;
                return p ? Math.max(g.documentElement[c], g.body[c]) : k[c]
            }
        }).end()
    };
    function n(b) {
        return typeof b == 'object' ? b: {
            top: b,
            left: b
        }
    }
})(jQuery);

Open in new window

0
Comment
Question by:jeremyBass26
  • 5
  • 2
7 Comments
 
LVL 16

Assisted Solution

by:sh0e
sh0e earned 2000 total points
ID: 22665850
Quite the beast to refactor, especially for a help forum.  At the risk of sounding greedy, I think what you are asking for help with may be a bit too much, and is why there is so little attention.  To optimize and reorganize any code is already quite a large job, and can be subjective.
It's a little bit like looking for a needle in a haystack, where the definition of a haystack and needle is unclear, and nobody would care even if you found the needle.

All questions are important, including yours, don't get me wrong.  But, you should probably be more specific in your question (of what you want), and ask for things in smaller pieces.

Here are some suggestions that I have for your code.
Take what you have and make it a plugin.
You may be reinventing the wheel a bit here.  There is a mousewheel plugin for jQuery.
Give it comments and more meaningful variable names. (Refactor it)
Use jQuery more, like instead of addEventListener you should use bind.
0
 
LVL 4

Author Comment

by:jeremyBass26
ID: 22669477
Thanks for the help... a few ideas to get me going is always a great way to start... thank you
jeremyBass
0
 
LVL 4

Author Comment

by:jeremyBass26
ID: 22672753
So I did find that plugin (below)... bit long like mine and I still need to tell it to move up or down the page...

>>>you should probably be more specific in your question (of what you want), and ask for things in smaller pieces
:-) this is the small piece of the much lager script... but I guess a smaller piece would be

>>>like instead of addEventListener you should use bind.
um... :-)
this

if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);

would be this??
$().bind('DOMMouseScroll', wheel, function(e){ false});

using bind in this manor is new to me... I've only used it for click before... :-/


>>>Take what you have and make it a plugin.
Never done that before and could use any help there you could spare...

/////////////////////
//////////////In short
/////////////////////

I'm  open to ideas... I'm not set on anything more then improving the scroll function of the bigger script... so any ideas are welcomed... thank you again for the help...

/**
 * 
 * credits for this plugin go to brandonaaron.net
 * 	
 * unfortunately his site is down
 * 
 * @param {Object} up
 * @param {Object} down
 * @param {Object} preventDefault
 */
  /** 
18      * Apply the mousewheel event to the elements in the jQuery object. 
19      * The handler function should be prepared to take the event object 
20      * and a param called 'delta'. The 'delta' param is a number 
21      * either > 0 or < 0. > 0 = up and < 0 = down. 
22      * 
23      * The pageX, pageY, clientX and clientY event properties 
24      * are fixed in Firefox. 
25      * 
26      * @example $("p").mousewheel(function(event, delta){ 
27      *   if (delta > 0) 
28      *     // do something on mousewheel scroll up 
29      *   else if (delta < 0) 
30      *     //do something on mousewheel scroll down 
31      * }); 
32      * 
33      * @name mousewheel 
34      * @type jQuery 
35      * @param Function handler A function to call when onmousewheel fires. Should take two params: event and delta. 
36      * @cat Plugins/Mousewheel 
37      * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net) 
38      */ 
 
jQuery.fn.extend({
	mousewheel: function(up, down, preventDefault) {
		return this.hover(
			function() {
				jQuery.event.mousewheel.giveFocus(this, up, down, preventDefault);
			},
			function() {
				jQuery.event.mousewheel.removeFocus(this);
			}
		);
	},
	mousewheeldown: function(fn, preventDefault) {
		return this.mousewheel(function(){}, fn, preventDefault);
	},
	mousewheelup: function(fn, preventDefault) {
		return this.mousewheel(fn, function(){}, preventDefault);
	},
	unmousewheel: function() {
		return this.each(function() {
			jQuery(this).unmouseover().unmouseout();
			jQuery.event.mousewheel.removeFocus(this);
		});
	},
	unmousewheeldown: jQuery.fn.unmousewheel,
	unmousewheelup: jQuery.fn.unmousewheel
});
 
 
jQuery.event.mousewheel = {
	giveFocus: function(el, up, down, preventDefault) {
		if (el._handleMousewheel) jQuery(el).unmousewheel();
		
		if (preventDefault == window.undefined && down && down.constructor != Function) {
			preventDefault = down;
			down = null;
		}
		
		el._handleMousewheel = function(event) {
			if (!event) event = window.event;
			if (preventDefault)
				if (event.preventDefault) event.preventDefault();
				else event.returnValue = false;
			var delta = 0;
			if (event.wheelDelta) {
				delta = event.wheelDelta/120;
				if (window.opera) delta = -delta;
			} else if (event.detail) {
				delta = -event.detail/3;
			}
			if (up && (delta > 0 || !down))
				up.apply(el, [event, delta]);
			else if (down && delta < 0)
				down.apply(el, [event, delta]);
		};
		
		if (window.addEventListener)
			window.addEventListener('DOMMouseScroll', el._handleMousewheel, false);
		window.onmousewheel = document.onmousewheel = el._handleMousewheel;
	},
	
	removeFocus: function(el) {
		if (!el._handleMousewheel) return;
		
		if (window.removeEventListener)
			window.removeEventListener('DOMMouseScroll', el._handleMousewheel, false);
		window.onmousewheel = document.onmousewheel = null;
		el._handleMousewheel = null;
	}
};

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Author Comment

by:jeremyBass26
ID: 22673922
Also... this (code in code area) works great for saying the wheel is going up or down... which is just the top of the stuff above... but... it does not have the means to move the "page" (or ".SA") up and down which is what I need to do...

So I guess what I'm saying is that if someone knows a better way to move up or down the page only replacing the alert("up"); that would solve this question....  that would be I think the best course... then I can try rewriting in a more jquery way... Hope that was clear ... if not please just ask me and I'll restate in a different way...thanks for the help...
jeremyBass
function handle(delta) {
    if (delta < 0) {
alert("down");
    } else {
alert("up");
    }
}
function wheel(event) {
    var delta = 0;
    if (!event) event = window.event;
    if (event.wheelDelta) {
        delta = event.wheelDelta / 120;
        if (window.opera) delta = -delta;
    } else if (event.detail) {
        delta = -event.detail / 3;
    }
    if (delta) handle(delta);
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}
 
if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;

Open in new window

0
 
LVL 4

Accepted Solution

by:
jeremyBass26 earned 0 total points
ID: 22675315
Well I figured a solution to my issue.... not a script but simply a div, transparent img, and css... the major issue was (which I should have said) that I could not use the mouse wheel to scroll the page while over flash... so the solution was to float the img over flash so I had "traction" with the mouse wheel... I'm sure I didn't explain that well like I didn't with my question but thats all part of learning lol...

thanks for the help...
jeremyBass
0
 
LVL 16

Expert Comment

by:sh0e
ID: 22676765
No need to be sorry, and it's not your fault.
I was just explaining why you might not get the help you need.
BTW, that's a clever workaround.
0
 
LVL 4

Author Comment

by:jeremyBass26
ID: 22679156
Thanks... funny what you think of when you have no choice but to fix something... still one issue with it but should be easy... anyways you can check it http://hellscanyonsportfishing.com/  not fully done but almost... thanks again for the help
jeremyBass
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month16 days, 17 hours left to enroll

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question