I have this code for show more/less of my comment with toggle. It works great. However I have another form for adding comments and that form is using jQuery ajax. So after adding a form the script is not working. I have to reload the whole page to show it working correctly. In the source I see the script loaded. It is also in side the part that is reloading.
Maybe I should change ready to load?
EDIT: onload is not helping either ;(
<script>
$(document).ready( function () {
$(".comment p").each(function() {
var val = $.trim(this.innerHTML);
var parsed = val.split(/\s+/);
var cut = parsed;
// for each word
for (var i = 0, k = 0; i < parsed.length; i++) {
k += parsed[i].length + 1;
if (k - 1 > 50) {
cut = parsed.slice(0, i);
break;
}
}
// if one long word
if (cut.length == 0) {
cut.push(parsed[0].substring(0, 50));
}
val = cut.join(" ");
// if the text is long enough to cut
if (cut.length != parsed.length) {
this.innerHTML = val.replace(/[.,;?!]$/, "")
+ "<span>...</span> ";
$("<span />")
.css("display", "none")
.html(parsed.slice(cut.length).join(" ") + " ")
.appendTo(this);
$("<a />", {
href : "#",
text : "[show more]"
}).on("click", function(e) {
var sh = this.innerHTML == "[show more]";
$(this).prev("span").toggle(sh).prev("span").toggle(!sh);
this.innerHTML = sh ? "[show less]" : "[show more]";
e.preventDefault();
}).appendTo(this);
} else {
this.innerHTML = val;
}
});
});
</script>
EDIT: My ajax call looks like this (I am using CodeIgniter):
$.ajax({
url : "<?php echo site_url('comments/add'); ?>",
type : 'POST',
data : form_data,
success : function(msg) {
var pathname = window.location.pathname;
$('.comments-tbl-div').load(pathname + ' .comments-tbl-div');
$('#comment-form-part').html(msg);
}
});