Search code examples
javascriptjquerystringimage

How to show image on page load instead of jQuery click function?


I use Sportlink javascript library and I'm trying to show logo of football clubs on the page. This library prints only links like:

https://binaries.sportlink.com/KNVB-production-DOCUMENT/95B8AF6A49636098D3F0709CB8D39A8C?expires=1725642258&sig=e915f414c03e1769fa25587ce6cd65b6ab99f048

So I'm trying to move this string to an img tag and I almost succeeded without any knowledge of javascript or jquery.

When I click the button I get a logo image, which I want. But I would like to show the logo on page load without clicking anything.

Example page: https://alcides.ineeditweb.nl/teams/test-team/

// Javascript library (embedded) code
   <div  
    data-article="programma"
    data-param-gebruiklokaleteamgegevens="NEE"
    data-param-eigenwedstrijden="JA"
    data-param-aantalregels="1"
    data-param-thuis="JA"
    data-param-uit="JA"
    data-label-thuisteamlogo="thuislogo"
    data-fields="thuisteamlogo" 
    ></div> 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    <script>
    $(document).ready(function(){
    $("button").on( "click", function(){
    var a = $("div[data-label-thuisteamlogo='thuislogo']").text().replace("thuislogo", "");
    
    let img = document.createElement("img");
    img.src = a;
    document.getElementById("test").appendChild(img);
     });
     });
     </script>

     <button>Return value</button>

      <label id="test" style="width:60px" height="60px"></label>

Solution

  • To do what you need you simply need to remove the logic from the click handler and place it directly within the ready handler, so that it runs as soon as the DOM is ready. Below is a working example of how to do that.

    Also note that, as you're using jQuery already, you may as well use that to simplify the logic which creates the new img element. Also, the <script> tags should not be placed in the middle of your HTML. Put them in the <head> or just before </body>

    <!-- in the <head> of your page -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        var imgUrl = $("div[data-label-thuisteamlogo='thuislogo']").text().replace("thuislogo", "");
        $('<img />').prop('src', imgUrl).appendTo('#test');
      });
    </script>
    
    <!-- in the <body> of your page -->
    <div data-article="programma" data-param-gebruiklokaleteamgegevens="NEE" data-param-eigenwedstrijden="JA" data-param-aantalregels="1" data-param-thuis="JA" data-param-uit="JA" data-label-thuisteamlogo="thuislogo" data-fields="thuisteamlogo">https://binaries.sportlink.com/KNVB-production-DOCUMENT/95B8AF6A49636098D3F0709CB8D39A8C?expires=1725642258&sig=e915f414c03e1769fa25587ce6cd65b6ab99f048</div>
    
    <button>Return value</button>
    
    <label id="test" style="width:60px" height="60px"></label>