Search code examples
javascriptjqueryhtmldocumentslideup

Div slide up when click in items inside it


I have a div that slides down (opens) when I click a certain input select. Inside this div, I have some other input selects and my objective is to slide up the div when I click on the rest of the page.

My problem:

The div slides up when I select some item in the input selects inside it, and I don't want this to happen.

  • Is there some way to slide up the div only when I click outside it?
  • Why are the selects inside the div making it to slide up as well?

This is my javascript to slide up the div:

$(document).mouseup(function (e) {
  var container = $('.myDiv');
  if (container.has(e.target).length === 0) {
    $(container).removeClass('close');
    $(container).addClass('open');
    $(container).next().slideUp(200);
  }
});

Solution

  • The div slides up when I select some item in the input selects inside it, and I don't want this to happen.

    Is there some way to slide up the div only when I click outside it? Why are the selects inside the div making it to slide up as well?

    Use event.stopPropagation() on the child element(s) to prevent the slide event being triggered by them.

    event.stopPropagation - Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

    Here's a simple jsFiddle and the basic example below.

    jQuery:

    $('div').click(function(){
      $('#slideMeUp').slideUp();
    });
    
    $('select').click(function(e){
      e.stopPropagation();
    });
    

    HTML:

    <div>Clicking here will trigger it! 
        <select>
            <option>This won't trigger the click event anymore!</option>
        </select>
        Clicking here will also trigger it!
    </div>
    
    <div id="slideMeUp">Only clicking the outer div will slide me up!</div>