jQuery each method for dynamic elements autorun

104 views Asked by At
$('body').on('click', function () {
  $( '.detailTextContainer a' ).each(function() {
    var urlFoto = $(this).attr('href');
    var imgElement = $("<img />").attr('src', urlFoto)
                                 .addClass('dalsiFoto');

    $(this).empty().append( imgElement );   
  });
});

How can I run this function automatically after load page (without event). '.detailTextContainer a' are dynamic elements, which are loaded to page immediately after start page.

I tried this code:

function showImage (){
  $( '.detailFeatureDesc a' ).each(function() {
    var urlFoto = $(this).attr('href');
    var imgElement = $("<img />").attr('src', urlFoto)
                                 .addClass('dalsiFoto');
    $(this).empty().append( imgElement );
  });
};

showImage();

But this weren't successfully.

Thanks

3

There are 3 answers

2
amicoderozer On

You can use load function:

$( window ).load(function() {

      // create detailTextContainer here
      $( '.detailTextContainer a' ).each(function() {
             var urlFoto = $(this).attr('href');
             var imgElement = $("<img />").attr('src', urlFoto)
                                          .addClass('dalsiFoto');

        $(this).empty().append( imgElement );   

      });

});

From documentation, this will run the function when the page is fully loaded including graphics.

Or you can use:

$( document ).ready(function() {

});

or the shorthand:

$(function() {

});

This will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

0
Manish Singh On

you should simply write function on window load function

<script>
$( document ).ready(function() {
    console.log( "document loaded" );
});

$( window ).on( "load", function() {
   //write your code is given section
});
</script>
0
Raviteja On

you can try "on" listener

$(document).on("click", ".detailTextContainer a", function() {
  // your code
});