Alex Zahir
Alex Zahir

Reputation: 969

jQuery: Show content of the <p> beyond one line

I have 3 paragraphs, as shown in the HTML below. I want the content of p-show to not exceed beyond the first line normally. And when the "Show me" button of each respective p-show is clicked, it should expand and show all of the content inside it.

I tried the below JavaScript but it doesn't seem to work:

var h = $('p-show')[0].scrollHeight;


$('.p-show a').click(function(e) {
    e.stopPropagation();
    $('.p-show').animate({
        'height': h
    })
});

$(document).click(function() {
    $('.p-show').animate({
        'height': '50px'
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="p-show p-show1">
Content Content Content <br />
Content Content Content <br />
Content Content Content <br />
Content COntent Content
<a href="#" class="show-me show-me1">Show Me</a>
</p>

<p class="p-show p-show2">
Content Content Content <br />
Content Content Content <br />
Content Content Content <br />
Content COntent Content
<a href="#" class="show-me show-me2">Show Me</a>
</p>

<p class="p-show p-show3">
Content Content Content <br />
Content Content Content <br />
Content Content Content <br />
Content COntent Content
<a href="#" class="show-me show-me3">Show Me</a>
</p>

Upvotes: 0

Views: 77

Answers (2)

Toni Michel Caubet
Toni Michel Caubet

Reputation: 20183

How about

$(document).on('click', '.p-show + a', function(event) {
    event.preventDefault();
    $(this).prev('p').toggleClass('expanded');
});
.p-show {
   height:1em; overflow: hidden;
}
.p-show.expanded {
   height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="p-show p-show1">
Content Content Content <br />
Content Content Content <br />
Content Content Content <br />
Content COntent Content

</p>
<a href="#" class="show-me show-me1">Show Me</a>

<p class="p-show p-show2">
Content Content Content <br />
Content Content Content <br />
Content Content Content <br />
Content COntent Content

</p>
<a href="#" class="show-me show-me2">Show Me</a>

Upvotes: 1

rich_c
rich_c

Reputation: 110

Perhaps you can have the content that can be hidden and shown wrapped in a element with a class assigned to it so that it can be accessed with jQuery

Example:

HTML

<p class="p-show p-show1">
Content Content Content <br />
   <span class="more">
   Content Content Content <br />
   Content Content Content <br />
   Content COntent Content
   </span>
<a href="#" class="show-me show-me1">Show Me</a>
</p>

CSS

.more{
   display:none;
}

jQuery

$(".show-me").click(function(){
   $(this).prev(".more").slideToggle();
});

Upvotes: 0

Related Questions