简体   繁体   中英

Convert event listener from jQuery to native Javascript

I want to remove the requeriment of jQuery in my app and I have this piece of code that handles an event related to a element.

So the original code is:

$(window.document).on('contextmenu', '.main td.active', function(e) {
    $("#context-menu").hide().css({
        left: e.pageX,
        top: e.pageY
    }).show();
    e.preventDefault();
});

The migration is the following:

window.document.addEventListener('contextmenu', function(e) {
    var el = document.getElementById("context-menu").style;
    el.left = e.pageX,
    el.top = e.pageY,
    el.display = 'block';
    e.preventDefault();
});

The problem is that the event (onContextmenu) is associated just only to the document.body ... then, when is fired, the event.target (mouse right-click) is checked to verify if matches with a .main td.active, instead of associate an event to each element.

(do not confuse with querySelector('.main td.active').addEventListener )

Any idea? Thanks!!

You can define a fn checkTarget() something like the jQuery sizzle one would do in case if you have a CSS selector to find and use querySelectorAll and call that if returns true then the target is your specified selector so execute your fn else do nothing

window.document.addEventListener('contextmenu', function(e) {
    if(checkTarget(this, e.target, '.main td.active')){
        el = document.getElementById("context-menu").style;
        el.left = e.pageX,
        el.top = e.pageY,
        el.display = 'block';
        e.preventDefault();
    }
});

function checkTarget(element, current, search){
   var matches = element.querySelectorAll(search);
   for(var i in matches){
      if(matches[i] === current){
          return true;
      }
   }
   return false;
}

You can also assign the event directly to the target elements using loops. Something like:

jsFiddle

var parents = document.querySelectorAll('.main');
for( var i = 0; i < parents.length; i++ ){
     var target = parents[i].querySelectorAll('td.active');
     for( var j = 0; j < target.length; j++ ){
         target[j].oncontextmenu = function(e){
             e.preventDefault();
             // do stuff
        };
     }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM