Prog Grl
Prog Grl

Reputation: 37

button onclick event to occur only once usin DOM addEventListener()

I am creating dynamic set of buttons

for (var i = 0; i < clr.length; ++i) {
    button = document.createElement("button");
    button.innerHTML = clr[i];
    button.addEventListener('click', event);
    button.style.backgroundColor = clr[i];
    document.body.appendChild(button);
}

but I want the event to occur "only once" for each button. But I am unable to implement this correctly using javascript .

Upvotes: 0

Views: 172

Answers (1)

Praveen
Praveen

Reputation: 56509

You can remove the attached event using removeEventListener once after it executed. By doing this the click event is handled only once as mentioned below,

function event(e) {  //e represented the current element which is clicked
    e.target.removeEventListener(e.type, arguments.callee);
    alert('hi');
}

JSFiddle

Upvotes: 1

Related Questions