0

I have a very simple html file that contains an input element. Whenever the input element is focused on, I want to console.log a message. What happens is, the console.log is fired immediately upon the loading of the page, and never again. I can't use inline onfocus and no jquery. Here is what I've tried.

first

<html>
<body id="fname" >
    <input id="fname" type="text" >
</body>
<script>        
    window.onload = () => document.getElementById("fname").addEventListener(`onfocus`,console.log(`hi`));
</script>
</html>

second

<html>
<body id="fname" >
    <input id="fname" type="text" >
</body>
<script>
    window.onload = () => document.getElementById("fname").onfocus = console.log(`hi`);
</script>
</html>

What gives?

  • Possible duplicate of [setTimeout -- callback executed immediately?](https://stackoverflow.com/questions/8462381/settimeout-callback-executed-immediately) – str Jan 17 '18 at 20:39
  • The first argument to `addEventListener` should be `"focus"`, not `"onfocus"`. – Barmar Jan 17 '18 at 20:58

3 Answers3

1

I think it's because you're not passing in a function to the onfocus event. Try this:

<html>
    <body id="someOtherId" >
        <input id="fname" type="text" >
    </body>
    <script>
        window.onload = () => document.getElementById("fname").onfocus = () => console.log(`hi`);
    </script>
</html>
dhuang
  • 909
  • 4
  • 18
1

The console.log statement is executed immediately,

To execute the listener onfocus, you want to wrap it in a function body:

document.getElementById("fname")
    .addEventListener(`onfocus`, () => console.log(`hi`) );
Steven
  • 381
  • 2
  • 10
1

You have a duplicated id on the body and didn't provide a function for the onfocus-event.

A working version:

<html>
  <body>
    <input type="text" >
    <input id="fname" type="text" >
  </body>
  <script>
    document.getElementById("fname").onfocus = function() {
      console.log("hi");
    }
  </script>
</html>

I added another input so you can switch between them and see the event fire only on the second one.

thutt
  • 640
  • 5
  • 18