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—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—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?
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
Wrap the code inside
$(function (){
})
And you have the working code
$(function (){
$(".todoitem").click(function() {
alert('Item selected');
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With