Question

I need some help with hiding a div when a user clicks on it and also sliding down the content of the div that is hidden.The following code is for sliding down the hidden div.

    $(document).ready(function (){ $('.hide').hide();
    $('.main:has(".hide")').find('div.toggle').click(function() {
       var el = $(this).next('.hide'),
       check = (el.is(':visible')) ? el.slideUp() : ($('.hide').slideUp()) (el.slideDown());
    });

    });

The above example is here and this link has the full markup and some experiment that I tried to hide the read more div but it hides every div.Also if someone would help me explain the above if else shorthand statement.

Thanks everyone my query is solved :)

Était-ce utile?

La solution

I think what you need to learn is how to use this. this is a keyword that refers to the element you click on. So, you can do something like $(this).hide() or remove(), or toggle(), or what ever you want.

http://jsbin.com/awirap/5/edit

JQuery this

Edit: To show the read more when you click on another you will do this:

$('.toggle').show();

You show all of them, and then after this bit of code you do $(this).hide(); to hide only the one you've clicked on.

Autres conseils

Here's a simpler way.

$(document).ready(function(){
  $('.toggle').click(function(){
    $(this).hide();
    $(this).next('div').slideToggle();
  });
});

The shorthand if/else statement is called the ternary operator. You code says if the div with the additional text is visible then slide it up (hide), else, slide it down (show). However the part after the : probably shouldn't have ($('.hide').slideUp())

Replace this code with your existing script

$(document).ready(function (){
       $('.hide').hide();
       $('.main:has(".hide")').find('div.toggle').click(function() {
           $(".toggle").show();
           $(this).hide();
           var el = $(this).next('.hide');
           var check = (el.is(':visible')) ? el.slideUp() : ($('.hide').slideUp()) (el.slideDown());
       });

});

I think you want this: http://jsbin.com/awirap/6/edit

$(document).ready(function (){
   $('.hide').hide();
   $('.main').find('div.toggle').click(function() {
       if ($('.hide').css("display") == 'none') {
          $('div.toggle',this).addClass("hidden").next().addClass("show");
       } else {    //---------------------------------^^---missed the parentheses
          $('div.toggle').show();
       }
       var el = $(this).next('.hide'),
       check = (el.is(':visible')) ? el.slideUp() : ($('.hide').slideUp()) (el.slideDown());
   });
});

if someone would help me explain the above if else shorthand statement.

(condition) ? if true : if false
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top