Home > Web Front-end > JS Tutorial > Why Isn't My JavaScript Hiding My Second Div?

Why Isn't My JavaScript Hiding My Second Div?

Mary-Kate Olsen
Release: 2024-12-13 17:58:17
Original
587 people have browsed it

Why Isn't My JavaScript Hiding My Second Div?

Toggle Visibility of Two Divs with JavaScript

Issue

For a website, you want to toggle the visibility of two divs using JavaScript. The first function works fine, but the second function meant to hide the second div is not working.

Solution

Hide an Element:

To hide an element, set its display or visibility property. For complete hiding, use display: none. To hide only visually, use visibility: hidden.

Hide a Collection of Elements:

If you need to hide multiple elements, iterate over them and set the display property to none for each.

Revised Code:

Modify your code as follows:

function toggleDiv(target, replacement) {
  document.getElementById(target).style.display = 'none';
  document.getElementById(replacement).style.display = 'inline';
}
Copy after login

Usage:

Create two buttons to toggle between the divs:

<button onClick="toggleDiv('target', 'replace_target')">View Portfolio</button>
<button onClick="toggleDiv('replace_target', 'target')">View Results</button>
Copy after login

This code will now correctly toggle the visibility of the divs.

The above is the detailed content of Why Isn't My JavaScript Hiding My Second Div?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template