Converting an event listener from jQuery to native Javascript

I want to delete a jQuery query in my application, and I have this piece of code that handles the event associated with the element.

So, the source code:

$(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 as follows:

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 only associated with document.body ... then when it is fired, event.target (right-click) checks if matches match .main td.active, and not bind the event to every element.

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

Any idea? Thanks!!

+4
source share
2 answers

fn checkTarget() - jQuery sizzle, CSS-, querySelectorAll, , true, , fn

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;
}
+1

. - :

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
        };
     }
 }
+1

Source: https://habr.com/ru/post/1608362/


All Articles