I want to click a button to switch the slideUp & slideDown div and faster elsewhere on the page to close the div

I have a #clickme button. When the div #cart clicked, the slide show, when it is clicked again, it slides down.

I also want to be able to close it by clicking elsewhere on the page other than #cart or #clickme.

The code I tried does not quite work. Now it happens that when I click #clickme, it slides, and then quickly goes back.

I assume that the click event is triggered both at the document level and at the #clickme level, causing one effect after another.

What an elegant way to get around this?

$('#clickme').click(function() {
   if ($("#cart").is(":hidden")) {
       $("#cart").slideDown("slow");
   } else {
       $("#cart").slideUp("slow");
   }
});

$(document.body).click(function () {
   if ($("#cart").not(":hidden")) {
       $("#cart").slideUp("slow");
   } 
});
+3
source share
3 answers

jAndy , , , " ", , :)

.slideToggle() :visible , , :

$('#clickme').click(function(e) {
  $("#cart").stop(true, true).slideToggle("slow");
  e.stopPropagation();
});

$(document).click(function () {
  $("#cart:visible").stop(true, true).slideUp("slow");
});

.slideToggle() , , , , , . :visible, #cart, , . .stop() , , , , .

event.stopPropagation() , , click .click() , ( , ).

+3

click event document.body, click event #clickme .

.stopPropagation() #clickme:

$('#clickme').click(function(e) {
   e.stopPropagation();

   if ($("#cart").is(":hidden")) {
       $("#cart").slideDown("slow");
   } else {
       $("#cart").slideUp("slow");
   }
});

click event DOM.

Sitenote: Caching DOM. , 6 .

var $cart = $('#cart');

$cart . .

: http://www.jsfiddle.net/EuzyL/1/

0

Try it,

var toggleThis = function() {
   if ($("#cart").is(":hidden")) {
       $("#cart").slideDown("slow");
   } else {
       $("#cart").slideUp("slow");
   }
};

$('#clickme').click(toggleThis);
$('#clickme').blur(toggleThis);

$(document.body).click(function () {
   if ($("#cart").not(":hidden")) {
       $("#cart").slideUp("slow");
   } 
});

Happy coding.

0
source

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


All Articles