Why can't I click on this div?

When I click on x inside the closing div, I want the background to change to white.

This is the markup:

<div class="list-item list-item-active"> <div class="close">x</div> </div> 

This is javascript:

 $(document).ready(function(){ $('.list-item').live('click', function() { if (!$(this).hasClass('list-item-active')) $(this).addClass('list-item-active'); }); $('.list-item .close').live('click', function() { $(this).parent().removeClass('list-item-active'); }); }); 

This is css:

 .list-item {width:100px;height:100px;background:#fff} .list-item-active {background:#ccc} 

Demo: http://jsfiddle.net/JMeff/

+4
source share
3 answers

You can click on it, but the click will also click on the parent due to the default event bubbles. To get the desired effect, stop the bubble through .stopPropagation() , for example:

 $('.list-item .close').live('click', function(e) { $(this).parent().removeClass('list-item-active'); e.stopPropagation(); }); 

Here you can check it out .

+10
source

Try the following:

 $(document).ready(function(){ $('.list-item').live('click', function() { if (!$(this).hasClass('list-item-active')) $(this).addClass('list-item-active'); }); $('.list-item .close').live('click', function() { $(this).parent().removeClass('list-item-active'); return false; }); }); 

Pay attention to the new return false : otherwise the event will be caught by $('.list-item').live instead of what you want, $('.list-item .close').live .

+3
source

Because you did not return false in the second event handler. Without return false; the event will also be handled by the parent who reads the class after it is deleted.

0
source

Source: https://habr.com/ru/post/1332375/


All Articles