SleBluue SleBluue - 3 months ago 9
jQuery Question

Toggle the content of a div and change the height of another div in Jquery

I am trying to toggle the height and to display two different

divs
on the same
onclick
event with jquery. I feel like I may be missing something small or a rule in jquery that I don't know. On the first click everything displays and changes height like planned, but the second does not minimize the content.

JS

jQuery(document).ready(function(){
jQuery('.readmore').on('click', function(event) {
if (jQuery("#content").height() == 500) {
jQuery("#content").animate(
{height: "750px"});
jQuery('#hidden').toggle('show');
}
else {
$("#content").animate({height: "500px"});
jQuery('#hidden').toggle('hide');
}
});
});


The div starts off as
500px
tall and want to toggle them between that and
750px
while switching between displaying the content in
#hidden
.

here is my HTML

<div id="content">
<p></p>
<div id="hidden" style="font-size:18px">
<p></p>
</div>
</div>
<div class="content3">
<p><a class="readmore" href="javascript://">Read More </a></div>

Answer

You can merely use the built in show() and hide() functions with jQuery.

As you have it, this:

jQuery('#hidden').toggle('show');

and this

jQuery('#hidden').toggle('hide');

are toggling the classes .show and .hide. Therefore if your classes differ from the default styling, they may be altering the functionality you are expecting. You need the .hide class to hide things initially, but after that it's not necessary to toggle that class.

The jQuery also assume the initial div is always 500px tall. So, if the #content div is less than 500px tall, it takes 2 clicks to minimize it again. You can tweak the function to account for instances where the div is less than 500px tall and it should all still work as expected.

jQuery(document).ready(function(){
    jQuery('.readmore').on('click', function(event) {        
        if (jQuery("#content").height() <= 500) {
            jQuery("#content").animate(
                {height: "750px"});
            jQuery('#hidden').show();
       } 
        else {
            $("#content").animate({height: "500px"});
            jQuery('#hidden').hide();
       }
    });
});
.hide { display: none; }
div { padding: 20px; }
#content { background: #aaa;}
#hidden { background: #eee;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<p>displayed text</p>
<div id="hidden" class="hide" style="font-size:18px">
<p>hidden text</p>
</div>
</div>
<div class="content3">
<p><a class="readmore" href="javascript://">Read More </a></div>

This will expand the height to 750px regardless of the initial height... then minimize to 500px on the second click.