Abozanona
Abozanona

Reputation: 2285

click addEventListener is called without been clicked

I'm trying to add a function Fvote to all elements with class vote-up and vote-down.

var voteup = document.getElementsByClassName("vote-up");
var votedown = document.getElementsByClassName("vote-down");

function Fvote(upordown,postid) {
    var x=this;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {console.log(xmlhttp.responseText);
            if(xmlhttp.responseText=="error")
                ;
            else{
                /*some JS actions*/;}
    }
    xmlhttp.open("GET", "ajax/vote.php?q=" + postid + "q2="+upordown, true);
    xmlhttp.send();
}

for(var i=0;i<voteup.length;i++)
    voteup[i].addEventListener('click', Fvote("up",voteup[i].getAttribute("data-vote")), false);

for(var i=0;i<votedown.length;i++)
    votedown[i].addEventListener('click', Fvote("down",votedown[i].getAttribute("data-vote")), false);

But when I load the page, it runs the function Fvote many times as the count of elements number, without clicking on any item. and if I clicked on items with class of vote-up or vote-down the function is not called. What I'm doing wrong?

Upvotes: 1

Views: 93

Answers (2)

blex
blex

Reputation: 25634

You can get the parameters from within the function:

var voteup = document.getElementsByClassName("vote-up");
var votedown = document.getElementsByClassName("vote-down");

function Fvote(e) {
    var x = e.target,
        upordown = x.className.indexOf('vote-up') > -1 ? 'up' : 'down',
    //  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        postid = x.getAttribute('data-vote');
    //  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        console.log(xmlhttp.responseText);
        if(xmlhttp.responseText=="error") {
                /*some JS actions*/
        } else {
                /*some JS actions*/
        }
    }
    xmlhttp.open("GET", "ajax/vote.php?q=" + postid + "q2="+upordown, true);
    xmlhttp.send();
}

for(var i=0;i<voteup.length;i++)
    voteup[i].addEventListener('click', Fvote, false);

for(var i=0;i<votedown.length;i++)
    votedown[i].addEventListener('click', Fvote, false);

Upvotes: 1

Amit
Amit

Reputation: 46323

You got the wrong idea of how addEventListener works.

Basically it registers an event handler, which is an "address" of a function to execute when the event occurs. What you're doing is CALLING the function and EXECUTING it inside the loop.

Here's how it's normally used:

function handle() {
  alert('An event!');
}

myElement.addEventHandler('click', handle);

Note that in this fragment, handle is passed without parenthesis thus "passing in the address", not invoking a call.

Upvotes: 0

Related Questions