Search code examples
jqueryhashchange

jQuery hashchange issue


I have a simple code in three forms one is not working and another two forms work BUT I want to understand that what causes two methods to work.

Please have a look at simple code. http://jsfiddle.net/NjWAz/ (It doesn't slide properly).

While if only div ids are appended then it slides properly. http://jsfiddle.net/NjWAz/2/ (here is my first question that what causes it to work actually? How just changing ids make it work?)

And in another form. http://jsfiddle.net/NjWAz/1/ (It works too, so here is my second question that by preventing default behavior how its made to work.. and what is default behavior which is breaking its working at http://jsfiddle.net/NjWAz/)


Solution

  • The reason it doesn't work for the first example is because you're not preventing the default behaviour of the link. When you create a link with a hash tag (e.g. #two) the link will move the page to the element with the same ID parameter (e.g. <div id="two">)

    Because in the first example, you have a link pointing to #two and you have an element with the same id, <div id="two">, it jumps to the element, then continues to execute your jQuery animation, causing it to appear as if it's moving to #three.

    The second example, the href attribute value doesn't match any HTML element, so it works fine.

    On the third example, you're preventing the default behaviour of the link, so it works.

    You could either prevent the default behaviour using the method in your third example, or you can just put return false; at the end of your click event:

    $( function () {
        $(".clickIt a").click( function () {
            var linked = $(this).attr("href");
            var pos = $(linked).position();
    
            $(".clickSlider").stop().animate({left: -pos.left,}, 500 );
    
            return false;
        });
    });​​​​​
    

    Hopefully my explanation makes sense :)