click event handler on add button is not working if i do following(click event defined in add.js and ready event is present in index.js).
If i put click event handler and ready handler in index.js, click event works (alert popup).
Please help me.
Note: #add_button is a static button ( present in index.php, not a dynamic div, i tried live instead of click but that doesn’t work too).
This doesn’t work
<script src="js/index.js" type="text/javascript"></script>
<script src="js/add.js" type="text/javascript"></script>
index.js
$(document).ready(function() {
//code
});
add.js
$('#add_button').click(function(event){
alert('hello');
});
this works if add.js content is directly put into index.js ?
$(document).ready(function() {
//code
$('#add_button').click(function(event){
alert('hello');
});
});
It’s not because they’re in different files. It’s because the code hooking up the
clickevent is running too soon. By putting theclicksetup insideready, you’re making it wait until “DOM ready”. When it’s not in thereadyhandler, it runs right away. If that code is above the#add_buttonelement, the element won’t exist yet, and the handler won’t be hooked up.You have two options:
Just put the
scripttag foradd.jsbelow the element(s) it uses in the markup, e.g.:Then when the browser runs
add.js, the element will exist. Thescripttag could even be immediately after the button, but I’d usually recommend the end of the file (e.g., just before the closing</body>tag), as indeed do the YUI folks.Use another
readyhandler inadd.js(you can have as many as you like):