Execute javascript function on anchor click, but the code must run on the page opened by that anchor

StackOverflow https://stackoverflow.com/questions/23595344

  •  20-07-2023
  •  | 
  •  

Question

Is this behaviour possible? I would need the code that is inside on click event handler, to be executed on the new HTML page that is opened by that navigation link.

I've put up a small fiddle to better illustrate what I want to achieve. http://jsfiddle.net/hWEpL/4/

Here is the jQuery for scrolling:

        $.fn.scrollView = function () {
            return this.each(function () {
                $('html, body').animate({
                    scrollTop: $(this).offset().top
                }, 1000);
            });
        }

        $('#link-3').click(function (event) {
            event.preventDefault();
            $('.section-3').scrollView();
        });

Let's assume that the fiddle is Home Page. When clicking on Section-3, the page scrolls to section-3.

Now, let's say the we are on the second page(about) and we click on Section-3. I would like to have Home Page opened, and that the page is scrolled to section-3.

The thing is that I don't want this behaviour when the Home Page is opened, I only need it when someone is on the other pages and clicks on Section-3

Was it helpful?

Solution

You can use Fragment identifiers. So in the about page for example, you would link to the home page with homepage.htm#section-3 and in homepage.htm, you would include just like the code you have included but add

var hash=location.hash
if(hash){
var el=$('.'+hash.substr(1))
  if(el)
    el.scrollView();
}

in the onLoad. Here we use the fragment as a way to tell the page which element to go to.

http://jsfiddle.net/hWEpL/5/ This is the updated jsfiddle (with simulated hashed location being already followed using

location.href="#section-3" //simulate named links. do not include this in your code

Moving forward, perhaps semantically, you could use ID instead of class, to use the default behaviour of fragments if javascript is disabled, but then you have to place this piece of code to actually prevent the default behaviour (and allow the animation to occur) as stated in https://stackoverflow.com/a/3659116/1480215

setTimeout(function() {
  if (location.hash) {
    window.scrollTo(0, 0);
  }
}, 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top