简体   繁体   中英

Hide div onClick with jQuery

I have a demo here of a script that allows me to show and hide content on my site. It is working perfectly.

However, when I click on a link to show the content and then click it again to hide it, it re-opens it. I need it to fully hide when clicked whilst on show ('active') status.

Can anyone explain how to fix this?

Thank you.

CODE:

$(document).ready(function() {

 $('.showscroll').bind('click', 'h2, h3', function(e) {
   e.preventDefault();

   $(this).toggleClass('active');
   $('.newboxes2').slideUp().delay(200);
   $(this).find('.newboxes2').slideToggle();

               if($(this).is('.active') ) {
                       $(this).find('img.small').attr('src', '/wp-content/themes/boilerplate/images/image_corner_btn_onstate.png');
               } else {
                       $(this).find('img.small').attr('src', '/wp-content/themes/boilerplate/images/image_corner_btn_offstate.png');
               }
   if (this.id === 'service29') {
    $('html, body').animate({
      scrollTop: $(this).find('h2').offset().top
    }, 1000);
                }

 });

});

It will toggle properly if you call only .slideToggle . With the call to .slideUp each time, it will slide up when it is visible and then immediately slide down because it's being toggled again. It slides down the first time because .slideUp doesn't make it visible.

If you want to hide all the other elements, you can use .not to exclude the current "shown" element.

http://jsfiddle.net/fS5gq/3/

Try this remove $('.newboxes2').slideUp().delay(200);

 $(document).ready(function() {

 $('.showscroll').bind('click', 'h2, h3', function(e) {
   e.preventDefault();

   $(this).toggleClass('active');       
   $(this).find('.newboxes2').slideToggle();

               if($(this).is('.active') ) {
                       $(this).find('img.small').attr('src', '/wp-content/themes/boilerplate/images/image_corner_btn_onstate.png');
               } else {
                       $(this).find('img.small').attr('src', '/wp-content/themes/boilerplate/images/image_corner_btn_offstate.png');
               }
   if (this.id === 'service29') {
    $('html, body').animate({
      scrollTop: $(this).find('h2').offset().top
    }, 1000);
                }

 });

});

http://jsfiddle.net/fS5gq/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM