I recently created a small website where I dynamically add code to HTML divs. Once the data is set, I attach click and mouse enter/leave events using the div's ID. The site consists of plain HTML, javascript, and CSS.
However, I noticed that when I view the page on a small screen size, the events attach properly. But when I resize the screen or open it on a larger device, the events do not work as expected.
I tried using both the ID and class selector for setting event listeners, but the result was still the same. Additionally, I attempted to set the event listener based on the screen size update (media query), but the issue persisted. The HTML and CSS are only set once during loading.
I suspect the problem may be related to a timeout issue. How can I troubleshoot this effectively?
Javascript
const elements = document.querySelectorAll('div.myClass');
if (window.matchMedia("(max-width: 800px)").matches) {
/* The viewport is less than, or equal to, 800 pixels wide */
console.log(at 800+"this works, but");
} else {
/* The viewport is greater than 800 pixels wide */
console.log("this is not working");
[...elements].forEach( (el) => {
el.addEventListener('click', masterEventHandler, false);
el.addEventListener('mouseenter', inFunction, false);
el.addEventListener('mouseleave', outFunction, false);
});
}
This is the setup code I used for the container:
function display(id){
var container = document.getElementById("myContainer");
var element = document.createElement("div");
var containedElement = document.createElement("div");
element.id = id;
element.className = "myClass";
containedElement.className = "tohideStuffOnLoad";
element.appendChild(containedElement);
container.appendChild(element);
}
The following is the compiled code which remains the same throughout the lifetime of the app:
<div id="container">
<div id="id" class="inner">
<div id="amnt" class="amount">$43,762.00</div>
<div class="h-overlay m-display">This is the title
<div class="img"><span>▶</span></div>
</div>
<img src="/animage.jpg" alt="my-image">
<div class="ribbon-new"><img src="/new-ribbon.png" alt="ribbon"></div></div>
</div>
Upon inspecting the element, I noticed that the m-display property toggles correctly on a screen size of 800 pixels or smaller but does not function on larger screens.
No errors were displayed aside from the fact that my events were not firing.
When examining the Event Listeners, they appeared standard:
var inFunction = function(event){
//console.log(event);
event.target.children[1].classList.remove("m-display");
};
var outFunction = function(event){
//console.log(event);
event.target.children[1].classList.add("m-display");
};
var masterEventHandler = function(e){
console.log("Here I redirect to some other stuff");
};
Although I provided this information, I don't believe it changes anything fundamentally.