Why does my onclick on an onload not work?

Asked

Viewed 407 times

0

I’m using this code however from the onclick it doesn’t work if I click on the "fa-search" element, but if I paste the same JS into the Chrome console it works as expected.

Would you like to know why? I imagine it is something that is related to scope.

onload = (() => {
    console.log("agua");	
    document.getElementsByClassName("fa-search")[0].onclick = () =>{
      document.getElementById("fieldSearch").focus();
      console.log("Executou");
    }
})();
<html>

<head>
    <script defer src="https://use.fontawesome.com/releases/v5.6.1/js/all.js" integrity="sha384-R5JkiUweZpJjELPWqttAYmYM1P3SNEJRM6ecTQF05pFFtxmCO+Y1CiUhvuDzgSVZ" crossorigin="anonymous"></script>
</head>

<body>    
    <aside id="container">
        <header>Encontre um ponto de venda</header>
        <p>Digite o seu CEP, rua, bairro ou cidade</p>
        <div class="search">           
            <input type="text" id="fieldSearch">
            <i class="fas fa-search"></i>            
        </div>

        <div id="proximidade">
            <ul>
                <li>
                    <button>5 KM</button>
                </li>
                <li>
                    <button>10 KM</button>
                </li>
                <li>
                    <button>15 KM</button>
                </li>
            </ul>
        </div>

        <div id="block-list">                
            <i class="fas fa-list"></i>
            <span>Lista</span>            
        </div>
    </aside>
</body>
<link rel="stylesheet" type="text/css" href="Dist/my-styles.css" />
<script src="../Sass/js/mapa.js"></script>
</html>

  • 1

    Works normally, I think you’re getting confused at another point in your code.

  • How so Fernando, I did not understand straight, I’m sorry, because at least in the version of Chrome here is not working this does not.

  • I opened now in Chrome 70 and Firefox 63 the link I commented with your code is working normally. By clicking on the element the input gains focus and is logged in "Run" in the console.

  • Even I just took this same code and for the click event to work I have to copy the js, and put on the console, then I can go back and click there on the magnifying glass, you even click on the magnifying glass?

  • You even opened the link I put in the first comment?

  • My version is: Version 71.0.3578.98 (Official version) 64 bits

  • Yes, in jsfiddle, it works, but probably because it doesn’t have an icon of fontawesome, but when I separated this two code one in html and the other in js tbm didn’t work, I even did a local test on your machine?

  • I get it, the problem is that Fontawesome is going to trade the element for an SVG and the onclick that had there will be no more.

  • Some way for this to go the way I imagine?

  • I’m not going to be able to formulate an answer right now, but I’m going to give you a piece of advice: <div class="search"> for <label class="search">. You are trying to simulate the behavior of a label, it is easier to use the same label.

  • You can leave, I’ll fix this, but I wanted to understand why I paste the code on the console, it makes it work?

  • You are assigning a auto-invoked function to the onload variable. This function is triggered at the time of its assignment... That is, it runs even before the onload is fired. https://www.w3schools.com/js/js_function_definition.asp

  • When pasting in the console, the page has already loaded and you are assigning the variable again, causing it to be invoked again... To correct just remove the parentheses of the function at the end of the function

  • Another issue is the use of Arrow Function, will work in very few browsers.

  • Actually Arrow Function already has a very decent support. 93.49% according to the caniuse

  • I have already taken out the immediate function, and the situation remains the same, does not change anything, and as it is inside an onload it only runs after the same loading

Show 11 more comments

2 answers

0


Guys, I found a way to solve, I ended up including the same inline code:

<i class="fas fa-search" onclick="nomedafuncaoquetornaclicavel()"></i>   

0

First you’d better use the method Element.addEventListener() to listen to events, the methods onevento are old and allow only one event Handler in the element.

Ex.:

let elemento = document.getElementById('meu-elemento')
elemento.onclick = minha_funcao

Would be:

let elemento = document.getElementById('meu-elemento')
elemento.addEventListener('click', minha_funcao)

So in your case you could use:

window.addEventListener("load", function(event) {
    console.log("Página carregada");
});

You also need to understand that when you use Immediately Invoked Function Expression the variable will receive the result of the function, not a function (which is what is expected to receive as a Handler of events).

Ex.:

let valor_1 = (function(){ return 'Função 1'; })()
let valor_2 = function(){ return 'Função 2'; }

console.log(valor_1)
console.log(valor_2)
console.log(valor_2())

Even applying the previous concepts you would have problems, because the script is using the attribute defer. You’d have to listen to the event DOMContentLoaded for your function to run after the script is run.


Now, the main point is that you are creating a script that only serves to focus on an input when there is already an element that does this natively for you, the <label>.

<label>
  <input type="search">
  Click
</label>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.