Durden Durden - 1 year ago 74
Javascript Question

addEventListener() not working on small screens

I've got a table on my wordpress, with a button on each row, which creates a small form when you click on it (on this page).
It's working perfectly fine, except when you change your browser's width to <768px, then nothing happens.

This is my main call :

var buttons = [];
if (jQuery(window).width() > 768)
buttons = document.querySelectorAll('td button');
buttons = document.querySelectorAll('div button');

Add a click event to all buttons inside the table
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', clickCheck);

On small screens, the table elements become divs, so I had to define the
array differently.

Now this is the
function :

function clickCheck(e) {
// if first click on the button
if (e.target.textContent === 'Inscription') {
// Cleaning an eventual earlier click on another button
for (var j = 0; j < buttons.length; j++) {
if (buttons[j].textContent === 'Fermer') {
buttons[j].textContent = 'Inscription';

// Popping the form
e.target.textContent = 'Fermer';
// if form submission
else {
// Depopping the form
e.target.textContent = 'Inscription';

On screens smaller than 768px, the 'ok' isn't appearing in the console, so the event isn't read. I've checked and my
array is fine even on small screens, so the problem has to come from

Any clue ? :)

Answer Source

There's a lot of code running in your page so I don't know the root case, but here's the general problem.

When you do this at startup:

 buttons = document.querySelectorAll('div button');

You are getting a different array of button elements than what ends up visible in your page. You can physically compare the original buttons array with what happens when you run a new document.querySelectorAll('div button') at the time of the click (I did so in the debugger). The first will contain 10 buttons, the second will contain 20 buttons. I think some code in your page is generating dynamic content AFTER you hook up the event handlers and what you're seeing and interacting with in the page is the dynamic content that was created after you ran your code to add click handlers so the visible content has no event handlers on it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download