0

I have the below HTML which is generated using jQuery from an AJAX call:

<ul id="ul-container">
    <li class="li-item" data-deviceKey="1">Data1</li>
    <li class="li-item" data-deviceKey="2">Data2</li>
</ul>

I then have this jQuery code:

$('.li-item').mousedown(function(e) {
    if(e.which == 3) {
        console.log('Right Click Detected on '+$(this).attr('data-deviceKey'));
    }
});

I am trying to detect a right mouse click, and then do something when it occurs.

This does not work, and it's stressing me out. I've tried literally every combination under the sun in order to try and get this to work. There's way too many to list, but literally nothing will detect the right click event.

Weirdly, if i set the selector to the ul's ID, it will then detect it? But, the problem is, i need to obtain the data-deviceKey attribute from the selected li.

Has anyone got any idea where the issue is here?

Things I've tried

1: Pretty much every reply in this: How to distinguish between left and right mouse click with jQuery
2: Detecting the right click on the ul's ID then finding the "closest" li element, which just returned the first li element in the list.
3: In my actual code, my li has 3 classes attached, i've tried using all of these which has not worked
4: tried using $('#ul-container li') to no avail.

Is it even possible to detect a right click on a class? Where am i going wrong? Please help before i have no hair left!

Community
  • 1
  • 1
Scott Thornton
  • 331
  • 1
  • 3
  • 17

1 Answers1

0

This is just a guess, but if you're loading the HTML content via an AJAX call, then you need to register the click handler after the HTML is inserted into the DOM.

Try registering the mousedown in the AJAX request's .done callback:

$.ajax({
  url: "test.html",
}).done(function() {
  $('.li-item').mousedown(function(e) {
    if (e.which == 3) {
      console.log('Right Click Detected on ' + $(this).attr('data-deviceKey'));
    }
  });
});
rphv
  • 5,409
  • 3
  • 29
  • 47
  • Thanks, will have a try tomorrow when i'm back in the office. Weird how it works in the fiddle above, but not on my webpage.. Might have to have a rethink about how i'm working it. Appreciate the response. – Scott Thornton Feb 21 '16 at 19:15