Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery class selector and click()

I'm currently trying to get an alert to happen when something is clicked. I can get it working in jsFiddle, but not in production code:

jsFiddle example that works (jQuery 1.5 loaded)
HTML (in case jsFiddle is inaccessible):

<!DOCTYPE HTML><html><head><title>Test</title></head>
<body> <h1>25 Feb 2011</h1><h3>ABC</h3><ul>
        <li class="todoitem">Test&mdash;5 minutes</li> </ul>
</body></html>

Javascript:

$(".todoitem").click(function() {
alert('Item selected');
});

Non-working production example:

<!DOCTYPE HTML><html><head><title>Test</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
        $(".todoitem").click(function() {
        alert('Item selected');
        });
    </script>
</head>
<body>
<h1>25 Feb 2011</h1><h3>ABC</h3><ul><li class="todoitem">Test&mdash;5 minutes</li></ul>
</body>
</html>

Safari's Inspector indicate that jQuery is being loaded correctly, so that's not the issue. As far as I can tell, these two pieces of code are essentially identical, but the latter isn't working. Can anyone see what I've done wrong?

like image 843
Anonymous Avatar asked Feb 26 '11 07:02

Anonymous


2 Answers

You need to wrap your code in $(document).ready()

This will work

$(document).ready(function(){
        $(".todoitem").click(function() {
            alert('Item selected');
        });
});

JSfiddle does this for you automatically

like image 137
JohnP Avatar answered Oct 18 '22 03:10

JohnP


Wrap the code inside

$(function (){

})

And you have the working code

$(function (){

    $(".todoitem").click(function() {
        alert('Item selected');
    });

})
like image 43
Santosh Linkha Avatar answered Oct 18 '22 03:10

Santosh Linkha