Exploring the techniques for displaying and concealing div elements with pure JavaScript

Here's an example of code I wrote to show and hide div elements using pure JavaScript.

I noticed that it takes three clicks to initially hide the div elements. After that, it works smoothly. I was attempting to figure out how to display the elements with just one click.

var count = 0;

function showMee() {
  var buttonHome = document.querySelector("#showMe");

  count += 1;
  buttonHome.addEventListener("click", function() {
    if (count == 1) {
      document.querySelector('#linkMeOne').style.display = 'none';
      document.querySelector('#linkMeTwo').style.display = 'none';
    } else if (count == 2) {
      document.querySelector('#linkMeOne').style.display = 'block';
      document.querySelector('#linkMeTwo').style.display = 'block';
      count = 0;
    }
  });
}
#linkMeOne {
  display: block;
}

#linkMeTwo {
  display: block;
}
<div id="linkMeOne">
  Hiding me As first time....
</div>

<div id="linkMeTwo">
  Hiding me as well as...
</div>

<input type="button" value="Check Me" id="showMe" onclick="showMee()" />

Answer №1

Simply hide and reveal.

If you prefer them to be hidden initially, include the hidden attribute in the divs

const element1 = document.getElementById("toggleFirst");
const element2 = document.getElementById("toggleSecond");
document.querySelector("#reveal").addEventListener("click",function() {
   element1.hidden = !element1.hidden;
   element2.hidden = !element2.hidden;
})
<div id="toggleFirst">
  Concealing me at first....
</div>

<div id="toggleSecond">
  Keeping me hidden too...
</div>

<input type="button" value="Show/Hide" id="reveal" />

Answer №2

To get the code working, simply delete the event listener for addEventlistener.

var count = 0;

function showMee() {
  var buttonHome = document.querySelector("#showMe");

  count += 1;
  //buttonHome.addEventListener("click", function() {
    if (count == 1) {
      document.querySelector('#linkMeOne').style.display = 'none';
      document.querySelector('#linkMeTwo').style.display = 'none';
    } else if (count == 2) {
      document.querySelector('#linkMeOne').style.display = 'block';
      document.querySelector('#linkMeTwo').style.display = 'block';
      count = 0;
    }
  //});
}
#linkMeOne {
  display: block;
}

#linkMeTwo {
  display: block;
}
<div id="linkMeOne">
  Hiding me As first time....
</div>

<div id="linkMeTwo">
  Hiding me as well as...
</div>

<input type="button" value="Check Me" id="showMe" onclick="showMee()" />

Instead of using a variable, opt for a class to adjust the display property to none.

function showMee() {
  document.querySelector('#linkMeOne').classList.toggle('hidden');
  document.querySelector('#linkMeTwo').classList.toggle('hidden')
}
#linkMeOne {
  display: block;
}

#linkMeTwo {
  display: block;
}

.hidden {
  display: none !important;
}
<div id="linkMeOne">
  Hiding me As first time....
</div>

<div id="linkMeTwo">
  Hiding me as well as...
</div>

<input type="button" value="Check Me" id="showMe" onclick="showMee()" />

Answer №3

Although there are numerous possible solutions, all of them seem to lack simplicity. The most straightforward solution is to attach an eventListener to the button and toggle a class for all elements with a specific class name. This way, you won't need to individually specify each element:

document.querySelector('#showMe').addEventListener('click', function() {
  document.querySelectorAll('.linkMe').forEach(el =>
    el.classList.toggle('d-block')
  );
})
.linkMe {
  display: none;
}

.d-block {
  display: block;
}
<div class="linkMe">
  Hiding me As first time....
</div>

<div class="linkMe">
  Hiding me as well as...
</div>

<input type="button" value="Check Me" id="showMe" />

Answer №4

One way to achieve toggling is by using a data attribute along with CSS. Here's an elaborate explanation of how you can do that:

document.querySelector("#showMe")
  .addEventListener("click", (event) => {
    const t = event.target;
    const showem = t.dataset.show;
    document.querySelectorAll('.can-toggle').forEach((element) => {
      element.dataset.show = showem;
    });
    t.dataset.show = showem == "show" ? "hide" : "show";
  });
.can-toggle[data-show="hide"] {
  display: none;
}
<div class="can-toggle">
  Hiding me As first time....
</div>

<div class="can-toggle">
  Hiding me as well as...
</div>

<input type="button" value="Check Me" id="showMe" data-show="hide" />

Alternatively, you can handle each toggle independently with an initial state:

document.querySelector("#showMe")
  .addEventListener("click", (event) => {
    document.querySelectorAll('.can-toggle').forEach((element) => {
      element.dataset.show = element.dataset.show == "hide" ? "show" : "hide";
    });
  });
.can-toggle[data-show="hide"] {
  display: none;
}
<div class="can-toggle" data-show="hide">
  Hiding me As first time....
</div>
<div class="can-toggle">
  Hiding me as well as...
</div>
<div class="can-toggle" data-show="Ishow">
  What am I?
</div>

<input type="button" value="Check Me" id="showMe" data-show="hide" />

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

What is the reason behind Next.js inability to import files within a directory?

