Hide multiple divs with similar ids in JQuery when clicking outside of them

Is there a way to hide all div elements with similar id if none of them are clicked on? Currently, my code only works for the first div because I am using index[0] to retrieve the id. How can I make it work for all ids?

Below is the code snippet:

$(window).click(function(e) {
  if (e.target.id != $('[id^=div_]')[0].id) {
    $('[id^=div_]').hide();
  }
});
div {
  height: 150px;
  width: 150px;
  display: inline-block;
  background: green;
  margin: 10px;
  color: #fff;
  text-align: center;
  line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1">One</div>
<div id="div_2">Two</div>
<div id="div_3">Three</div>
<div id="div_4">Four</div>

FIDDLE

Answer №1

To easily solve this issue, you can assign a common class to all the elements and then use the is() method to check if the e.target belongs to any of those elements. You can then show or hide them accordingly. Give this a try:

$(window).click(function(e) {
  if (!$(e.target).is('.common-class')) {
    $('.common-class').hide();
  }
});
.common-class {
  height: 150px;
  width: 150px;
  display: inline-block;
  background: green;
  margin: 10px;
  color: #fff;
  text-align: center;
  line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="element_1" class="common-class">One</div>
<div id="element_2" class="common-class">Two</div>
<div id="element_3" class="common-class">Three</div>
<div id="element_4" class="common-class">Four</div>

If modifying HTML by adding classes is not an option for you

In that scenario, you can inspect the clicked element's id to determine if it starts with element_. If it doesn't match, you can hide all the elements with IDs starting with that prefix. Here is how you can do it:

$(window).click(function(e) {
  if (e.target.id.indexOf('element_') != 0) {
    $('[id^=element_]').hide();
  }
});
.common-class {
  height: 150px;
  width: 150px;
  display: inline-block;
  background: green;
  margin: 10px;
  color: #fff;
  text-align: center;
  line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="element_1" class="common-class">One</div>
<div id="element_2" class="common-class">Two</div>
<div id="element_3" class="common-class">Three</div>
<div id="element_4" class="common-class">Four</div>

Answer №2

Feel free to utilize this handy function:

if(e.target.id=="" || $('[id^=div_]').filter('#'+e.target.id).length==0){
     $('[id^=div_]').hide();
  }

The filter function is designed to sift through a list of div elements whose id starts with 'div'

$(window).click(function(e) {
  if(e.target.id=="" || $('[id^=div_]').filter('#'+e.target.id).length==0){
     $('[id^=div_]').hide();
  }

});
div {
  height: 150px;
  width: 150px;
  display: inline-block;
  background: green;
  margin: 10px;
  color: #fff;
  text-align: center;
  line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1">One</div>
<div id="div_2">Two</div>
<div id="div_3">Three</div>
<div id="div_4">Four</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

Utilize JavaScript to implement CSS using an "if" statement

I am currently working on implementing iOS web app properties into my website. My goal is to create a <div> at the top of the page and apply specific CSS styles when a certain condition is met in a JavaScript script. Unfortunately, I am facing issue ...

Unstyled Cards Failing to Receive Design

I am currently working on creating a prototype that utilizes two Bootstrap 4 cards to display information from a form and store related information from another form in the second card. The current layout of this setup can be observed below: This JSFiddle ...

Retrieve telephone number prefix from Cookies using React

Being able to retrieve the ISO code of a country is possible using this method: import Cookies from 'js-cookie'; const iso = Cookies.get('CK_ISO_CODE'); console.log(iso); // -> 'us' I am curious if there is a method to obt ...

Creating a custom URL following a redirect in Contact Form 7 to ensure a unique

This is the code I am currently using: <script type="text/javascript> document.addEventListener( 'wpcf7mailsent', function( event ) { location = 'https://www.example.com/thank-you/'; }, false ); </script> With this ...

What is the best method for creating an HTML table using a JSON object?

Currently, I am in the process of developing an express app that can render a csv file and convert it into a json format. Within my method, I have this json data stored as a variable and my goal is to display it as a table on an HTML page. How can I effect ...

Ways to automatically refresh the div block's content whenever new data is added or updated in the database

Is there a way to automatically refresh the div block whenever there is activity in the database? I attempted using the setInterval function, but I'm looking for a solution that will update or insert data into the block based on updates made to the da ...

Loop through the .getJSON response using jQuery

I've searched high and low for an answer to my question, but I can't seem to find one. My issue is with iterating over a JSON array (and its object) using jQuery's .each() method to print out all the values. Here is the JSON structure: { ...

"Exploring the process of implementing a fixed method POST in Angular 5

When developing an application for Portal, I encountered an issue where a newly created role is not displayed without refreshing the browser. How can I ensure that the added element is directly displayed in the table without needing to refresh the browser? ...

When attempting to extract values from selected items in Nextjs, clicking to handle them resulted in no action

I am facing an issue with my Nextjs project. I am trying to gather values from select items and combine them into a single object that needs to be processed by an API. However, when I click the select button, nothing happens. How can I resolve this issue? ...

Data transmission from Node's hosted router to an external API, not from Node's hosted API

Need a Node router that can POST Json to a remote API? I dedicated my morning to solving this issue, and now I want to share some detailed examples with you for your benefit. In each example below, the router includes a GET method that, when called, will ...

JavaScript animation not functioning properly when height is set to "auto"

Can someone help me figure out why setting the height to "auto" in the code snippet below isn't working as expected? I want the DIV to adjust its size based on the content, but it's not happening. Any ideas on how to fix this issue would be great ...

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

Reveal unseen information on the webpage upon clicking a link

I have successfully implemented a fixed header and footer on my webpage. The goal is to make it so that when a user clicks on a link in either the header or footer, the content of that page should appear dynamically. While I have explored various styles, ...

Why isn't my jQuery click event triggering?

Visiting this PAGE and scrolling down, you'll find the following code snippet: HTML <ul class="play_navigation"> <li class="active"gt;<a class="barino_story_bottom" href="#">The Story</a> ...

Font and div placement varies on a mac within a WordPress environment

www.oihanevalbuenaredondo.be After styling my post titles in CSS using font-family: adobe arabic, I noticed that while they display correctly on my Windows machine, they appear in a basic font on Mac OS, Safari specifically. Why is it that Safari cannot r ...

Difficulty in displaying JavaScript function output as text

I'm currently developing a program that randomly selects and prints a function from an array list. I am facing difficulties in getting the result to print correctly. Below is the snippet of code: const hiddenElements = document.querySelectorAll( &qu ...

Learn the method for toggling images in HTML while simultaneously storing a 0 or 1 in a flag variable

In my design, I would like to have a star icon that displays two star icons at once - one blank and the other yellow. These stars will swap their appearance when clicked or tapped on touch screen devices. Additionally, I want to be able to store values as ...

jQuery modal fails to display

I am currently experiencing an issue with my jQuery dialog that is not displaying after clicking a radio button. Previously, the dialog was showing properly, but after implementing some script for submitting from the dialog, it stopped showing up when th ...

What is the best way to set up multiple routes for a single component in React

I am currently using Vue 2 in my project and have set up the following routes: const routes = [ { path: "/suites", component: Home, }, { path: "*", component: LandingPage, }, ]; Now, I need to include an additi ...

Can you explain the significance of the 'X-Bandwidth-Est 3' error message that states, "Refused to get unsafe header"?

I'm currently facing an issue with all the websites I am working on where I keep encountering the following error: Refused to get unsafe header "X-Bandwidth-Est 3" in base.js. This error seems to be related to a YouTube file named base.js, but after ...