How can I display a clicked-on div while hiding all other divs using jQuery?

I want to create a website where a button can show and hide a specific div, but my challenge is;

How can I ensure that clicking on one button hides all other divs?

Here is the JavaScript code:

function showHide(divId){
    var theDiv = document.getElementById(divId);
    if(theDiv.style.display=="none"){
        theDiv.style.display="block";
    }else{
        theDiv.style.display="none";
    }    
}

And here is the HTML code:

    <div id="div" onclick="showHide('divcontent')"> This is the button. </div>
    <div id="divcontent"> This is a div to hide and show. </div>

    <div id="div2" onclick="showHide('divcontent2')"> This is the button. </div>
    <div id="divcontent2"> This is a div to hide and show. </div>

    <div id="div3" onclick="showHide('divcontent3')"> This is the button. </div>
    <div id="divcontent3"> This is a div to hide and show. </div>

When the user clicks on div2, the intention is to hide the display of other divs.

Answer №1

To start, incorporate a method for distinguishing all of your div tags with content by assigning them a class, like this:

<div id="div" onclick="showHide('divcontent')"> This is the button. </div>
<div class="content" id="divcontent"> This is a div to hide and show. </div>


<div id="div2" onclick="showHide('divcontent2')"> This is the button. </div>
<div class="content" id="divcontent2"> This is a div to hide and show. </div>


<div id="div3" onclick="showHide('divcontent3')"> This is the button. </div>
<div class="content" id="divcontent3"> This is a div to hide and show. </div>

Next, implement the following function to toggle the visibility of content div tags:

function showHide(divId){

    $(".contents").not("#" + divId).hide();
    $("#" + divId).show();
}

It is important to ensure that you have correctly included the jQuery library somewhere in the header of your page.

Answer №2

A probable solution:

function toggleVisibility(button){   
    $(button).next('.showhide').toggle().siblings('.showhide').hide();
}

LIVE DEMO

Here is an example of the corresponding HTML:

<div onclick="toggleVisibility(this)">Click here</div>
<div class="showhide">This is the content to hide and show.</div>
<!-- More code here -->

Answer №3

Typically, this is accomplished using CSS classes.

<div id="div" class="toclick"> This is the button. </div>
<div id="divcontent" class="tohide"> This is a div to hide and show. </div>

<div id="div2" class="toclick"> This is the button. </div>
<div id="divcontent2" class="tohide"> This is a div to hide and show. </div>

<div id="div3" class="toclick"> This is the button. </div>
<div id="divcontent3" class="tohide"> This is a div to hide and show. </div>

Using jQuery, you can easily target the object you clicked on:

$('.toclick').click(function(){
   var doNotDisappear =  $(this).attr('id'); //get id of div
   $('#'+doNotDisappear).next('.tohide').removeClass('tohide');
   $('.tohide').hide(); //make the other disappear
});

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

Styling components using classes in Material-UI

I recently started using material-ui and noticed that it applies inline styles to each component. After running a test with multiple instances of the same component, I realized that there was no CSS-based styling - only repeated inline styles were generate ...

Using JavaScript to parse JSON and set the value of a DatePicker

I have a text input field in my .cshtml page which is a Date type field. <div class="form-group"> <label for="comments">ETA:</label> <input class="form-control text-box single-line" data-val="true" id="MilestoneETAEdit" name ...

Creating column gaps that remain consistent when resizing a webpage is essential for maintaining a clean and organized layout

Visit my current site [This is the HTML code for my website:][2] <div class="column-box" style="width: 100%"></div> <div id="column1" style="float:left; margin:15; width:33%;"> <p>Sara Adams<br> I am a Web Developer and C ...

Integration of Django Tastypie with Angular for secure user authentication

I'm currently facing an issue where I cannot establish a connection to the Django server. Upon checking the browser console, I noticed the following error message: [![console error][1]][1] My setup involves using Tastypie along with a UserResource c ...

Combining Rails 3.1 authenticity tokens with the uploadify feature

Currently, I am facing an issue while trying to integrate Uploadify with my Rails 3.1 application. Despite setting up all the necessary steps such as middleware, initializers, and configuration, everything seems to be working correctly except for one parti ...

