Konadi
Konadi

Reputation: 192

execute/trigger a script depending on #anchor in url?

I have a central page example.com/info/requirements that contains the requirements to run different applications. By default only the div that shows the requirements for the flagship application is shown, and users can click buttons to switch on/off a different div.

<a id="main-app"></a>
<div id="req-container-main" class="invisible">
    [Requirements are listed here]
</div>
<a id="app2"></a>
<div id="req-container-app2" class="invisible">
    [Requirements are listed here]
</div>
<a id="app2"></a>
<div id="req-container-app3" class="invisible">
    [Requirements are listed here]
</div>
<a id="app4"></a>
<div id="req-container-app4" class="invisible">
    [Requirements are listed here]
</div>

I have a landing page for each of the apps. They contain a link to the requirements page including an anchor, like this example.com/info/requirements#app3

Now I'm looking for a way - using JS/jQuery - that checks for the existence of an #anchor when the page is accessed and can then trigger my openReqDiv('#app3'); function i have in place.

Can anyone please point me in the right direction when, where and how to check for the anchor and trigger my script? Thank you!

Upvotes: 2

Views: 1798

Answers (3)

Martin Gottweis
Martin Gottweis

Reputation: 2739

This thing is called routing. Your approach is rather simple, but no worries. Just do:

var hash = window.location.hash;
switch(hash){
    case '#app2':
        $("#app2").removeClass('invisible');
        break;
}

However, eventually you will want to detect changes to the hash. Just use a plugin such as https://github.com/asual/jquery-address. Another option is to use a framework of some kind(angular, ember...)

Upvotes: 2

James
James

Reputation: 442

You can achieve this with Javascript using the document.location.href method.

Example:

// When the page loads...
$( document ).ready(function() {
    // Check if the hash is in the URL
    if ( document.location.href.indexOf('requirements#app3') > -1 ) {
        // Init your function
        openReqDiv('#app3');
    }
});

You can modify this function and bind it to a window.load event. So as soon as the user lands on the page your function is executed.

Good luck!

Upvotes: 2

Jazi
Jazi

Reputation: 6712

You can check the existance of DOM element by this jQuery solution:

if($('#anchor').length > 0) {
    openReqDiv('#app3');
}

Upvotes: 1

Related Questions