th3rion
th3rion

Reputation: 183

Go to anchor on page load depending on clicked link

Hi I have a code which takes me to anchor on page load.

What if I have menu where links are different anchors. When I click link1 it loads a page and takes me to anchor1 and when I click link2 it takes me to the same page but to anchor2?

$(function(){
    $('html, body').animate({
        scrollTop: $('.anchor1').offset().top
    }, 1000);
    return false;
});

Upvotes: 0

Views: 61

Answers (1)

Mudassir Hasan
Mudassir Hasan

Reputation: 28741

This looks like passing value from one page containing menu links to other page containing anchors using javascript.

There are many ways of doing this one of them being using cookies. Let say you have drop down on menu page from which you pass value of anchor

<select id="menuselect">
  <option value=".anchor1"> Anchor1 </option>
  <option value=".anchor2"> Anchor2 </option>
  <option value=".anchor3"> Anchor3 </option>
</select>

Now in Menupage js

$(#menuselect).change(function(){
  //Store value of anchor class to passed to next page from option sel;ected in menu dropdow in cookie
  $.cookie('anchorclass',$(this).val());

  $(window).load('AnchorPage.htm'); // Go to page containing anchors
});

Now in anchor page you can check for value stored in cookie and use your code to got to that anchor on page load.

AnchorPage.htm

$(document).ready(function(){
  var classofAnchor = '.anchor1'; //Set default target anchor class
  if($.cookie('anchorclass') ! = null)
  {
    classofAnchor = $.cookie('anchorclass'); // Fetch value from cookie
  }
  $('html, body').animate({
        scrollTop: $(classofAnchor).offset().top
    }, 1000);
});

Upvotes: 1

Related Questions