Is it possible to have multiple divs with unique IDs that can be individually controlled using a single JavaScript function?

I'm in the process of figuring out how to create a single JavaScript function that can manage multiple divs.

I currently have several divs with distinct ids and I've written separate JavaScript functions for each one. However, they either do not function correctly or only one of them works properly.

I suspect that they may be conflicting with each other and I'm exploring the possibility of using a single JavaScript function while still maintaining unique ids for each div.

Below is a basic example of my current setup:

Note: the script is designed to close a window when a user clicks outside a "container" window. Currently, only clicking on the last yellow container triggers the desired action.

var modal = document.getElementById('window-one');

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

var modal = document.getElementById('window-two');

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

var modal = document.getElementById('window-three');

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
div {
  border: solid 2px black;
  height: 20px;
  background: yellow;
  margin: 5px;
}
<div id="window-one" class="container-one">1</div>
<div id="window-two" class="container-two">2</div>
<div id="window-three" class="container-three">3</div>

Answer №1

One issue is that the same variable is declared three times with different values, globally. This means it gets overwritten each time.

A better solution would be to add a common property to all modals (e.g. a className), select them all, determine which one is clicked, and perform actions accordingly.

Here is a simple example:

const modals = document.querySelectorAll('.modal')

const doStuffWithModal = (modal) => modal.style.display = 'none'

modals.forEach(modal => modal.addEventListener('click', () => doStuffWithModal(modal)))
.modal {
width: 100px;
height:100px;
background:red;
margin: 20px
}

.modal.container-two {
background:blue
}
.modal.container-three {
background: green
}
<div id="window-one" class="container-one modal"></div>
<div id="window-two" class="container-two modal "></div>
<div id="window-three" class="container-three modal" ></div>

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

Pattern matching tool for identifying React components with an unlimited number of properties

Currently diving into MDX and experimenting with Regex to extract details on React components from Markdown files. The regex pattern I'm aiming for should: Detect all types of React components This includes identifying the opening tag <Component ...

Can angular and grunt support multiple run blocks simultaneously?

Currently, I am configuring $httpBackend to simulate fake API routes while our team of API developers is building them out. However, I am facing an issue where I have to place all the $httpBackend configurations within my run block. This leads to a situa ...

How to style a CSS list and center-align it

My website features a <ul> list with submenus structured like this: <div id="cssmenu"> <ul> <li class='active'><a href='index.html'><span>Home</span></a></li> <li class=&ap ...

What is the method for creating a fixed position div that remains until a certain point?

Is there a way to prevent the position: fixed; property from being applied after a certain point on the screen scroll using only CSS? ...

Is there a way to dynamically update the text of $ionicPopup's subTitle in Ionic?

I am currently attempting to modify both the value and style of the subText attribute linked to an $ionicPopup within my app. Despite searching extensively, I have been unable to uncover a viable method for accomplishing this task. Is there a way to achi ...

What is the best way to sequentially slide down multiple elements with a time delay in between each one?

I have multiple div elements with the same class. I have selected them all and I am iterating through each one to slide down every element. My goal is to first slide down the initial element, then introduce a delay before moving on to the next slide. Here ...

CSS Element Overlapping Issue in Safari Browser

I am currently developing an audio player for my application that includes a pause/play button, next button, and back button. I have encountered a problem specifically on Safari where the back/pause buttons are overlapping each other. The play/pause button ...

Is there a way to retrieve the id of an input field using PHP?

I am faced with a situation where I have an HTML input field that is specified with a unique id. My goal is to use this input field id to identify the field effectively. For example: <input type='text' id='float' name='attribu ...

What is the best way to transform an associative array into a sorted string array?

I am trying to convert the following JS object into a string array that is sorted by value: var obj1 = {"user1":28, "user2":87, "user3":56}; The desired output should be like this: ["user2","user3","user1"] ...

Adjust the GTK3 tooltip color exclusively for Eclipse when it is operating on Ubuntu

I am using Eclipse Mars on Ubuntu 15.04 and looking to customize the GTK3 tooltip fg/bg color specifically for Eclipse without impacting other applications. I have come across instructions for changing this color system-wide, but I need guidance on how t ...

Exploring jQuery functionality through data attributes

I'm having trouble implementing the search functionality using the data-find attribute. Currently, my function is simply matching the input string with any text inside the container. You can test this by adding more words to the HTML and then enterin ...

Experience an endless array of objects

This demonstration showcases the ability to navigate within a group of spheres within specific boundaries. My goal is to explore infinitely among them. What steps should I take to achieve this? ...

Is it possible in Angular.js to limit the visibility of a service to only one module or to a specific group of modules?

When working with Angular.js, the services declared on a module are typically accessible to all other modules. However, is there a way to restrict the visibility of a service to only one specific module or a selected group of modules? I have some service ...

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

Rules of HTML tables extend to the border size

Check out this HTML code snippet: div { border: 2px solid red; height: 50vh; width: 50vw; } table { border: 1px solid; table-layout: fixed; } <div> <table rules="cols"> <tr> <th>Name</th> < ...

Panning is not compatible with shared camera OrbitControls

I am attempting to set up two renderers on separate div containers. Each renderer should have its own OrbitControls to update the camera associated with it. However, the camera is shared between the two renderers. The objective is to synchronize the camer ...

Is it achievable to dynamically generate new pages on initial load in NextJS?

Right now, I am utilizing getStaticProps and getStaticPaths to pre-render a specific number of articles before my website goes live. This method works effectively, but if a new article is created and displayed on the front page while the site is still acti ...

Utilize OpenLayer3 to showcase Markers and Popups on your map

I am currently exploring how to show markers/popups on an osm map using openlayers3. While I have come across some examples on the ol3 webpage, I'm interested in finding more examples for coding markers/popups with javascript or jquery, similar to som ...

Tips for effectively managing relationships in a RESTful API

Exploring the concept of REST architecture through the development of a RESTful service for an 'Issues Tracking Application'. In this application, users, projects, issues, and comments are integral components. The relationships are outlined as f ...

I would like to showcase the image with specific dimensions in CakePHP

Currently working on a CakePHP application where I need to upload an image. However, for some sections of my app, I need to display the image at a specific height and width without losing image quality. Any suggestions on how to achieve this? ...