Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollTo after a href with jQuery / JavaScript

Tags:

html

jquery

I am building a html web page, and the main problem for now is that I do not know how to scroll to a section of page after clicking a new link. What I did was I used the scrollTop jQuery method :

$("#klienti2").click(function(){
    $('.parallax').animate({ scrollTop: windowHeight }, 'slow');
});

and it scrolled the amount of windowHeight from the top of the screen. I choose this method over using navigation with ids, because there is no content at the spot where I need to scroll.

So what I am looking for now is to do the same thing after redirecting to this page from different page. What I tried was :

$("#audio2").click(function(){
    window.location.href = "prew2.html";
    $('.parallax').animate({ scrollTop: windowHeight*2.6 }, 'slow');
});

but now it just redirects to that page without scrolling. Any ideas why? I thought that, fallowing the code, it should href to the location and then animate to the specified location, but it seems to ignore the animate.

like image 869
Oskars Avatar asked Jun 29 '15 13:06

Oskars


2 Answers

From comment: HTML is stateless. Once you change href, anything following is disregarded as the code is unloaded. You need to pass something to the receiving page (e.g. a query string parameter on prew2.html) and react to that instead from inside prew2.html.

The receiving page needs to know whether, or not, to scroll to the intended location. That decision whether to scroll, or not, is made by the caller.

The obvious method is to pass a parameter in the query string. As this code acts just like a bookmark URL, you might as well use a bookmark URL for the task and check for a specific bookmark value:

In your first page the link code would be something like:

$("#audio2").click(function(){
    window.location.href = "prew2.html#doitnow";
});

Of course if that is just a normal anchor, this would do the same:

<a id="audio2" href="prew2.html#doitnow">Click me</a>

In the receiving page the code would be like this:

$(function(){   // Shortcut for DOM ready handler
    if (location.href.indexOf("#doitnow") >=0 ){
        $('.parallax').animate({ scrollTop: windowHeight*2.6 }, 'slow');
    }
});
like image 186
Gone Coding Avatar answered Nov 20 '22 09:11

Gone Coding


Your script tells the Browser to open a new Url on click

window.location.href = "prew2.html";

Now the Browser navigates to this address, stopping all actual scripts and building a new DOM.

$('.parallax').animate({ scrollTop: windowHeight*2.6 }, 'slow');

This code is never reached and will never execute.

like image 29
AbeCodes Avatar answered Nov 20 '22 10:11

AbeCodes