JQuery class selector and hit ()

I'm currently trying to get a warning when something clicks. I can get it to work in jsFiddle, but not in production code:

Example jsFiddle that works (loaded with jQuery 1.5)
HTML (in case jsFiddle is unavailable):

<!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');
});

Example of non-working production:

<!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>

The Safari Inspector indicates that jQuery loads correctly, so this is not a problem. As far as I can tell, these two parts of the code are essentially identical, but the latter does not work. Can anyone see what I did wrong?

+5
source share
2 answers

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

It will work

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

JSfiddle

+18

$(function (){

})

$(function (){

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

})
+2

All Articles