Reputation: 31590
I define the same listener on document.ready
in both an external script file and in-file. I have one in a central external file because I'll always want to perform the delete when clicking an element with class .delete
, but sometimes I also want to do some other stuff.
//script.js
$(document).ready(function(){
$('.delete').click(function(){
//send AJAX delete
});
});
//index.php
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var msg = "Are you sure you want to delete the <?=$item?>'"+$(this).attr("name")+"'?";
if ( confirm(msg) ) {
removeDataTableRow( $(this)... );
}//fi
});
});
</script>
The listener in the external js file fires before the in-file script's listener, but I want the opposite (and I want to cancel the second event from the external file if confirm=false
).
I thought of setting a variable in the in-file script and setting that variable in the external to know the result of the confirm, but the script in the external script still fires first, and as such the variable has not yet been properly defined :/
EDIT: I've read question 282245 which covers event precedence of different listeners, but not for occurrences of the same listener.
Upvotes: 0
Views: 253
Reputation: 35812
Javascript run order is actually pretty simple. Unless you're using asynchronous code (eg. an event handler, and AJAX request, or a setTimeout) code is always ordered sequentially. In other words, the browser starts at the top of the page, runs everything in the first script tag it finds, moves on to the next script tag, etc.
Asynchronous stuff confuses matters a bit, but the general rule (in most libraries at least) is that the first handler to get hooked up runs first. So in this case, your external document.ready handler is going off because it comes earlier on the page than your in-page script tag.
Upvotes: 1