views:

49

answers:

2

Seriously. The simplest jQuery code ever simply isn't working.

<script type="text/javascript">
$(document).ready(function(){

 $('.codeswitcher').click(function() {
        alert("You clicked it");
 });

});
</script>

And then, in my page structure, I have this:

<div class="codeswitcher">
<img src="http://mysite.com/images/codeswitcher.png" alt="codeswitcher">
</div>

It's just a 32x32px image. And you can click it. But nothing happens! :( I've also changed my jQuery selector to .codeswitcher img and div.codeswitcher, but still nothing.

I have other jQuery code also running on the page just fine. What's going wrong?

Thanks!

Jack

+1  A: 

First, you're not crazy, your example code works: http://jsfiddle.net/c3e6X/

Check to see if you have a JavaScript error before this code runs, just open the console and look.

If it's created dynamically, e.g. AJAX then you should use .live() instead, like this:

$(function() {
  $('.codeswitcher').live('click', function() {
    alert("You clicked it");
  });
});
Nick Craver
jsfiddle looks like a neat site! Thanks for confirming, by the way.And the problem is that it was generated by Ajax. Thanks for letting me know, I didn't know you had to select it differently in a situation like that!
Jack Webb-Heller
Can't accept your answer for another 9 minutes though... but, thanks :)
Jack Webb-Heller
@Jack - The selector runs **at that time**, and attaches a `click` handler to the elements it found...this just wasn't there to find :) for a bit more explanation: `.live()` listens for the event to bubble up to `document`...since new and old elements bubble events the same way, it just doesn't matter when they were added.
Nick Craver
A: 

Your code looks absolutly fine and is working. There is maybe another Javascript error somewhere else on your site or for some reason, jQuery isn't loaded correctly at the point you are executing this piece of code.

jAndy