skip to Main Content

I am trying to run a function but only in the first click, I would do it onload, but I already have another function running on window.onload, both functions work fine independently, but not together, so I am calling the function window.onclick, but I don’t want the function to run in every click, is there a way to do this? Thanks in advance!

window.onclick = function changeURL(){
    var user = document.getElementById("user").value;
    document.getElementById("link").setAttribute("src", "indexT.html?ProofLoginDataRegistration="+ user);
  }

3

Answers


  1. Why does your onload not work with two functions? It sould be no problem.

    Anyway, you can do it in .onClick by setting a global boolean variable ("hasClicked"). Execute the function only when the variable is false. When the user clicked the first time, set this variable to true.

    E.g. something like

    <script>
    var isClicked = false;
    window.onclick = function changeURL(){
        if(!isClicked){
            isClicked = true;
            alert("HI");
        }
    }
    </script>
    
    Login or Signup to reply.
  2. Have you tried to solve this with an event listener?

    window.addEventListener("click", function() {
    
        // Do something 
    
    }, {once : true});
    
    Login or Signup to reply.
  3. create a function that calls both functions. include that in the onload event handler 😀

    window.onload = function handleOnload() 
    {
       func1();
       func2();
    }
    

    define the other functions elsewhere, without being assigned as event handlers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search