designerdarpan designerdarpan - 26 days ago 6
Javascript Question

click triggered button not working in read more and read less button

I am trying to make read more and read less button. Everything is pretty much working, I have total 4 div where characters are to be limited, characters are limited too, and even the buttons are working fine, The problem is the button works in certain div and dont work in certain div, I dont understand what is the problem ?



function limitCharacters(){
$('.limit-characters').each(function(){
var element = $(this);
// var element = $('.limit-characters');
var elementHtml = element.html();
element.prepend(elementHtml);
element.find("p:first").addClass("limited");
element.find("p:last").addClass("unlimited hide-element");
var limitedElement = element.find('.limited');
var limitedElementString = limitedElement.text();
var subStringedString = limitedElementString.substring(0,500);
limitedElement.html(subStringedString);
var buttonElement = '<a href="#" class="btn btn-sample3 btn-sm actionButton ">Read More</a>';
element.append(buttonElement);
var button = $(".actionButton");
button.click(function(e){
$(this).parent().find(".unlimited").toggleClass("hide-element");
$(this).parent().find(".limited").toggleClass("hide-element");
$(this).toggleClass("read-less");
if($(this).hasClass("read-less")){
$(this).html("Read Less");
}else{
$(this).html("Read More");
}
e.preventDefault();
});
});
}

.hide-element{
display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="limit-characters">
<p>
Had best days of my life ever in Nepal. Wish you all a good time and hope to see you again in my next holiday and I promise to make longer holiday for best memories.Had best days of my life ever in Nepal. Wish you all a good time and hope to see you again in my next holiday and I promise to make longer holiday for best memories.Had best days of my life ever in Nepal. Wish you all a good time and hope to see you again in my next holiday and I promise to make longer holiday for best memories.Had best days of my life ever in Nepal. Wish you all a good time and hope to see you again in my next holiday and I promise to make longer holiday for best memories.
</p>
</div>




Answer Source

The problem is in var button = $(".actionButton");, you should select the .actionButton that's inside your element.

var button = element.find(".actionButton");