I would like to create one of those read more / read less buttons using toggleClass().
This is my html:
<p>Lots of bla bla bla.....<span id="plus">Plus</span></p>
<p>Lots of bla bla bla.....<span id="plus">Plus</span></p>
<p>Lots of bla bla bla.....<span id="plus">Plus</span></p>
This is my jQuery:
$(function(){
$("#plus").on("click", function () {
$(this).parent().toggleClass( "showmore" );
var txt = $("p").hasClass("showmore") ? 'Minus' : 'Plus';
$("#plus").text(txt);
});
});
Fiddle: Click here
My Question:
How do I get toggleClass to work with multiple IDs (same selectors). The current script only works with the first ID.
Looking forward to your input, cheers!
IDs should be unique. You can rather use same class name
<p>Lots of bla bla bla.....<span class="plus">Plus</span></p>
<p>Lots of bla bla bla.....<span class="plus">Plus</span></p>
<p>Lots of bla bla bla.....<span class="plus">Plus</span></p>
and then use class selector to target them. also you need to use context this
in click event to target current element and parent p element with jquery method .parent()
:
$(".plus").on("click", function () {
$(this).parent().toggleClass( "showmore" );
var txt = $(this).parent().hasClass("showmore") ? 'Minus' : 'Plus';
$(this).text(txt);
});