KeepCool KeepCool - 2 months ago 5
CSS Question

How do I get a jQuery function to work with specific elements when they have the same class names?

I have sections (divs) with text in it, but when the text is too long I made it so the text "fades" (with css) and displays a "show more" button, which shows the full text for that specific div when clicked. The problem is that it only works for the first div, and I believe it's because they all have the same class and id name. What's the best way to get around that? Here's my code:

HTML:

<div id="fade-container">
<div id="fade-content">
<p>
Long text goes here...
<div class="fade-anchor"><span class="btn-primary round-xl small btn-shadow">Show more</span></div>
</p>
</div>
</div>


Script:

<script>
$('.fade-anchor').click(function(e){
e.preventDefault();
$('#fade-content').css('max-height','none');
$('.fade-anchor').remove();
});
</script>


By the way, info is being fetched from the database in a php while loop.

Answer

When the user clicks on .fade-anchor you can use thisto get the element currently selected, you should also use classes instead of ids for multiple elements, like so:

$('.fade-anchor').click(function(e){
    e.preventDefault();
    $(this).parent('.fade-content').css('max-height','none');
    $(this).hide(); // Maybe you should hide instead of removing, in case you want to add a toggle effect later on.
});

You can also check out this jsFiddle with the working version.

Hope it helps.

Comments