Self-invoking JS function
jordane45 Posted messages 30427 Registration date Status Moderator Last intervention -
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
-
Hello,
(function changeVisibility(){ // code })()Try with the () at the end of the block
Source: https://www.w3schools.com/js/js_function_iife.asp
-
Hello,
Test not conclusive. It’s the same. No display of the divs ;-(
Thanks anyway.Daniel
-
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
-
-
Hello,
Same here, the divs still do not display when the condition is met.
Thanks anyway.Daniel
-
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