NoNameIamLame NoNameIamLame - 4 years ago 139
Javascript Question

Getting class or id values on mouseDown

I want to stop default right click menu and make my own one, but before that on mouseDown I need to get class and id data so after when I check is it right click to open menu with specific data for that class name or id.

Now the problem is that the only thing I get for id and class values are undefined even tho I have both className and Id?

HTML:

<div class='someClassName' id='someId'>someText</div>
<div class='pss'><div class='ps' id='pS123'>Some data</div></div>


JS:

document.oncontextmenu = function() {return false;};

$(document).mousedown(function(e){
var id = $(this).attr('id');
var clas = $(this).attr('class');
console.log("id: "+id+" / class: "+clas);
if(e.button==2){
console.log("id: "+id+" / class: "+clas);
if(id=="" && clas==""){
console.log("id: "+id+" / class: "+clas);
}else{
if(clas=="someClassName"){
$(document).mousemove(function(event){
var xPos = event.pageX;
var yPos = event.pageY;
console.log('xPos: '+xPos+'px; / yPos: '+yPos+'px;');
});
}
}
return false;
}
return true;
});


EDITED: $('body') to $(document) but I have same problem, but when I try to get some data by click on document I do get what element I clicked on by I need to check that with right click.

Answer Source

The problem was that $(this) was returning the body tag because that is what you attached the click handler to. You can access what was really clicked with e.target. See new snippet.

$('body').contextmenu(function(e) {
        var id = $(e.target).attr('id');
        var clas = $(e.target).attr('class');
        console.log("id: "+id+" / class: "+clas);
        if(id=="" && clas==""){
            console.log("id: "+id+" / class: "+clas);
        }else{
             if(clas=="someClassName"){
                $(document).mousemove(function(event){
                    var xPos = event.pageX;
                    var yPos = event.pageY;
                    console.log('xPos: '+xPos+'px; / yPos: '+yPos+'px;');
                });
             }
        }
        return false; 
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='someClassName' id='someId'>someText</div>
      <div class='pss'><div class='ps' id='pS123'>Some data</div></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download