I have a div with class "post" that has a bunch of text in it with no height specified.
.post {
width: 100%;
margin: 0 0 2% 0;
background-color: #AAA;
overflow: hidden;
}
With jQuery I want to initially add a second class "postLess" that specifies a height of 300px. And therefore hides part of the text.
.postLess {
height: 300px;
}
When the "read more" button is clicked I would like to remove "postLess" and add "postMore" so that the height is set to "auto" and shows the full text.
.postMore {
height: auto;
}
Then of course I want it to remove class "postMore" and add back class "postLess" when the button is clicked a second time. Here is my jQuery. What am I doing wrong?
$('.post').addClass('postLess');
$('.readMore').click(function() {
if ($('.post').hasClass('postLess')) {
$('.post').removeClass('postLess').addClass('postMore');
}
else if ($('.post').hasClass('postMore')) {
$('.post').removeClass('postMore').addClass('postLess');
}
});
And here is the important part of my HTML down to the first two ".post"'s
<!DOCTYPE html>
<html lang="en">
<head>
<title>Switchback</title>
<link href="css/styles.css" type="text/css" rel="stylesheet">
<script src="js/jquery-1.9.0.min.js" type="text/javascript"></script>
</head>
<body>
<header>
</header>
<div id="content">
<div id="sidebar">
<p>
Ut neque tellus, dapibus bibendum tempor quis, gravida vitae nisl. Pellentesque erat elit, ullamcorper in accumsan id, ullamcorper in lectus. Nullam nec augue
</p>
<p>
Nunc facilisis lacus vel enim fringilla consequat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur vitae sem mauris.
</p>
</div> <!-- end div id="sidebar" -->
<div id="posts">
<div class="post">
<div class="postImg" style="background-image: url('img/pic1.png');">
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse purus lorem, viverra sed blandit non, vulputate in sem. Donec laoreet turpis id lectus
<a href="javascript:;" class="readMore">read more »</a>
</p>
</div>
<div class="post">
<div class="postImg" style="background-image: url('img/pic2.png');">
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec felis
</p>
<p>
Sed ornare, velit ac dignissim lacinia, dui mauris suscipit enim, quis viverra metus elit id quam. Sed quis tellus nulla. Nam pulvinar ante at felis lobortis eleifend.
<a href="#" class="readMore">read more »</a>
</p>
</div>
$('.post')selector there is nothing wrong with your code. Does it not work? You could also simplify it a little by removing theifcondition and using$('.post').toggleClass('postMore postLess');<div>with the classpost, the.hasClass()function will return true if any of them have thepostLessclass.