Error: Module not found - Unable to locate 'components/layout' in nextjs-blog/pages/posts > 1 | import Layout from 'components/layout' 2 | import Link from 'next/link' 3 | import Head from 'next/head' I' ...

Placing the jQuery/javascript source pages right before the closing body tag

Multiple plugin instructions recommend placing the javascript/jQuery source right before the closing body tag. I wondered why this advice is given, but couldn't find a clear explanation for it. In my experience, placing the src file anywhere in the s ...

Having trouble accessing the scrollHeight property of null when using Selenium WebDriver

I am currently working on a function in my code that is responsible for scrolling the page. This particular function was inspired by code used to scrape Google Jobs, which can be found here. However, I encountered an error that reads "javascript error: Ca ...

Guide on increasing a basic counter and a counter with an object component using redux

(I need help fixing my code) I am trying to write a counter increment code to better understand Redux in the following situations: Increasing a simple counter Increasing a counter with an object Currently facing an issue where counter1 is undefined on the ...

Authenticating the Gmail API using a specified user ID

Is there a way to manually input email and password for authentication in the Gmail API without using the default Google popup? I need users to enter their login credentials directly, but I can't figure out how to do it. The code I am currently using ...

What is the best way to connect individual buttons to a dynamic div that displays different content depending on the button clicked?

Hey there! I'm diving into the world of JavaScript and HTML, and I need some guidance on creating a menu that can toggle visibility of specific content in div(s) depending on which button (picture1-12) is clicked. My idea is to have one div that can d ...

What impact does reselect have on the visual presentation of components?

I'm struggling to grasp how reselect can decrease a component's rendering. Let me illustrate an example without reselect: const getListOfSomething = (state) => ( state.first.list[state.second.activeRecord] ); const mapStateToProps = (state ...

Triggering a jQuery event upon clicking a link

Trying to achieve a specific functionality here. Clicking on an image triggers a lightbox, but right-clicking and opening in a new tab should lead to a different page. Instagram has a similar feature that I'm aiming for. Using <a href=""> doesn& ...

Revamping the vertices and UVs of DecalGeometry

I am currently experimenting with ThreeJS decals. I have successfully added a stunning decal to my sphere. Below is the code snippet I am using to place the decal on my sphere. (Please disregard any custom classes mentioned in the code.) // Creating the ...

Utilize dropdown1 to dynamically populate dropdown 2 in AngularJS

Here is the HTML code snippet I am currently working with: <select ng-controller="category" ng-model="selectedTestAccount" ng-options="c.category for c in categories track by c.categoryID" ></select> <select ng-controller="subcategory" ng ...

AngularJS factory architecture for multiple functions

It's not the exact data I'm using in my project, but I'm simplifying it for demonstration purposes. In my AngularJS app, I have a factory like this: myApp.factory('inputinfo', function () { var self = { test: function (in) { ...

The form is functioning properly on mobile devices but is currently experiencing issues on the server

Everything runs smoothly when accessing the website and using the form on localhost. However, once it's uploaded to a server, the form only functions correctly on desktop devices. On mobile, the form fails to filter and displays all professionals inst ...

Retrieving data from a backend express server using Client-side Javascript

I have created an Express Server set up in the following way: var mysql = require('mysql2'); var express = require('express'); var app = express(); var PORT = 3000; app.get('/getDataFromDatabase', function(req, res) { cons ...

Could you explain the distinction between push and offset within the grid system?

I'm currently diving into the world of Bootstrap grids and trying to wrap my head around the concepts of push and offset. In the showcase below, I have two rows that only differ in how the third column is positioned - one using a push and the other an ...

Is the jquery autocomeplete plugin malfunctioning when using numbers in the input?

I encountered a requirement to display stock number suggestions within a search box. To achieve this, I decided to implement the Jquery autocomplete plugin. Through an ajax call to a function in my cfc, I was able to retrieve all the stock numbers and stor ...

Struggling to dynamically update array values by comparing two arrays

I am faced with a scenario where I have two arrays within an Angular framework. One of the arrays is a regular array named A, containing values such as ['Stock_Number', 'Model', 'Type', 'Bill_Number'] The other arr ...

Unexpected syntax error occurs while retrieving data from web API using jQuery AJAX request

I'm attempting to retrieve a json object from the following URL: You may not understand much as it's in Greek, but the format is json. Below is the code snippet I'm using: function getDicts() { api_url = 'https://test3.diavgeia.gov ...

Using React and Ant Design: Sharing state between multiple <Select> components within a <Form> element

Just getting started with ReactJS and AntDesign. Currently, I am working on connecting a series of <Select> components to share state. The goal is for the selection made in the first dropdown to dynamically update the options available in the follow ...

The audio directory is not included in the build of the Ionic framework, causing it to be skipped and absent

Recently, I've been working on an Ionic/Cordova app and came across a folder labeled /audio which consists of mp3 files: /www /assets /audio file.mp3 /css /js config.xml index.html The issue at hand is that the /audio directory is n ...

Canvas only draws outside the table, with the exception of the first one

I am facing an issue with placing multiple signature pads inside table cells. Only the first canvas gets drawn, while the others remain blank. I have checked the mouse/touch events. The events are triggered (up/down/move) and the draw function is called, ...