I have the following code which should change the value of an h2 from “Show More” to “Show Less” and then back again when the parent is clicked.
The if() tests ok and changes the text to Show Less but it will never change it back again and always displays the alert “Show More” so it just isn’t detecting the else() condition.
I have searched high and low to find out why but haven’t found a solution yet.
I know this a noob question so apologise for this but I have tried finding the solution before posting here.
Thanks.
$('#panels > .feature').click(function() {
if($(this).children('h2').val('Show More')) {
$(this).children('h2').text('Show Less');
alert('Show More was found');
}
else {
$(this).children('h2').text('Show More');
alert('Show Less was found');
}
$(this).next(".info_box").animate(
{'height':'toggle'}, 'slow', 'linear'
);
});
The HTML in question is:
<div id="panels">
<div id="Email" class="feature">
<h1>LiveContent</h1><h2>Show More</h2>
</div>
<div class="info_box">Information will go in this div which should slide in and out.</div>
<div id="Email" class="feature">
<h1>Publishing Solutions</h1><h2>Show More</h2>
</div>
<div class="info_box">Information will go in this div which should slide in and out.</div>
<div id="Email" class="feature">
<h1>Title 1</h1><h2>Show More</h2>
</div>
<div class="info_box">Information will go in this div which should slide in and out.</div>
</div>
You’re using
.val()to check the text, use.text()instead (and compare the result, don’t set it), like this:Also, you can slim it down overall by using a function for
.text()and.slideToggle(), like this:You can test it out here.