Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struggling to add a blur event listener

I have a searchbox on the site I work on and would like to track the search terms folk are looking for.

Since the searchbox auto guesses what someone is typing and searches for it, there is no click event.

In the console the textContent that I want when the blur happens is the .textContent of this:

myVar = document.querySelectorAll('.twitter-typeahead > span')[2]

But the value returned here is only not null when someone has actually typed something. So attaching a blur event seems the way to go. On the back of someones help on another forum I got this far in the console:

myVar.addEventListener('blur', function(){dataLayer.push({'event':'bla'})})

After typing this all in the console I don't see any values being pushed to the dataLayer which makes me think that the blur event is not working (as opposed to the dataLayer.push function.)

The page with the searchbox in question is here.

How would I attach a blur event to someone unfocussing the search box?

like image 476
Doug Fir Avatar asked Aug 12 '14 18:08

Doug Fir


People also ask

Why is my add event listener not working?

The "addEventListener is not a function" error occurs for multiple reasons: calling the method on an object that is not a valid DOM element. placing the JS script tag above the code that declares the DOM elements. misspelling the addEventListener method (it's case sensitive).

Which is the correct method to add an event listener?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

Why is Onblur not fired?

You can add tabIndex={0} to outermost div in order to dismiss keyboard from input. If the element that has the onBlur effect and tabindex is created onClick of another element, it does not automatically gets focus when it appears. Thus, you may need to focus it using element. focus() after creating the element.


1 Answers

You should add the blur listener to the search box, not a span:

searchbox = document.getElementById('searchboxID');
searchbox.addEventListener('blur', function() {
    var input = this.value;
    // Do whatever you want with the input
});
like image 179
Barmar Avatar answered Sep 27 '22 20:09

Barmar