Doug Fir
Doug Fir

Reputation: 21232

Struggling to add event listener to array or Node List

I have an object confBtns that contains two buttons based on the following html:

<footer>
  <button id="authCreateAcctConfirmNoBtn" class="button2">
    No
  </button>
  <button id="authCreateAcctConfirmYesBtn" type="submit" class="red-button">
    Yes
  </button>
</footer>

What I would like is that when someone clicks either of these buttons, then "Yes" or "No" is then put through a function like so:

dataLayer.push({
    "event":"ButtonBlur",
    "elementText": /*What goes here to grab Yes or No depending which blurred? */
}); 

I could just write two separate scripts and add an event listener to each button like so:

document.querySelectorAll("#authCreateAcctConfirmYesBtn")[0].addEventListener("blur", 
    dataLayer.push({
        "event":"ButtonBlur",
        "elementText": "No"
    )}
); 
);

Then the same for the Yes button.

But how do I do it in a oner?

I tried adapting this SO post to my need but I'm spinning my wheels. Here is what I tried in the console:

var confBtns = document.querySelectorAll("#authCreateAcctConfirmYesBtn,authCreateAcctConfirmNoBtn");

btnPush = function() {
    dataLayer.push({
        "event":"ButtonBlur",
        "elementText": /*What will go here to be Yes or No?*/
    })
};

function addEventListenerConfBtns (btns, event, fn) {
    for (var i = 0, len = btns.length; i < len; i++) {
        btns[i].addEventListener(event, fn, false);
    }
}

addEventListenerConfBtns(confBtns, "blur", btnPush);

So I really have two questions:

  1. How do I get my function to work?
  2. How do I dynamically pass Yes or No for the value of "elementText"?

When I run this in the console I just get "undefined". I expected to be able to click and then blur a button, and then see the values of the dataLayer in the console. But no values for dataLayer from the function btnPush were present.

Upvotes: 0

Views: 1123

Answers (1)

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

You are messing the events. The event you really need is click, not blur, because it could be triggered when user navigates with tab, for instance.

addEventListenerConfBtns(confBtns, "click", btnPush);

And in your btnPush you receive the event as the first argument, and the target property of the event is the clicked element, so:

btnPush = function(e) {
    dataLayer.push({
        "event":"ButtonBlur",
        "elementText": e.target.innerText
    })
};

I didn't tried but it should work.

Upvotes: 1

Related Questions