Jonas
Jonas

Reputation: 128777

How to run a JavaScript function when the user is visiting an hash link (#something) using JQuery?

I have a webb application at http://example.com/app and I would like to show a form if the user is visiting http://example/app#add-item.

Is there any way I can use a jQuery script to add this functionallity?

My current jQuery script already has a structure like this:

$(document).ready(
    function() {
        $('#search').keyup(
            function() { ... }
        );
    }
)

How can I show a form using someting like this:

$(document).ready(
    function() {
        $('#search').keyup(
            function() { ... }
        );

        $('#add-item').visit( // .visit probably doesn't exist
            function() { content.innerHTML = myForm; }
        );
    }
)

Upvotes: 1

Views: 368

Answers (3)

ssapkota
ssapkota

Reputation: 3302

$(document).ready(
    function() {
        $('#search').keyup(
            function() { ... }
        );

        $('#add-item').click(
            function() { $("#content").html(myForm); }
        );
    }
);

I assume you have a element with id "content" where you want to display the form.

Upvotes: 0

Femi
Femi

Reputation: 64690

Might be able to use the hashchange event, as shown at http://benalman.com/projects/jquery-hashchange-plugin/.

Upvotes: 2

Naftali
Naftali

Reputation: 146302

Here is something I do:

    var hash = (window.location.hash).replace('#', '');
    if (hash.length == 0) {
        //no hash
    }
    else {
        //use `hash`
        //example:
        if(hash == 'add-item'){
             //do something
        }
    }

Upvotes: 3

Related Questions