Search code examples
jqueryeventsmouseup

How to exclude more div id's from clicking event


I am new to jquery, and i like to know if there is a way to exclude multiple div's from clicking event. First, i was looking how to hide certain div, when mouse clicks outside of it. This is only solution that gave some result (:not selector didn't work). I would like to exclude #cartbasket div as well, so that same button can continue to toggle up and down #cartbasketList ul below. I tried many combinations, but without any good..

html:

<div id="cartinfos">
  <div id="cartbasket"></div>
    <ul id="cartbasketList">
      <li><a href="#">somelink</a></li>
      <li><a href="#">somelink</a></li>
      <li><a href="#">somelink</a></li>
    </ul>
 </div>

CSS:

#cartinfos {
    position: relative;
    display: inline-block;
    text-align: right;
    width: 50%;
    left: 10px;
    padding: 15px 0px;
}

#cartbasket {
    position: relative;
    display: inline-block;
    background: #ff0000;
    width: 40px;
    height: 40px;
}

#cartbasketList {
   position: absolute;
   display: none;
   border-top: 5px solid #ff0000;
   width: 250px;
   height: 400px;
   top: 60px;
   right: 0px;
   background:#fff;
   z-index: 999999;
}

jquery:

  $(function() {

      $("#cartbasket").click(function() {
         $("#cartbasketList").slideToggle("fast");
    });


      $("body").mouseup(function(event) {
        if (event.target.id != 'cartbasketList') {
            $("#cartbasketList").slideUp(100);
        }

    });


    });

Solution

  • You should track what your click event and check to see if a certain element has been clicked.

    Be sure to only use 1 click event otherwise the events will start to bubble and give you an undesirable affect.

    $(function() {
    
        var $cartList = $('#cartbasketList');
    
        $(document).on('click', function(e) {
            var target = e.target.id;
    
            if(target == "cartbasket"){
                $cartList.slideToggle('fast');
            }
            else {
                $cartList.slideUp('fast');
            }
        });
    
    });
    

    Demo Fiddle