On a smaller screen size, the event listeners I add dynamically are successfully attached using the exact same HTML, however, they fail to attach on a larger screen size

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.

Answer №1

Alright, let's dissect the issue:

The parent container had a transparent background. The z-index was mistakenly higher than the content beneath it. The container was obstructing the content below. This problem was specific to large screens only... So unfortunately, click methods were not functioning for the obscured content :(

Fortunately, the issue was not related to my Javascript. Appreciate all the assistance provided.

Answer №2

Check out the code snippet below:

let items = document.querySelectorAll('section.mySection');

This grabs all elements with the class .mySection. It's possible that new elements are being inserted into .mainContainer after a page refresh, which were not originally selected.

To address this issue, consider updating the element list when the window is resized.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Time to reverse the string

I currently have a timestamp formatted like this: Thu Sep 12 04:28:37 +0000 2013 While I am aware that PHP's strtotime function allows for inputting things like '2 days ago' or 'last week', my goal is to take the existing timesta ...

Button with tooltip for easy access to trigger a modal dialog

My task involves creating a button with a tooltip that displays simple statistical information to the user, such as a student's grades (e.g., "Homework: 100%, Exams: 85%"). Upon clicking the button, a modal should appear with more detailed information ...

Check and uncheck checkboxes in a hierarchical structure in real-time

I am facing a similar question to a previously solved issue regarding unchecking parent nodes if all children are unchecked using JQuery, but I am attempting to enhance the solution by ensuring that the children will also all uncheck if the parent is unche ...

Modifying the TITLE dynamically post header insertion: A guide

Is there a way to dynamically change the title of an HTML page based on the content included below the header section using PHP? For example: <html> <header><title>I would like to change</title></header> <!--CONTENT--> ...

Tips for maintaining the original Backbone template when reloading the browser

Within my Backbone application (with a Rails backend), I utilize [Handlebars] JavaScript templates (JST's) to render the Backbone views. However, whenever I refresh the browser while on a URL template, it always redirects me back to the root URL. I am ...

Question about React.js: What is the best way to add multiple classes to a component by using a ternary operator?

I am looking to apply multiple classes to a component by utilizing a ternary operator. In our shared ts theme file, we have the general button styles defined, but for this specific component, I want to adjust the sizes based on screen width. To achieve thi ...

Node.js function failing to return any value

I am facing an issue with retrieving the value of a function as it is not returning anything. Below is the function I am using (Request is an async function that sends a get request): var getVolumesOKCoin = function(pair){ request('https://www.okc ...

Open the link and input the text into the text box?

Suppose I have the following JavaScript code: <script language="javascript" type="text/javascript"> function addText() { var newText = document.myForm.inputText.value; document.myForm.description.value += newText; } </script> I want t ...

Interactive image grid with adjustable description field per image upon selection

My goal is to create a grid of images with a single text field below the grid. This text field should display the description of the image that was last clicked. The grid is implemented using floating divs within a main div, as shown in the code snippet be ...

Struggles with toggling a sliding menu using JQuery

As I work on constructing a menu, I've implemented submenus that slide down upon hovering over the parent item and remain expanded when clicking on an arrow next to the parent. While the hovering functionality is working correctly, I'm encounteri ...

Having trouble adding two controller.js files to the same HTML page. The error message "Argument {mycontroller} is not a function, got undefined" keeps popping up

I recently started learning Angular and I'm facing a challenge with nested Angular controllers. I have stored all the controllers in separate .js files. The main controller on my webpage needs to include another controller called 'UploadControll ...

Creating MySQL queries programmatically using data stored in a JSON object

Is it possible to construct a MySQL query dynamically from a JSON object with potentially empty values? For instance, starting with an object like this: { "a": 1 "b": "" "c": "foo" } we want to generate a query like the following (ignoring the emp ...

Utilizing image backgrounds for hyperlinks in the Android browser

Encountering a minor issue with some <a> tags that have images as background, and the text inside the tags is indented using CSS. However, on the Android browser, part of the string used in HTML appears to cover the background image within the area o ...

Create PDFs using PhantomJS when the HTML content is fully loaded and ready

I am a newcomer to utilizing phantomjs and encountering difficulties in rendering my website as a PDF file. Although I can successfully render a simple version of the page, issues arise when multiple images and web fonts are involved, causing the DOM not t ...

Update the data in Firebase, but revert it back to the original state after a few seconds with the use of "angularFire."

I'm currently working on updating data in the Firebase Realtime Database using Angular and AngularFire. The issue I'm facing is that even though the data changes successfully, it reverts back to the original data after a few seconds. Below is the ...

What is the most efficient way to choose the correct value from an HTML drop-down list based on the name and ID that is provided?

Is there a way to automatically select the value in a drop-down list from HTML based on the name and ID I receive? I need this functionality to edit information from the database. I've tried using this code but it's not displaying the correct op ...

Discover the magic of using the spread operator to effortlessly insert key-value pairs into an object!

Currently, I am grappling with the challenge of handling variable products using the spread function. For instance, in an online store selling clothes (similar to the screenshot linked below), I am looking to track when a user adds different sizes of the s ...

Utilizing VueJs (Quasar) to access vuex store within the router

Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I notice ...

Review the file's content prior to uploading

Before uploading a zip or rar file to the server, I need to ensure that the content is safe and not malicious. Let me paint the picture for you. In my web project, there are two types of users: 1: Regular registered users 2: Project administrators Any ...

Plow through the contents of the S3 Bucket, exploring every Folder and File

I've encountered an issue while iterating through an S3 bucket using s3.listObjects. The error message { [UnexpectedParameter: Unexpected key 'Key' found in params] has been popping up. Below is the snippet of code I'm currently working ...