martin j martin j - 28 days ago 5
CSS Question

Read more button only open parent div

I have a read more button on my website that once clicked, shows more of the text (or code) bellow. The problem is if I use 2 of the read more functions on same page, they will open and close each other (both will open and close no mather wich button I use. How can I make it only open the parent div?

HTML:



<h1>Read more using CSS and JS</h1>

<p class="p">This text is long, realy realy realy loooooooong!<br />
It is so long we even have a read more button and this text is to test the read more function. Cheers!</p>

<p class="p">This text is long, realy realy realy loooooooong!<br />
It is so long we even have a read more button and this text is to test the read more function. Cheers!</p>

<div class="hidden">

<p class="p">This text is long, realy realy realy loooooooong!<br />
It is so long we even have a read more button and this text is to test the read more function. Cheers!</p>

<p class="p">This text is long, realy realy realy loooooooong!<br />
It is so long we even have a read more button and this text is to test the read more function. Cheers!</p>

<p class="p">This text is long, realy realy realy loooooooong!<br />
It is so long we even have a read more button and this text is to test the read more function. Cheers!</p>

<p class="p">This text is long, realy realy realy loooooooong!<br />
It is so long we even have a read more button and this text is to test the read more function. Cheers!</p>

</div>

<div class="more-after">
<a class="more">Show More...</a>
<a class="more" style="display:none">Show Less</a>
</div>

<!--<p class="debug"></p>-->




CSS:

/* *****************************************************
/////////// Read More //////////////////////////////////
***************************************************** */
.wrap {
width: 100%;
margin:0 auto;
}

.hidden {
display: none;
}

.more {
font-size:13px;
letter-spacing: 2px;
cursor: pointer;
color:#e3382d;
}

.more-after {
border-bottom:1px solid #080e11;
width:100%;
}


JS:

$(".more").click(function() {

$(".hidden").slideToggle("slow",function(){
$(".more").toggle();
});

});


var content = $(".wrap").text();
var length = content.length;
$(".debug").text(length);


require ajax:

//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js


You can also see the codepen with the code already setup:
http://codepen.io/Volcan3/pen/xRxBpe

Answer

Here is a way to achieve what you want without modifying your HTML or CSS structure at all, and keeping the transition effect that you have.

$(".more").click(function() {
  var $more = $(this);
  $more.parents('.wrap').find('.hidden').slideToggle('slow', function() {
    $more.parent('.more-after').find('.more').toggle();
  });
});

Edit: Codepen http://codepen.io/anon/pen/wovOQq

Comments