dangerChihuahua007
dangerChihuahua007

Reputation: 20915

How can I use javascript to detect an inline link?

Say I have a web page index.html. Suppose the client goes to index.html#section2. This should take the client to the section of the page with a block-level element having a name attribute of section2.

How do I detect this inline link in javascript? Specifically, if the user goes to index.html#section2, I want to run a certain function in javascript.

I am open to using jQuery as well. Thank you!

Upvotes: 0

Views: 86

Answers (2)

Alex
Alex

Reputation: 35407

Do a switch on the window.location.hash property.

switch(window.location.hash) {    
   case '#section1':
      foo();
   case '#section2':
      bar();
}

Note - The hash property is supported in all major browsers.

Edit - @IvanCastellanos is right about the new hashchange event and the lack of support in down-level browsers. If the OP needs to handle this situation then the overhead of the plugin may be necessary - as pointed out in his answer...

Upvotes: 1

Ivan Castellanos
Ivan Castellanos

Reputation: 8252

Use jQuery with this jQuery plugin http://benalman.com/projects/jquery-hashchange-plugin/

Then you can do:

$(window).bind( 'hashchange', function( event ) {
    if(window.location.hash === "#section2"){
        // What you want to do
    }
})

Or if you dont want to use jQuery just use onclick events.

<a href="#section2" onclick="changed()"></a>

JS:

function changed(){
        setTimeout(function(){
                if(window.location.hash === "#section2"){
                    // What you want to do
                }
        })
}
window.onload = changed; // In case user starts on #section2

Upvotes: 2

Related Questions