6

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?

2 Answers 2

21

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

Sign up to request clarification or add additional context in comments.

Comments

2

Wrap the code inside

$(function (){

})

And you have the working code

$(function (){

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

})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.