Ways to display or conceal text using Vanilla JavaScript

I am struggling to toggle text visibility using Vanilla JS. Currently, I can only hide the text but cannot figure out how to show it again.

<button id="button">my button</button>
<div> 
 <p id="text">Hello</p>
</div>

This is the JavaScript code:

const z = document.getElementById('text');
const y = document.getElementById('button');

y.onclick = () => {
    z.style.display = 'none';
};

Answer №1

Opting for a class makes things simpler, as you can just toggle it on and off:

const element = document.getElementById('text');
const button = document.getElementById('button');

button.addEventListener('click', () => {
    element.classList.toggle('hidden');
});
.hidden { display: none; }
<button id="button">Click me</button>
<div> <p id="text">Hello World</p> </div>

Answer №2

Here is a simple toggle example that allows you to control the visibility of an element.

const element = document.getElementById('targetElement');
const button = document.getElementById('toggleButton');

button.onclick = function() {
  element.style.display = element.style.display === 'none' ? '' : 'none';
}
<button id="toggleButton">Toggle Element</button>
<div> 
  <p id="targetElement">Lorem ipsum</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

Can you clarify the semver meaning of the >= operator and what is the highest version it permits?

It's commonly known that when using symbols like ^, it represents anything up to the next major version, and ~ means only patches. However, there seems to be a lack of clarity regarding what the maximum version is when utilizing >=. So, how should ...

Are there any tools you rely on for speeding up the process of developing html/css?

Have you heard of zen-coding? It's a script that generates markup based on a css-esque selector like this: div#foo > p*6 This code would generate: <div id="foo"> <p></p> <p></p> <p></p> & ...

Tips for positioning an asp.net Button alongside other elements in a form by making use of Bootstrap styling

Looking to revamp the style of my ASP.NET Web Forms project with the latest version of Bootstrap. Having trouble aligning an ASP.NET Button control horizontally with other controls in the form, as seen in this snapshot: https://i.sstatic.net/IVRKo.png Her ...

Struggling to access values from your model using EL in JavaScript? Let me provide some guidance

In my model, there is an object named "domain" with two methods: getDescriptionEn() and getDescriptionFr(). I am trying to retrieve the appropriate description based on the current locale. My issue lies in the following code snippet: var locale = "${cur ...

How come my useEffect still contains outdated data?

I have encountered an issue with my useEffect in a React component. Despite having all the necessary dependencies, the state does not update after the useEffect completes. It always displays the previous render. Below is the code snippet of the hook: exp ...

I am experiencing an issue with using double quotation marks in VS Code

Whenever I press the double quote symbol like this "", the cursor automatically moves to the end. While this may be natural, I would prefer the cursor to move inside the double quotes automatically when pressing them. Additionally, it's a bi ...

The useEffect function is failing to execute when deploying on Vercel with Vite and React Router

After successfully deploying a React site using Vite on Vercel, with React Router for routing and a separate backend service, everything seemed to be working fine on my local machine. However, when testing the deployment on Vercel, I encountered an issue w ...

The functionality of my script relies on the presence of an alert function within it

My code seems to only work when I include an alert function in it. I'm trying to make my div scroll to the bottom. I've done some research, but for some reason, the script doesn't run without an alert function. $(document).ready(function ...

The presence of onChange?: (ValueType, ActionMeta) => void with OptionType is not compatible

After updating to version v2.4.2, I keep encountering an error from flow regarding react-select. It seems that I am passing the correct types to the handle change, which expects an array with objects + OptionType accepting any string [string]: any. Can som ...

Is it possible to arrange JSON Objects vertically on a webpage using tables, flexboxes, divs, and Javascript?

Within my JSON data, I have multiple products defined. My goal is to loop through this JSON and display these products side by side on a web page for easy comparison. Initially, I envision structuring them in columns and then rows: https://i.sstatic.net/K ...

Generate a JavaScript File/Blob from an image's URI

Can I generate a File or Blob object from an image URI? I am utilizing the Cordova Image Picker plugin in my mobile application to retrieve photo URIs like this: "file:///data/user/0/..../image.jpg" However, I am struggling to create a File or Blob objec ...

What is the best way to send a form value to a servlet?

As someone who is relatively new to programming, I kindly ask for your patience with me. I am currently attempting to extract values from a form (embedded in a JSP) using JavaScript, and then make a post request to a servlet. The form consists of 6 differ ...

Having trouble importing the name 'RadioChoiceInput' from the 'django.forms.widgets' module during the migration from Django 1.19 to 3.2

Currently, I am facing an issue while upgrading a Django widget.py file from version 1.19 to version 3.2. The error message I encountered is: from django.forms.widgets import RadioSelect, RadioChoiceInput ImportError: cannot import name 'RadioChoiceI ...

Understanding the binary format in JavaScript

In my JavaScript project, I am facing a challenge with reading a large table that contains a mix of numbers, enums, and strings. The data is significant in size, so I am exploring the option of converting it to binary format to save space. However, I' ...

Access a specific element within an array using Handlebars.js

After converting a CSV to JSON, I have data that looks like this: [["Year","Make","Model","Description","Price"],["1997","Ford","E350","ac, abs, moon","3000.00"],["1999","Chevy","Venture \"Extended Edition\"","","4900.00"],["1999","Chevy","Ventu ...

Issue with creating a variable name inside a JavaScript for loop

Here is the code snippet I am currently working on: var var1 = 58; for(var i=0;i<10;i++){ if(("var"+i) == 58) { console.log("they are equal"); } } I am wondering why ("var" + i) is not equal to 58 in this scenario. Could someone please provide an ...

The Python error message, "JSONDecodeError: Expecting value: line 1 column 1 (char 0)," indicates that there

What is causing this error to occur? Are there any alternative methods available for converting it into a json file? import requests import json url = 'https://finance.yahoo.com/quote/AMZN/balance-sheet?p=AMZN&.tsrc=fin-srch' r = requests. ...

What's causing the appearance of a horizontal scrollbar?

I'm puzzled by the appearance of a horizontal scroll bar on my webpage and I can't seem to pinpoint the exact cause. I've tried simplifying the page as much as possible, but there still seems to be an issue. Here's all the information I ...

Detect Flash Player Event using Javascript

Is there a way to detect when a flash video ends without depending on user input like clicking the stop button? It's important to note: I HAVE NO CONTROL OVER THE PRESENTATIONS OR SWF FILES. My goal is to automate the client player object through s ...

Retrieve information from the identical registration form in Codeigniter

https://i.stack.imgur.com/FWTIf.png The student registration form includes fields for father and mother information in the student table, while guardian information is stored in a separate guardians table. When selecting "Father" in the "Guardian Informat ...