When I reload the page, I call ajax to get the data and display it on the screen. As of now, I am displaying paragraphs and If the content is more than 40 words then I am displaying read more, and once expand then I am displaying the read less but it’s not working.
Do i need to use like this $(document).on('each', '.countParawords', function(e){ });
?
<style>
.empList .more-text{display: none;}
.less{display: none;}
</style>
<div class="empList"> <ul> </ul></div>
<script>
$(document).ready(function() {
$.ajax({
url: 'process.php',
method: 'post',
dataType: "json",
data: {
action: "employeelist"
},
success: function(data) {
var trHTML = '';
$.each(data, function(i, item) {
trHTML += '<li><div class="employeeShareWrap"><p class="countParawords">' + item.desc + '</p></div></li>';
});
$('.empList ul').append(trHTML);
}
});
var maxLength = 20;
var moretxt = "...Read More";
var lesstxt = "...Read Less";
$(".countParawords").each(function() {
var myStr = $(this).text();
if ($.trim(myStr).length > maxLength) {
var newStr = myStr.substring(0, maxLength);
var removedStr = myStr.substring(maxLength, $.trim(myStr).length);
$(this).empty().html(newStr);
$(this).append('<span class="more-text">' + removedStr + '</span>');
$(this).append(' <a href="javascript:void(0);" class="read-more more">' + moretxt + '</a>');
}
});
$(".read-more").click(function() {
if ($(this).hasClass("more")) {
$(this).removeClass("more");
$(this).text(lesstxt);
$(this).siblings(".more-text").show();
} else {
$(this).addClass("more");
$(this).text(moretxt);
$(this).siblings(".more-text").hide();
}
});
});
</script >
2
Answers
As the content that is added comes from ajax (not there when
$(".read-more")
is executed. yes you should use.on('click...)
however if the added element with class.read-more
is also added by ajax, then you should use one of it ancestors (that exists when the code executes). example:You should do it like:
not
So this part of your code:
should be changed to:
You can put your code of appending
a
tag orspan
inside success function of ajax then put the valuetrHTML
in some variable then use.find(".countParawords")..
to iterate through divs and finally append the values inside ul tag.Demo Code :