Event listeners that execute without event and loop through the HTML collection

I am trying to write a loop to initialize event handlers in JavaScript.

I think I am doing something wrong because my debug function is fired without an event (click).

I want to do the following:

var JS_elements = document.getElementsByClassName("JS")

for (y = 0; y < JS_elements.length; y++){
    document.write(JS_elements.item(y).innerHTML);
    JS_elements.item(y).addEventListener("click",testfunc());
}

function testfunc() {
    alert("TestFunc");
}

      

and run testfunc () when I click on the element with class = "JS".

The line document.write(JS_elements.item(y).innerHTML);

is being executed correctly, so I know I am getting to the correct objects. Unfortunately, the commented line causes a violation: testfunc () runs three times automatically on page load.

Can anyone explain why this is happening? The only thing I can think of is that "click" is evaluated as for some reason true

.

HTML:

<header>
    <hr>
        <p>- Header Background Color Controller -</p>
        <table>
            <tr>
                <td>Javascript Controller:</td>
                <td class="JS">Red
                    <input type="hidden" value='false'>
                </td>
                <td class="JS">Green
                    <input type="hidden" value='false'>
                </td>
                <td class="JS">Blue
                    <input type="hidden" value='false'>
                </td>
            </tr>
            <tr>
                <td>jQuery Controller:</td>
                <td class="jQ" value=false>Red</td>
                <td class="jQ" value=false>Green</td>
                <td class="jQ" value=false>Blue</td>
            <tr>
        </table>
    <hr>
</header>

      

+3


source to share


2 answers


Change this:

JS_elements.item(y).addEventListener("click",testfunc());

      

:

JS_elements.item(y).addEventListener("click",testfunc);

      



()

causes the immediate execution of the function, and the return result is passed to addEventListener()

. This is not what you want. Instead, you want to pass a function reference, which should just be the name of the function, testfunc

with no ()

after it.


If you want to pass arguments to testfunc

, and they are the same arguments for all event handlers, you can create an intermediate anonymous function:

JS_elements.item(y).addEventListener("click",function() {
    testfunc("whatever");
});

      

+4


source


Just do the following: JS_elements.item(y).addEventListener("click",testfunc);



+1


source







All Articles