Self-invoking JS function

danielos77 Posted messages 109 Registration date   Status Member Last intervention   -  
jordane45 Posted messages 30427 Registration date   Status Moderator Last intervention   -
Hello,

I’m looking to display or hide 2 div elements on page load based on a result I receive and its processing in PHP. I want to have a button with an OnClick and the JS script placed between the tags; that works fine. But I can’t auto-invoke the script inside my if.

[Long PHP/JS code block omitted for brevity in this summary]

Thanks to anyone who can point me in the right direction.
Daniel

4 answers

  1. danielos77 Posted messages 109 Registration date   Status Member Last intervention   2
     

    Hello,

    Test not conclusive. It’s the same. No display of the divs ;-(
    Thanks anyway.

    Daniel
     

    0
    1. Grandasse_ Posted messages 967 Registration date   Status Member Last intervention   611
       

      Darn, I have another idea:

      <script type="text/javascript" defer>

      Add "defer" at the end of the tag that contains your script; it ensures the HTML is loaded first (and thus the various elements that are called by the JS exist in the document)

      https://developer.mozilla.org/fr/docs/Web/API/HTMLScriptElement/defer

      0
  2. danielos77 Posted messages 109 Registration date   Status Member Last intervention   2
     

    Hello,

    Same here, the divs still do not display when the condition is met.
    Thanks anyway.

    Daniel

    0
  3. jordane45 Posted messages 30427 Registration date   Status Moderator Last intervention   4 830
     

    Hello,

    I skimmed through your exchanges, but I think we need to wait for your elements to be loaded in your page before you can manipulate them.

    There are several solutions (defer isn’t one because it only applies to elements with a src=)



    So, try:
    echo '<script> document.addEventListener("DOMContentLoaded", function (){ const informations = document.getElementById("Informations"); const helloAsso = document.getElementById("HelloAsso"); if (!informations || !helloAsso) { return; } if (informations.style.visibility !== "hidden") { informations.style.visibility = "hidden"; informations.style.display = "none"; } else { informations.style.visibility = "visible"; informations.style.display = "block"; helloAsso.style.visibility = "visible"; helloAsso.style.display = "block"; } }); </script>';

    And if it still doesn’t work, add console.log in the js code and show us what it prints in your browser console


    .
    Best regards,
    Jordane

    0