Mannythoughts
Mannythoughts

Reputation: 3

jQuery event triggered when clicking outside the list

I am trying to trigger a click event on every item in a nested list and return the text of the clicked item. The return text part works fine but when I click outside the list, it still triggers the click event and returns the text of the list item in the corresponding line. Has anyone faced such an issue?

HTML:

 <div id="myDiv">
    <ul id = "u" class="nam">
      <li id="i1" class="nam">John</li>
      <li id="i2" class="nam">
          <ul id="uu">
             <li id="i3">F</li>
             <li id="i4">Fitzgerald</li>
          </ul>    
      </li>
      <li id="i5" class="nam">Kennedy</li>
     </ul>
   </div>

jQuery Code:

  $("#u").on("click","li",function(event){
   event.stopPropagation();
   alert($(this).text());
});

Upvotes: 0

Views: 66

Answers (3)

Batu.Khan
Batu.Khan

Reputation: 3065

Giving fixed width will solve that but another solution is wrapping li content with span. You can do this with jquery if you dont wanna do it in your html code then build your click event for li span selector.

$("li").not(":has(ul li)").wrapInner("<span></span>");

$("#u").on("click","li span",function(event){
  event.stopPropagation();
  alert($(this).text());
});

FIDDLE

Upvotes: 1

Sikander
Sikander

Reputation: 656

Just style your div ul li and your problem will be solved because the element you are using they are the block element which using the full page, so style your page or provide some fixed pixel it will work.

Upvotes: 0

Mathlight
Mathlight

Reputation: 6653

The problem is that without any width styling, your div and UL is taking the whole width of the page.

You can see that example here: JSFIDDLE

If you give the div some with, the problem will be gone ( the container to click will be smaller )

width: 200px;

Upvotes: 5

Related Questions