0

Dealing with a particular case where there are a number of elements with inline onclick event triggers that also pass a variable that need to be preprocessed through an addEventListener with the original onClick removed, preferably through removeAttribute as opposed to setAttribute("onclick", null).

<div onClick="alert('shoe');">shoe</div>
<div onClick="alert('epic');">epic</div>
<div onClick="alert('dogs');">dogs</div>
<div onClick="alert('army');">army</div>

For the sake of reuse and usefulness to others - the example above is simplified however there is no need to handle IE attachEvent or detachEvent and jQuery is not available (for me at least).

I've tried several approaches and my initial trial code looked like the following:

var fields = document.getElementsByTagName("div");
    for (var i = 0; i < fields.length; i++) {
        word = fields[i].getAttribute("onClick").substr(7,4);
        fields[i].addEventListener("click", function() {console.log(word);}, false);
        fields[i].removeAttribute("onclick");
    }

Needles to say in most derivative approaches i've either managed to remove the onclick but couldn't assign the event listener, could populate a words array but only with the last word and so forth.

  • possible duplicate of [How to generate event handlers with loop in Javascript?](http://stackoverflow.com/questions/6487366/how-to-generate-event-handlers-with-loop-in-javascript) – Felix Kling Jul 29 '13 at 20:32
  • indeed, thank you @FelixKling - that article you pointed to is somewhat helpful for this situation and i've looked on it several times before posting this question... essentially, what i think i'm dealing with (despite a lack of understanding of proper syntax and how dom methods work) is once i've made an array of element pointers i don't really know how to get each element's attribute, parse that attribute and assign each element (individually) an `addEventListener` with the previously parsed attribute... – user2630942 Jul 30 '13 at 13:38
  • i've tried local loop procedure to parent array push to the point of using either several functions or closures within closures and all i end up with is only partially useful and breaks... i'm clueless as to a solution at this point. – user2630942 Jul 30 '13 at 13:39
  • You can do it like in the accepted answer: Create a function and put the code your currently have in the loop body in the function. Call the function in the loop and pass the element as argument. Like `function bindHandler(element) { var word = element.getAttribute.... } ... for (....) { bindHandler(fields[i]); }` – Felix Kling Jul 30 '13 at 14:21
  • Managed to come up with a solution and my main error was not passing the right variable to the closure and indeed it was the solution i was looking for. Made a fiddle here http://jsfiddle.net/GhPKq/ for anyone looking for insight to the same problems. Also thanks for your effort @FelixKling. – user2630942 Jul 30 '13 at 15:05

0 Answers0