franenos
franenos

Reputation: 357

Can't fire JS properly with addeventlistener

Two examples: JSfiddle without evenlistener and JSfiddle with eventlistener

The base code for both of them is:

HTML

<body>

</body><p id="one" tabindex="0">ID one of tag P</p>
<input id="two" type="text" value="An input field">
<button id="three">A Button</button>

<p id="showid" tabindex="0"></p>

JS

function myFunction() {
    var x = document.activeElement.id;
    document.getElementById("showid").innerHTML = x;
}

In order the script will work I added the onclick="myFunction()"(see first example at JSF), but if I'm adding an eventlistener instead of onclick="myFunction()" I'm not getting the proper result.

The JS code with eventlistener:

document.addEventListener('DOMContentLoaded', function myFunction() {
    var x = document.activeElement.id;
    document.getElementById("showid").innerHTML = x;
}, false);

What am I doing wrong here?

Upvotes: 0

Views: 495

Answers (2)

Jesse Lee
Jesse Lee

Reputation: 1301

Your question is hard to understand but based on your comments and the example I think what you're wondering is how to get your function to execute on the DOMContentLoaded.

Indeed your function is firing on load...

The reason it appears your function isn't firing is because when using the DOMContentLoaded event your 'p' element is not active at the time you are assigning it to x, so x is undefined.

document.addEventListener('DOMContentLoaded', function myFunction() {
    document.getElementById('one').focus();
    var x = document.activeElement.id;
    document.getElementById("showid").innerHTML = x;
}, false);

By setting focus first, now your code works.

Upvotes: 0

ilken
ilken

Reputation: 46

In your first example click event is attached to the body.

<body onclick="myFunction()">

"click" event can be used instead of 'DOMContentLoaded' to get the same result:

document.addEventListener('click', function myFunction() {
    var x = document.activeElement.id;
    document.getElementById("showid").innerHTML = x;
}, false);

Upvotes: 1

Related Questions