I'm trying to run some jQuery code when I click a button, but I can't make even the most simple example work.
My jQuery code is this:
<script src="scripts/jquery-1.4.1.js"></script>
<script>
$('#btn').click(function() {
alert("Hello");
});
</script>
and my html looks like this
<div>
<input id="btn" type="button" value="button" />
</div>
but when I click the button nothing happens.
wrap your code inside a document.ready function
$(function(){
$('#btn').click(function() {
alert("Hello");
});
});
or put your script code right before the end of the body tag
You need to wait for the elements to be available the dom on page load before binding event handlers
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