vbenitogo vbenitogo - 6 months ago 10
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.
slider.animate({
"right": (dist)
}, 600);

});
};

init();‚Äč


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.

Thanks

Answer

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) {
    e.preventDefault();

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

    //animate to the div id.
    slider.animate({
        "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).