javascriptjquerypage-jump

How can I achieve "jumps" with jquery?


I am developing a website that loads different pages depending on what menu icon a user clicks. A friend and I wrote this javascript function:

function loadPage(targetURL){
    $.get( targetURL, function( data ) {
    document.getElementById("placeholder").innerHTML=data;
    window.scrollTo(0,0);
    });
}

And the menu icons are coded like this:

<img src="images/some_icon.png" title="Some Page" onclick="javascript:loadPage('pages/somePage.php')"/>

It works great except if trying to jump to a particular div id. For example,

<img src="images/some_icon.png" title="Some Page" onclick="javascript:loadPage('pages/somePage#someLocationOnPage.php')"/>

Taking out the .scrollTo(0,0) doesn't solve the issue. I put that line in to ensure that the page is scrolled all the way up when changing pages (Otherwise, if you were in the middle of the page and clicked a menu icon, the new page would display in the middle of the page).

What have I missed? How can I get the link to jump to a div id?


Solution

  • The two URL's are not different. The one with the bookmark just gets the same HTML code. Since you are not telling the browser to go to a specific bookmark, it should display the same information. (Unless your server sends different info for that link, of course)

    I guess you'd have to manually move the view to the bookmark you want.

    function loadPage(targetURL, targetID){
        $.get( targetURL, function( data ) {
            document.getElementById("placeholder").innerHTML=data;
            if(targetID && $("#"+targetID).length != 0){
                $(document).scrollTop($("#"+targetID).offset().top);
            } 
            else {
                window.scrollTo(0,0);
            }
        });
    }
    

    And then give the ID for the target as another parameter. If that's not possible, you can also search for # in the url and find the ID/ or anchor.