vbenitogo vbenitogo - 2 years ago 61
jQuery Question

jQuery animate 'right' position issue

I have a menu that slides through several sections of my Website, right and left.

Originally I had a function 'goto()', which was triggered 'onClick', and the animation worked exactly as expected.

I wanted to clean up the HTML, so I added a bind handler to a click event in a JS file.

var navanchors = $('#navMain a');
var slider = $('#slider');

init = function() {

navanchors.bind('click', function() {

var t = $(this);
var id = t.attr('href');
var dist = $(id).position().left;

//animate to the div id.
"right": (dist)
}, 600);



The left animation seems to work as expected, but the right animation is off. On the first click the animation seems to move twice the expected distance. On a second click it resets without animation.

Please have a look at the issue here: http://jsfiddle.net/Kj4bU/1

I have searched and experimented but am at a loss. Any help would be much appreciated.


Answer Source

You're not preventing the default behavior of the click events you handle from occurring. Since the clicks occur on anchor elements, the browser will try to scroll to the clicked anchor's position during your animation, resulting in the issue you're experiencing.

You can use event.preventDefault() to inhibit this behavior:

navanchors.on("click", function(e) {

    var t = $(this);
    var id = t.attr("href");
    var dist = $(id).position().left;

    //animate to the div id.
        "right": dist
    }, 600);

You will find an updated fiddle here.

(Note the code above uses on() instead of bind(), the former being preferred to the latter since jQuery 1.7).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download