Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the id of element when right clicked

I like to know how to get the id of li when i right click over this li using javascript or jquery.

<ul>
    <li id="liid" class="collapsable">
        <div class="hitarea collapsable-hitarea">
        </div>
        <span class="folder">Group1.2</span>
    </li>
</ul>

I have the right click function.

$(document).bind("contextmenu", function (e) {
    // code to get the id of current li
});

Can any one help me please.

like image 322
Aswathy Avatar asked Jan 03 '14 07:01

Aswathy


People also ask

How do I get the clicked element id?

We can get the ID of the element that's clicked from the click event handler. We can either get the value from this if we use a regular function. Or we can get the same value from the event object of the click event handler.

How do I find id attributes?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element.

Can you get multiple elements by ID?

You cannot have more than one element with the same id in an HTML document.


1 Answers

Use .on('contextmenu', 'li')

$(function() {
    $('ul').on('contextmenu', 'li', function(e) { //Get li under ul and invoke on contextmenu
        e.preventDefault(); //Prevent defaults
        alert(this.id); //alert the id
    });
});

Demo

like image 103
Mr. Alien Avatar answered Oct 20 '22 20:10

Mr. Alien