<html>
<head>
<script src="../jquery.js" type="text/javascript"> </script>
<script type="text/javascript">
$(".demo").click(function() {
alert("JavaScript Demo");
});
</script>
</head>
<body>
<p class="demo">a paragraph</p>
</body>
</html>
Why did not the click function response?
Thanks.
You are running the code too early. You should wrap it in a document-ready handler, which jQuery supports thus:
$(function() {
$(".demo").click(function() {
alert("JavaScript Demo");
});
// Put other initialisation code here...
});
This will ensure that your code runs after the document is loaded.
You are running the code when the DOM isn't ready yet.
There are 2 solutions:
Add the Javascript after the elements it affects. Preferably as far down the page as possible.
Doing this is not always possible, but it is suggested by YUI for speeding up your website.
<html>
<head>
<script src="../jquery.js" type="text/javascript"> </script>
</head>
<body>
<p class="demo">a paragraph</p>
<script type="text/javascript">
// This is after .demo
$(".demo").click(function() {
alert("JavaScript Demo");
});
</script>
</body>
</html>
Wrap your script in a doc ready. In jQuery there are several forms. The quickest to type is $(function() { ... });:
<html>
<head>
<script src="../jquery.js" type="text/javascript"> </script>
<script type="text/javascript">
// doc ready
$(function() {
$(".demo").click(function() {
alert("JavaScript Demo");
});
});
</script>
</head>
<body>
<p class="demo">a paragraph</p>
</body>
</html>
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