1

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; }
        );
    }
)
Jonas
  • 121,568
  • 97
  • 310
  • 388

3 Answers3

3

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
        }
    }
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • 1
    +1 - Just a minor nitpick; I would do `if(hash) { // since empty string == falsy } ` to save valuable bytes. – karim79 May 25 '11 at 16:38
  • @karim79, doesn't `hash.length` take the same amount of time? and it also accounts for if the url is: `example.com/#` – Naftali May 25 '11 at 16:39
  • It's not about the performance but about the smaller footprint (but again, just a nitpick! :) Since you're replacing the hash character with nothing, the example URL in your comment should still yield a falsy result. – karim79 May 25 '11 at 16:40
  • 1
    @karim -- pick away, just not my nose – Naftali May 25 '11 at 16:41
2

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

Femi
  • 64,273
  • 8
  • 118
  • 148
0
$(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.

ssapkota
  • 3,262
  • 19
  • 30
  • But this is only working if the user is clicking on a `#add-item` link and not if the user is visiting that url, or am I wrong? – Jonas May 25 '11 at 16:40
  • yea, If that is the case you need to check the hash, on onload event of the Page. Which is already answered. – ssapkota May 25 '11 at 16:43