Find a solution to splitting the area in half, with one side designated for the icon and the other for text

https://i.sstatic.net/Ov3yF.png I'm currently working on a code to assign tasks to employees, and I have created a login form with multiple text fields, each accompanied by an icon. However, there seems to be a layout issue as shown in the image. The ...

What is the best way to send a Rails AJAX form upon clicking?

I'm looking to implement AJAX form submission in Rails using a button. Here's my current code: Controller: def list @events = ExternalEvent.all if !params[:city_id].nil? @events = @events.where(city_id: params[:city_id]) end respond ...

Retrieve the content of the second <li> element using jQuery

Seeking assistance with replacing the separator symbol in a given structure. In order to proceed, I first need to identify its position. Can anyone offer guidance on how to do this? Below is the structure in question: <div> <ul> ...

Strategies for extracting methods and refactoring to a separate file for better reusability

Still relatively new to the JQuery/javascript realm, I've put together a functional jqgrid with a datepicker and custom control (using jquery auto complete) by piecing together code samples I came across online. This code has been added to a T4 templa ...

Incorrect footer navigation on my Vuepress website

I'm in the process of developing a vuepress single page application for showcasing and providing downloads of my personal game projects. When it comes to website navigation, I am aiming to utilize the native sidebar exclusively. This sidebar will hav ...

The face textures are not being applied correctly to the model imported in THREE.js

I'm having trouble importing a model exported from blender using the THREEJS exporter. The model loads correctly in my scene with the materials applied, such as the car appearing yellow and the glass being transparent as intended. However, I am facin ...

Creating a customized function in javascript/jquery with the ability to override it

Currently, I am utilizing Visual Studio for writing JavaScript/jQuery. For instance, when I input: $('#selector').text('foo') and then highlight text and hit F12, Visual Studio directs me to the file jquery-2.2.3.intellisense.js, auto ...

Changing the content of a PHP div with an Ajax callback inside another Ajax callback?

In the index.php file, there is a script that triggers an ajax call when a header element is clicked. This call sends a $selection variable to ajax.php, which then replaces #div1 with the received HTML data. <script> $(document).ready(function(){ ...

Utilize jQuery to dynamically apply Bootstrap classes while scrolling through a webpage

Having an issue with jQuery. Trying to include the fixed-top class (Bootstrap 4) when scrolling, but it's not working as expected. jQuery(document).ready(function($){ var scroll = $(window).scrollTop(); if (scroll >= 500) { $(".robig").a ...

How to effectively pass data between parent and child controllers in Angular 1 - Seeking guidance

Currently, I am working on two separate applications that have a common requirement of displaying active incidents and closed incidents. Both apps involve similar logic for creating, modifying, saving, and deleting incidents. I am exploring the best appro ...

Attempting to align the dropdown menu to the left side

This is a challenge I'm facing: https://i.sstatic.net/d3PtN.png I'm attempting to align it in the following way: https://i.sstatic.net/GCwEO.png Below is the HTML code snippet: <li class='list-group-item'> <!-- The dropdow ...

How do RxJS collection keys compare?

Is there a more efficient way to compare two arrays in RxJS? Let's say we have two separate arrays of objects. For example: A1: [{ name: 'Sue', age: 25 }, { name: 'Joe', age: 30 }, { name: 'Frank', age: 25 }, { name: & ...

React Jodit Editor experiencing focus loss with onchange event and useMemo functionality not functioning properly

I'm currently working on a component that includes a form with various inputs and a text editor, specifically Jodit. One issue I've encountered is that when there are changes in the Jodit editor's content, I need to retrieve the new HTML va ...

Stop duplicate form submissions in Ajax by implementing form tokens in PHP

****Update**** After creating a new document with the exact same code, it became evident that there was nothing wrong with my code. This led me to believe that the original file may have somehow become corrupt. For more information, please refer to my ans ...

Choosing and aiming with jQuery on dynamically created Ajax pages

I am facing an issue with a Select box on a page that is generated through AJAX. Here is the code snippet: <select onchange="setLocation(this.value)"> <option value="https://xy.com/accessories.html?dir=asc&amp;limit=15&amp;order=name"& ...