Thursday, December 20, 2018

javascript - jquery hide div when click outside




I am trying to style div and ul to function like . However, I have a problem that:
1) I only want to toggle the ul that I click and hide the other ul. So I wonder if jquery support some function such as 'not click'?
2) I want to hide all the ul when the mouse is click outside. I did some research, and see other people use mouseup or click on body. But I am not quiet sure how it works.





$(document).ready(function() {
$('.hide').each(function() {
$(this).hide();
});


$('.select').click(function() {
var id = '#' + $(this).attr('id');
var sub = id + '_sub';
$(sub).slideToggle();
});

$('body').mouseup(function() {
if($(this).length == 0) {
$(this).hide();

}
});
});

div.select {
display: inline-block;
margin: 10px;
padding: 20px;
background: red;
cursor: pointer;
}






1



  • 1

  • 2







1



  • 1


  • 2







1




  • 1

  • 2










Answer



here you go: DEMO



$(document).ready(function() {
$('.hide').hide(); //hide in the beginning

$('.select').click(function() {
$('.hide').slideUp(200); //hide all the divs
$(this).find('.hide').slideDown(200); //show the one that is clicked

});
$(document).click(function(e){
if(!$('.select').is(e.target) || !$('.select').has(e.target)){ // check if the click is inside a div or outside
$('.hide').slideUp(200); // if it is outside then hide all of them
}
});
});


you can define your notClick() function as below:




$.fn.notClicked= function(clickPosition){
if (!$(this).is(clickPosition.target) && $(this).has(clickPosition.target).length === 0){
return true;
}
else{
return false;
}
};



and then use it as:



$(document).click(function(e){
alert($('.select').notClick(e)); // will return true if it is not clicked, and false if clicked
});

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...