?
Solved

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

Posted on 2008-10-06
7
Medium Priority
?
943 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
DFW AZURE MEETUP TONIGHT FRI 6PM

We will be discussing what Azure Stack is, how does it fit into the suit of offerings that Azure has currently, and where can it fit into your organizations technology stack. We will also be discussing limitations of the platform while covering various applicable scenarios.

 
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

RHCE - Red Hat OpenStack Prep Course

This course will provide in-depth training so that students who currently hold the EX200 & EX210 certifications can sit for the EX310 exam. Students will learn how to deploy & manage a full Red Hat environment with Ceph block storage, & integrate Ceph into other OpenStack service

Question has a verified solution.

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

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)
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

800 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