Reputation: 1695
I am using context menu of jquery in a page, but I am not able to pick up the id of particular div when I click the right button on this div.
Upvotes: 0
Views: 3948
Reputation: 179046
I am assuming you mean "right-click on the div"
This will work on any <div>
on the page:
//bind the event to the document, using the delegate of "div"
$(document).on('mousedown', 'div', function (e) {
//check that the right mouse button was used
if (e.which === 3) {
//log the [id] attribute of the element that was right-clicked on
console.log($(this).attr('id'));
}
});
Upvotes: 0
Reputation: 5298
Here is an example.
HTML::
<div id="buttondiv">
<button type="button">Click Me!</button>
</div>
jquery code:
$(document).ready(function(){
$("button").on("mousedown", function(e){
if(e.which == 3){
var divId = $(this).parent().attr("id");
console.log(divId);
}
})
});
Upvotes: 0
Reputation: 318182
$('#element').on("contextmenu",function(){
alert(this.id);
});
or
$('#element').on('mousedown', function(e) {
if (e.which === 3) {
alert(e.target.id);
}
});
Upvotes: 7
Reputation: 9740
$("#id").click(function() { console.log($(this).attr("id")); })
In jQuery, the object on which the event was fired is always this.
Upvotes: 0