toggle back and forth between two div elements

I am trying to create a toggle effect between two divs, where clicking on one will change its border and header color to red while the other div disappears. I have tried using an IF statement in my JavaScript code, but it is not working as expected. Can someone please assist me with this issue?

$(".container").on("click" , function(){    
  $(this).toggleClass("active");
  $(".header", this).toggleClass("active2");    
  if ($(".box1").hasClass("active")) {       
    $(".box2").removeClass("active");
    $("h2", ".box2").removeClass("active2");    
  }if ($(".box2").hasClass("active")) {       
    $(".box1").removeClass("active");
    $("h2", ".box1").removeClass("active2");    
  }        
});
body{
  padding: 3em;
}
.box1, .box2{
  padding: 2em;
  border: 1px solid silver;
  margin-top: 2em;
}    
.active{
  border-color: red;
}    
.active2{
  color: red;
}    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container box1">
  <h2 class="header">Boys</h2>
  <hr>
  <p>Benjamin</p>
  <p>David</p>
</div>    
<div class="container box2">
  <h2 class="header">Girls</h2>
  <hr>
  <p>Sara</p>
  <p>Tania</p>
</div>

Answer №1

To achieve this task, you only need a few lines of code. Simply add the class .active to the clicked element and remove the same class from its siblings.

$(".container").on("click", function() {
  $(this).toggleClass("active").siblings().removeClass("active");
});
body{padding: 3em}
.box1, .box2{
  padding: 2em;
  border: 1px solid silver;
  margin-top: 2em;
}    
.active {border-color: red}    
.active .header{color: red}    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container box1">
  <h2 class="header">Boys</h2>
  <hr>
  <p>Benjamin</p>
  <p>David</p>
</div>    
<div class="container box2">
  <h2 class="header">Girls</h2>
  <hr>
  <p>Sara</p>
  <p>Tania</p>
</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

Disable touch interactions on the body, only allow pinch-zoom on specific elements

I have been attempting to implement the following code: body { touch-action: none; } .left-side { touch-action: pinch-zoom; } <div class="left-side"><img src="image.jpg" /></div> The touch-action: none is functioning properly, but ...

Struggling to retrieve accurate information from JSON file in AngularJS

Having some issues with my initial AngularJS project. I am utilizing a yeoman generator and trying to fetch data from a JSON file to check the length of an array containing objects. This is contents of my data.json file: {"persons":[ { "fi ...

Dynamic navigation menu shifting when bolded

Looking at my menu, you'll notice the following layout: If one clicks on Recruitment in the menu, it correctly bolds the text as intended. However, an issue arises where the entire menu unexpectedly shifts 1 or 2px to the left. The menu is implemente ...

Encountering an error in Vue.js where a "cannot read property of undefined" message is displayed when attempting to use v

While attempting to use v-model on an array item's property, I encountered the error message "[Vue warn]: Error in render function: 'TypeError: Cannot read property 'viewFood' of undefined' when loading the page. This resulted in a ...

AngularJS ng-repeat: displaying a list of filtered outcomes exclusively

I currently have a ng repeat that loops through a set of results. <a class="list-group-item" href="#trip/{{trip.id}}/overview" ng-repeat="trip in trips | filter:search | limitTo:-15"> Basically, as I enter more text into my input field, the list sh ...

What is the best way to apply a texture to a triangle using three.js?

I've been able to add textures to cubes, spheres, and other primitives in a scene I created. However, when it comes to adding a texture to a simple triangle, I'm encountering difficulties. Below is my attempt at achieving this: var texture=TH ...

How can I incorporate multiple quality sources into a flowplayer using Angular?

Is there a way to add multiple sources with different qualities like 1080p, 720p etc.? Thank you in advance. flowplayer('#my_player', { src: '../assets/videos/video_1080p.mp4', // title: 'This is just demo&apo ...

SQL Sorting Investigation

I am working with a SQL table that contains a column called reference_number. The values in the reference_number column follow the format of x-MMYY-xxxx. (MM represents the month and YY stands for year. -xxxx indicates auto-increment.) My current challen ...

Customizing the appearance of columns in an antd table

Below is the table column configuration I am working with, where notes are rendered using a custom function: fieldDefs: (results, isJsonData) => [ { title: 'Notes', name: 'notesHTML', table: { render: SectionNotes, sear ...

Vue-router is displaying only the root route

I've been working on vue-router for some time now, but I seem to have hit a roadblock. Despite going through numerous articles and documentation, I can't seem to find the solution. Even after reading multiple tutorials on using vue-router, I&apo ...

How can I apply a blurred effect to the background image of a jumbotron in Bootstrap-vue without affecting the clarity of the text overlay

I need help figuring out how to blur the background image of my jumbotron without blurring the text on top. <b-container fluid class="text-center"> <div> <b-jumbotron class="jumbotron"> <p style=& ...

Can a repetitive 'setTimeout' function invocation ultimately cause the JS Engine to crash?

Imagine a scenario where I require data from the server every 10 seconds. A function would be created to fetch the data using AJAX, and then setTimeout would be used to schedule the function to run again: function RetrieveData(){ $.ajax({ url: " ...

What is the best way to adjust my column position in order to make the links clickable?

Looking for help with a mobile version website menu bar design. The issue is that the central "+" button is covering the two icons on either side, making them unclickable. Is there a solution to rearrange this layout? Here is the current design: https:// ...

The SCORM content is not establishing a connection with the Learning Management System

Despite initializing, the SCORM package is failing to communicate with the LMS and throwing an error: No SCORM implementation found. Below is my folder structure: -index.php -player.php -course/SCORM-course (directory) -wrap.js -SCORM_2004_APIWrapper.js ...

Tips for centering text in a react flexbox layout

Utilizing react-flexbox-grid in my project has led to the following layout: const SpicyMenu = (props) => ( <List> {props.foodItems.map(foodItem => <SpicyMenuItem key={foodItem.name} {...foodItem}/>)} </List> ); co ...

Lag in jQuery Animate Property

Hello fellow developers! I am currently working on a promotional website where both the homepage and subpages are contained within the same index file. The transition between the content occurs when users click on the menu items. There are a total of 4 su ...

Embed the variable directly within the JSON structure

My goal is to dynamically create a JavaScript object using object initializer notation, but with keys taken from a config object. Instead of the traditional method: var obj = { 'key' : 'some value' }; I envision something like this: ...

Margin challenge in CSS

Just starting out with CSS, so please be patient with me. I'm currently working on customizing a form and everything is looking good, except for the confirmation label which is located in a div. I've managed to create space between other elements ...

Selecting Specific File in Directory Using HTML File Input

Can you customize an HTML file input to choose a particular file from a directory or drive? By clicking on the file input button, the user opens the file selector and selects a folder or external drive. With jQuery, it is then possible to specify a specif ...

Tips for invoking a JavaScript class method from an HTML document

I've created a Typescript class that dynamically inserts an HTML element to a page after it's loaded. Here is the code snippet: const calcElement: string = ` <div class="container"> <span class="cc-title">Field</span> ...