jQuery's "on" and "off" in pure native javascript - Stack Overflow

I'm looking for a way to represent the "on" and "off" capabilities of jQuery i

I'm looking for a way to represent the "on" and "off" capabilities of jQuery in pure JavaScript code.

For example:

jQuery("my_selector_here").on("click", function(){
     // some code here...
})

Should be represented in the most (total) accurate way, something like:

myobj.fn.on = function(){
     // pure javascript code here...
}

Thanks in advance!

I'm looking for a way to represent the "on" and "off" capabilities of jQuery in pure JavaScript code.

For example:

jQuery("my_selector_here").on("click", function(){
     // some code here...
})

Should be represented in the most (total) accurate way, something like:

myobj.fn.on = function(){
     // pure javascript code here...
}

Thanks in advance!

Share Improve this question asked Nov 13, 2014 at 13:35 TheCuBeManTheCuBeMan 2,4934 gold badges27 silver badges41 bronze badges 6
  • 2 Have you tried just looking at the jquery.js and doing a find? – C Bauer Commented Nov 13, 2014 at 13:37
  • 4 on is an event listener, so check out AddEventListener – DannyTheDev Commented Nov 13, 2014 at 13:37
  • 1 @Jai i.imgur./OpFcp.jpg – Rory McCrossan Commented Nov 13, 2014 at 13:39
  • @TheCuBeMan HaHaHa so you love it satan....;) – Jai Commented Nov 13, 2014 at 13:43
  • @Archer I don't think you can add event listeners to a collection without looping over the elements. And I'd highly remend using addEventListener over onclick. – pawel Commented Nov 13, 2014 at 13:47
 |  Show 1 more ment

1 Answer 1

Reset to default 6

The most native approach is using the DOM's Element.prototype.addEventListener method. Which looks pretty straight forward like

elem.addEventListener('click', function( event ) {
}, false);

That is, beside some other magic, what jQuery will call underneath. The biggest issue libraries deal with, is that old'ish Internet Explorer had a different syntax for adding events on Elements. Those used the elem.attachEvent method, which had some slight differences.

Naively spoken, we could just add to the Elements.prototype. For instance

Element.prototype.on = function( name, callback ) {
    this.addEventListener( name, callback, false );
};

..and then we can use it like

document.body.on('click', function() {
    // code
});

Ref.: addEventListener, jQuery .on

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744967336a4603760.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信