How to change the order of events when they are set via the .on
method?
It turns out to change the order only for directly installed handlers
Example: https://jsfiddle.net/Bozon/3gcea2q1/8/
I was expecting this output:
click # 4 = # div1
click # 3 = # div1
click # 2 = # div1
click # 1 = # div1
I need this to reverse the order of events for a dynamically created block:
- The handler for the dynamic block is created in advance
$('body').on("click", 'div2', function(){ });
- Then another handler is created
$('body').on("click", 'div2', function(){ });
- Then a block is created
$("body").prepend('<div id="div2">Text div2</div>');
- How to make the second handler run ahead of the first?
Example: https://jsfiddle.net/Bozon/3gcea2q1/11/
I need 'click # 2' to be displayed first
Example code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<style>
#div1 {background-color:red;width:150px;height:50px;}
#div2 {background-color:yellow;width:150px;height:50px;}
#output {margin:15px;width:50%}
</style>
</head>
<body>
<div id="div1">CLICK HERE ( div1 )</div>
<script>
$(document).ready(function() {
var selector = '#div2';
$('body').on("click", selector, function(){
output("click #1 = " + selector);
});
$('body').on("click", selector, function(){
output("click #2 = " + selector);
});
$(selector).click(function() {
output("click #3 = " + selector);
});
$(selector).click(function() {
output("click #4 = " + selector);
});
$("body").prepend('<div id="div2">CLICK HERE ( div2 )</div>');
$('body').on("change load", selector, function(){
output("load el with selector = " + selector); // does not work for some reason, then it will use "mouseover" event
});
$('body').one("mouseover", selector, function(){
var elem = $(selector).get(0);
var all_events = $.data(elem, 'events') || $._data(elem).events;
if( typeof all_events !== "undefined" ){
all_events['click'].reverse();
}
else {
output("all_events is undefined");
}
//output( all_events['click'] );
});
function output(text) {
console.log(text);
$("#output").html(function(i, h) {
return h + text + "<br />";
});
}
});
</script>
<div id="output"></div>
</body>
</html>