Udara Udara - 3 months ago 8
Javascript Question

How to use jQuery in dynamically loaded elements?

I have loaded 12

<div>
elements first to web page and it has a description inside a
<span>
. Other
<div>
elements load when scrolling the page. I have used following jQuery to limit description text on div.

$(document).ready(function () {
$("span.fine-print").html(function(index, currentHTML) {
if (currentHTML.length > 200) {
var str= currentHTML.substr(0, 200)+ '...<p style="color:blue;display:inline">Read more</p>';
return str;

}
});
});


This jQuery works correctly for first 12
<div>
elements, but it's not working after 12 elements. How to fix this issue. Is there any possibility to do this?

Answer

Check this :

Html

<div id="wrapper">
 <div>
   <span class="sp">hello hello hello hello hello hello hello hello hello</span>
 </div>
 <div>
  <span class="sp">hello hello hello hello hello hello hello hello hello</span>
 </div>
 <div>
  <span class="sp">hello hello hello hello hello hello hello hello hello</span>
 </div>
 <div>
  <span class="sp">hello hello hello hello hello hello hello hello hello</span>
 </div>
 <div>
  <span class="sp">hello hello hello hello hello hello hello hello hello</span>
 </div>
</div>

Jquery

$(document).ready(function () {
     changeContent();
});
$(document).scroll(function() {
 $("#wrapper").append("<div><span class='sp'>hello hello hello hello hello hello hello hello hello</span></div>");
       changeContent();
    });

function changeContent(){
    $(".sp").html(function(index, currentHTML) {
        if (currentHTML.length > 20) {
            var str= currentHTML.substr(0, 20)+ '...<p style="color:blue;display:inline">Read more</p>';
            return str;
        }
        });
}

Demo Link

Check this :- https://jsfiddle.net/o3ntvbex/1/

Note : just for demo purpose. Not optimised code.