I have a button which has :
onclick
Example
<input id='b1' type='button' value='go' onclick='alert("0")';'/>
$("#b1").on('click',function (){alert('1');});
$("#b1").on('click',function (){alert('2');});
$("#b1").on('click',function (){alert('3');});
It alerts 0,1,2,3.
But How can I insert new onclick
at "custom index" ?
For example , Lets say that there is a function which I want to insert between the alerts of 1,2 .
How can I do that ?
p.s :
Controlling the inline onclick
is not a problem , I just take its attr
and execute it later.
The problem for me is the .on
registers. I thought about $.data("events")
But it ws deprecated and should be used only for debug proposes. ( also - it's syntax has changed).
JSBIN
I wrote a small jQuery plugin that claims to do this.
Use on
jQuery function (that is actually rewritten by my plugin) like below:
<script src="path/to/jQuery.js"></script>
<script src="path/to/jQuery-priorityze.js"></script>
<button id="go">Test 1</button>
<script>
var $go = $("#go");
$go.on('click', 5, function () { console.log('nice'); });
$go.on('click', {priority: 4}, function () { console.log('a'); });
$go.on('click', 6, function () { console.log('plugin?'); });
$go.on('click', 1, function () { console.log('Is'); });
$go.on('click', 3, function () { console.log('this'); });
$go.on('click', 2, function () { console.log('not'); });
<script>
If priority is not provided the plugin will choose the priority of the event incrementing 1
to the latest provided priority.
I was hoping to get a solution without changing existing structure
Include my plugin in the page and use this:
$("#b1").on('click', function (){alert('1');}); // 1
$("#b1").on('click', function (){alert('2');}); // 2
$("#b1").on('click', function (){alert('3');}); // 3
$("#b1").on('click', 1.5, function (){alert('4');}); // 1.5
// 0 -> 1 -> 4 -> 2 -> 3
// seems that onclick attribute is stronger that .on
function topPriority() {
alert('top priority');
}
Setting 1.5
priority puts the last handler between the first (1
) and second (2
) one.
Like I commented onclick
attribute is stronger than on
jQuery function.
UPDATED JSBIN
Checkout the source code here on Github and check the tests.
Don't forget to star fork it: https://github.com/IonicaBizau/jQuery-prioritize :-)
The plugin is compatible with jQuery >= 1.8.x
and it uses $._data($el[0]).events
like it was described here.
Do you want to contribute to this project? Great! Follow the following steps:
I will try to merge the pull requests as fast I can.
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