ScrollTo after href with jQuery / JavaScript

I am creating an html page, and the main problem at the moment is that I do not know how to go to the page section after clicking a new link. What I did, I used the jQuery scrollTop method:

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

and she scrolled the number of windowHeight at the top of the screen. I choose this method using navigation with identifiers, because there is no content in the place where I need to scroll.

So now I am looking for the same after redirecting to this page from another page. I have tried:

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

but now it just redirects to this page without scrolling. Any ideas why? I thought that by running the code, it should be tied to the location, and then plunge into the specified location, but it seems to be ignoring the animation.

+5
source share
3 answers

From the comment: HTML is idle. As soon as you change href, none of the following is taken into account when downloading the code. You need to pass something to the receive page (for example, the query string parameter on prew2.html ) and respond to it instead inside prew2.html .

The receiving page should know whether to scroll or not show the desired location. This decision, whether or not to scroll, is made by the caller.

The obvious method is to pass the parameter in the query string. Since this code acts just like the bookmark URL, you can also use the bookmark URL for the task and check the specific value of the bookmark:

On the first page, the link code will look something like this:

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

Of course, if it is a regular anchor, it will do the same:

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

On the reception page, the code will look like this:

 $(function(){ // Shortcut for DOM ready handler if (location.href.indexOf("#doitnow") >=0 ){ $('.parallax').animate({ scrollTop: windowHeight*2.6 }, 'slow'); } }); 
+5
source

Your script tells the browser to open a new URL when clicked

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

Now the browser moves to this address, stopping all actual scripts and creating a new DOM.

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

This code is never reached and will never be executed.

+3
source

A place outside the original click operator and on the page to which you are switching.

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

A simple if statement will check and apply the changes when you reach this URL

0
source

All Articles