tags:

views:

34

answers:

4

Hi - I'm learning jQuery and can't figure this out:

Here's the HTML

<a id="myid" name="myid" href="stub">click here</a>

and the jquery snippet:

 $("#myid").click(function() {
    alert('Hello from click');
 });

Yet when I click on the link no alert displays. Something basic no doubt, What could I be doing wrong?

Thanks

+5  A: 

Your code needs to be in a document.ready handler so it binds the click after the anchor itself is available in the DOM, like this:

$(function() {
  $("#myid").click(function(e) {
    alert('Hello from click');
    //stop the link from going to it's destination here if you need to using
    //e.preventDefault();
    //or:
    //return false;
  });
});

If it's not like this or at the very least after the element in the page, the $("#myid") selector won't find any elements...so it won't bind an onclick handler to anything.

Nick Craver
You'll probably also want to return false to avoid navigating away to `stub`
Stefan Kendall
@Stefan - Yes very true, *if* that's your goal :) Keep in mind there are lots of cases you want to do something and still leave the page afterwards as well :)
Nick Craver
+1 for nailing it much better than me :)
alex
Yes, I should have included that I had it in document.ready (of course). I tried return false and preventDefault() with no luck either.
nullone
@nullone - Do you have a link to the page? It's possible you have an error including the jQuery library itself.
Nick Craver
A: 

This code works for me exactly as is. It then redirects to "stub", but that could be resolved with a return false in the click function.

Dustin Laine
A: 

you can also put a pound (#) in your href in your a tag like this

<a id="myid" name="myid" href="#stub">click here</a>

so even without return false in your jquery code, it will not redirect to anything.

rob waminal
A: 

I figured it out, file this under "learning jQuery".

The hyperlink html was being loaded into a div via load() by clicking on a button after the document had loaded.

Fine, but the problem was that I was binding the event handler to the hyperlink before the element was created. Having used inline onlcick() for so long, it took me a while to figure it out the jQuery/Ajax way.

Thanks for the suggestions.

nullone