Jump to content

Send function to linked page?


eiranix

Recommended Posts

You can add a query string or a hash to the URL you're calling and get data from location.search or location.hash.

 

For example:

<a href="page2.html?link1">Link 1</a><a href="page2.html=link2">Link 2</a>
switch(location.search) {    case "?link1":        alert("Link 1 was clicked");        break;    case "?link2":        alert("Link 2 was clicked");        break;}
Edited by Ingolme
Link to comment
Share on other sites

OK so what I ended up doing to keep the script small was to remove the ? from the loaction.search and make it a variable that matches the id's of my elements.

 

The page has several elements using class1. Depending on which link takes you there it will cause one of the elements to be class2 on load.

window.onload=function() { var id = location.search.substr(1);document.getElementById(id).className = 'class2';  } 
Link to comment
Share on other sites

Ok this might sound like a stupid question but, how would I go about using the function as above at the same time as linking to a location on the page?

 

When I try using location.hash in place of location.search, the function will work but the location link does not...

Link to comment
Share on other sites

Here's what's happening: When loading the current page's URL with a hash the page does not reload. Since the page does not reload, the window.onload method isn't called. There's a hashchange event to deal with this.

 

You can change your code to the following:

window.onload = doSomething; // Call the function if the page is loading for the first timewindow.onhashchange = doSomething; // Call the function when the #hash changesfunction doSomething() {    var id = location.hash.substr(1);    document.getElementById(id).className = 'class2'; }
Link to comment
Share on other sites

I am linking from a different page so that's not actually a problem. I've realized my problem is not that it isn't working, but that it's doing it in the wrong order...

When I use a #linked page it is loading the page and going to the location first, then it's doing the change class function.

The new class is expanding content on the page (along with a 0.5sec transition) which leaves the page in the wrong position if it is done to things low enough in the layout.

 

How would I tell it to wait till after the expanding transition has finished before the page moves to the hash location?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...