0
$('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

Shiladitya
  • 12,003
  • 15
  • 25
  • 38

3 Answers3

0

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.

amicoderozer
  • 2,046
  • 6
  • 28
  • 44
  • Thanks for your reply. But your solution with .load() (in my page) is the same like my. The image element is append after click event. And this solution is not functional, too: `$function () { $( '.detailTextContainer a' ).each(function() { var urlFoto = $(this).attr('href'); var imgElement = $("").attr('src', urlFoto) .addClass('dalsiFoto'); $(this).empty().append( imgElement ); }); };` – Kamil Novák Sep 05 '17 at 07:46
  • This should work, but you have to create your dynamic elements before each function. Try to create them in windows load function (or document ready) before each.Without html code is difficult to provide working example. – amicoderozer Sep 05 '17 at 07:57
0

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>
Manish Singh
  • 934
  • 1
  • 12
  • 27
0

you can try "on" listener

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