Vanilla JavaScript // Conceal a div when the class of another div is modified

Note: I am unable to utilize jQuery, only vanilla JavaScript

I am not very proficient in pure JS. Additionally, this time around, I cannot rely on any external resources such as jQuery.


What I am looking for:

If the div1 class is active, I want to hide text2

If the div2 class is active, I want to hide text1

I managed to get it working somehow, but my JavaScript does not respond when the class changes dynamically due to another piece of JavaScript code.

Code that activates the active class:

function activateClass(element) {
  var allElements = document.getElementsByClassName('item');
  for (var i = 0; i < allElements.length; i++) {
    allElements[i].classList.remove('active');
  }
  element.classList.add('active');
}

Code that should trigger the hiding/showing when the class changes:

if (document.querySelector(".text2").classList.contains("active")) {
  document.getElementsByClassName('text1s')[0].style.visibility = 'hidden';
  document.getElementsByClassName('text2s')[0].style.visibility = 'visible';
}

if (document.querySelector(".text1").classList.contains("active")) {
  document.getElementsByClassName('text2s')[0].style.visibility = 'hidden';
  document.getElementsByClassName('text1s')[0].style.visibility = 'visible';
}

Where did I make a mistake?


Check out the Codepen demo

Answer №1

  • Ensure to place your conditions inside the click handler function.
  • Remember to include inline visibility style for the inactive element.

function toggleActiveClass(element) {
  var items = document.getElementsByClassName('item');
  for (var i = 0; i < items.length; i++) {
    items[i].classList.remove('active');
  }
  element.classList.add('active');
  
  if (document.querySelector(".text2").classList.contains("active")) {
    document.getElementsByClassName('text1s')[0].style.visibility = 'hidden';
    document.getElementsByClassName('text2s')[0].style.visibility = 'visible';
  }
  if (document.querySelector(".text1").classList.contains("active")) {
    document.getElementsByClassName('text2s')[0].style.visibility = 'hidden';
    document.getElementsByClassName('text1s')[0].style.visibility = 'visible';
  }
}
body {
  margin: 3em;
}
.item {
  cursor: pointer;
}
a {
  padding: 10px;
}
.active {
  color: red;
  border: 1px solid red;
}
<a class="item text1" onclick="toggleActiveClass(this)">show text</a>
<a class="item text2 active" onclick="toggleActiveClass(this)">hide text</a>
<br>
<br>
<h1 class="text1s" style='visibility:hidden;'>TEXT 1</h1>
<h1 class="text2s">TEXT 2</h1>

Check out the Updated Codepen Here!

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

Executing various tasks concurrently with web workers in Node.js

Looking to read multiple JSON files simultaneously and consolidate the data into a single array for processing on a Node.js server. Interested in running these file readings and processing tasks concurrently using web workers. Despite finding informative ...

What is the process for placing a breakpoint within a "require"-d library using node inspector?

As I navigate through a library that is multiple layers deep from my project, I am facing the challenge of setting a breakpoint inside it. Node-inspector is a new tool for me, and I am currently exploring how to access the library and set breakpoints in i ...

arrange elements by their relationship with parents and children using typescript and angular

Here is a list that needs to be sorted by parent and child relationships: 0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4} 1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null} 2: {id: 5, name: ...

Having trouble retrieving data from getStaticProps

I'm currently developing a project using next.js and I am attempting to fetch a list of gyms in the getStaticProps function. Here is my code snippet: import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet"; import { useState } ...

Is it necessary to delay until the entire page finishes loading in Selenium 3?

public boolean CheckPageLoadStatus(){ final ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(final WebDriver driver) { return ((JavascriptExecutor) driver).executeScr ...

Using jQuery to clear a textarea when a select input is changed

Currently, I am in the process of developing a small text editor that enables users to edit files and create new ones. Here is how I have set up my select menu. <select name="reportname" id="reportname" class="form-control"> <option value="zr ...

The Mapbox map fails to display properly upon initial page load

When my Mapbox map loads, I am experiencing issues with it only rendering partially. It seems that adjusting the width of the browser or inspecting the page will cause the map to snap into place and display correctly. To demonstrate this problem, I created ...

Arranging Functions in JavaScript

I am encountering an issue regarding the execution of JavaScript functions within HTML. Specifically, I am using dimple.js to create a graph and need to select an svg element once the graph is created via JavaScript. Despite placing my jQuery selector as t ...

How can I implement the ternary operator in React Native and resolve my code issue?

Hello, I'm looking to implement the ternary operator in my code. Specifically, I want to render a FlatList if `cookup` has a value. However, if `cookup` is an empty array, I want to display some text instead. <FlatList data={cookUp} ...

The tabbed menu should remain selected until the user switches to another menu option

Each time a user clicks on a tabbed menu, the selected menu should be highlighted in the background color until another tab is clicked. Each tab corresponds to a different page of content. In order to achieve this, the selected tab needs to have the attri ...

Challenges Encountered When Working with Date Fields in Kendo JS Grid

We are facing an unusual issue with the Kendo UI Grid on our production site. Some users are experiencing date fields showing as null in Google Chrome, while they appear correctly in private browsing mode and other browsers like IE and MSEdge. We have bee ...

I need a layout similar to the navbar on http://thecoloradan.com/ but I am not asking for instructions on how to do it

Have you seen the stunning navbar on this website? It appears to merge with the background upon loading, then smoothly shifts to the top of the page as you scroll. The transition is accompanied by a lovely animation. I am curious about the steps needed to ...

Is there a way to position one DIV behind another?

Hey, I'm working on my first project and running into some trouble with divs. I'm trying to position the firework behind the central text but can't figure it out. Can anyone lend a hand? I need to add more details in order to submit the que ...

I am having trouble with my Vue nested For loop as it is only returning the first value of the second array. What could be

I am currently utilizing a nested For loop to retrieve data from JSON and then returning a variable for Vue frontend access. Oddly enough, I am only able to retrieve values from the initial element of the nested array. Can anyone assist with this issue? It ...

Ways to determine if a browser is currently loading a fresh webpage

I'm experiencing an issue with my web app where the 'safety' code triggers a page reload if the server (Socket.IO) connection becomes silent for more than 5 seconds, often due to customer site firewall or broken-proxy issues. Although the S ...

Creating interactive JSON objects through the use of JavaScript and AngularJS

When using AngularJS to build a dynamic JSON from server data, I encountered an issue where my current declaration only works if the server data contains one item in the object array. How can I modify this to handle multiple items dynamically? $scope.it ...

Stop the reloading of the parent page when the exit button is pressed on the popup screen

I have set up a modal popup that appears when a user clicks on a specific link. Inside the popup, I have included an exit button to close it. However, I am facing an issue where clicking on the exit button not only closes the popup but also reloads the par ...

What is the best method to transfer information from a What You See Is What You Get editor to a database using Vue.js?

I have recently started using the Vue2Editor in order to streamline my process of sending text and image data to my Firebase database. However, I am encountering an issue where the entered data is not being added successfully. Previously, with traditional ...

What could be causing my React child component to not update when changes are made to an array passed down in props after fetching new data?

My Profile.js component is responsible for fetching activity data related to a specific user from the URL parameter and updating the profileActivity state. This state is then passed down to my child component, ProfileActivity.js, where it should be display ...

Tables inserted via ckeditor do not preserve the style attribute

After incorporating ckeditor into my web page along with the table plugin, I noticed that sometimes the width of tables created in the editor window extends beyond the boundaries of the webpage when displayed. To address this issue, I made some adjustments ...