iNikkz
iNikkz

Reputation: 3819

Enable only Click event inside mouseup event Jquery

I have ul tag inside div tag. I have applied mouseup event on div tag and click event on ul tag.

Issue
Whenever I click ul tag, then both mouseup and click events are triggered.

What I want is that when I click on ul tag, then only click event should trigger and if I do mouseup event on div tag, then only mouseup event should trigger.

My code:
HTML:

<div class="m1">
    Nitin Solanki
    <ul>
        <li>one</li>
        <li>two</li>
    </ul>
</div>

JS:

$(document).on('mouseup', '.m1', function(){
    alert('div mouseup ');
});

$(document).on('click', 'ul li', function(){
    alert("ul li- clicked");
});

JSFIDDLE

Upvotes: 2

Views: 775

Answers (4)

DrLazer
DrLazer

Reputation: 3113

It's a strange question, as part of a "click" is actually a mouseup. A click comprises of a mousedown followed by a mouseup on the same element.

The only thing I think you could do here is to store when a click has started, and add a onesecond timeout to a variable that the mouseup event depends on.

Like this. (I feel dirty even posting this).

var clickStarted = false;

$(document).on('click', 'ul li', function(){
    alert("ul li- clicked");
    clickStarted = false;
});

$(document).on('mousedown', 'ul li', function(){
    clickStarted = true;
    setTimeout(function(){ clickStarted = false; }, 1000);    
});

$(document).on('mouseup', '.m1', function(){
    if(!clickStarted)
        alert('div mouseup ');
});

JSFiddle

Upvotes: 0

Raghvendra Kumar
Raghvendra Kumar

Reputation: 1388

The reason is event bubbling. You can handle this using event.stopPropagation();

$(document).ready(function(){

        $("ul li").click(function(event){
            event.stopPropagation();
            alert("The ul li element was clicked.");
        });

        $(".m1").click(function(){
            alert("The div element was clicked.");
        });
    });

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can stop the propagation of the event

$(document).on('mouseup', '.m1', function() {
  alert('div mouseup ');
});
$(document).on('mouseup', '.m1 ul', function(e) {
  e.stopPropagation()
});


$(document).on('click', 'ul li', function() {
  alert("ul li- clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="m1">
  Nitin Solanki
  <ul>
    <li>one</li>
    <li>two</li>
  </ul>
</div>

Upvotes: 2

sampie777
sampie777

Reputation: 133

You can use jQuery's is() to check if the clicked element is a div or a list:

$(document).on('mouseup', '.m1', function(event){
    // Check if the clicked element is the div and not the list
    if($(event.target).is('div'))
        alert('div mouseup ');
});

$(document).on('click', 'ul li', function(){
    alert("ul li- clicked ");
});

Upvotes: 1

Related Questions