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

Establishing the value of "document.cookie"

Encountering issues while trying to set a cookie using different methods: Method 1: document.cookie = name + "=" + value + "; expires=" + date.toUTCString() + "; path=/"; This method only sets the value up to "name=value" wh ...

React-app size has grown larger post-deployment

I recently created my second app clone using React. I have noticed that after deployment, the size of the app increases. Everything looks normal on localhost:3000, but it significantly grows once deployed. Any assistance in resolving this issue would be gr ...

Charting data from MongoDB with Highcharts column chart

Having trouble creating a column chart with Highcharts in Node.js, fetching data from MongoDB. Specifically stuck on the series option - any help is appreciated. Here's an excerpt of my code in the EJS file: <html> <head> <meta ht ...

Contenteditable feature dynamically styling text upon input

Is it possible to prevent CSS properties like text-transform from affecting text entered via contenteditable? On my webpage, "CERTIFICATE PROGRAM" is shown in uppercase due to text-transform settings. However, the original input was: Certificate Program. ...

Issues with PHP not properly accepting JSON data sent via Ajaxor

I've been attempting to send JSON data to a PHP file using Ajax. Here is the JavaScript code I've written: function updateJSON(){ var xmlhttpa; if (window.XMLHttpRequest){ xmlhttpa = new XMLHttpRequest(); } else { xml ...

The input field malfunctioned after the clear button was pressed

Hi there, I have a question. Every time I try to click on the clear button, it keeps giving me an error message and I'm not sure what the issue is. Also, I can't type in the field anymore after clicking it. methods: { add () { this.ta ...

Having difficulty including the Column Name in the Jqgrid footer for sum calculation

I was working on the Jqgrid code and found a way to display the sum correctly in the footer of the grid. var colSum = $("#dataGrid").jqGrid('getCol', 'Amount', false, 'sum'); $("#dataGrid").jqGrid('footerData', &a ...

A guide on how to perform a PUT or DELETE operation for Azure Table Storage using Node.js

I've been faced with a challenge in my project where I aim to create basic CRUD functionality for Azure Table Storage. However, I'm encountering difficulties in generating a valid SharedKeyLite signature. While I can successfully generate valid ...

What steps can I take to refactor a portion of the component using React hooks?

I am trying to rewrite the life cycle methods in hooks but I am facing some issues. It seems like the component is not behaving as expected. How can I correct this? Can you provide guidance on how to properly rewrite it? useEffect(() => { updateUs ...

IE compatibility mode causing ckeditor dropdown to be hidden

When using the CKEditor editor bar inside a green div with another div below it, I noticed that when clicking on "font" or any other option that opens a dropdown menu, it gets hidden behind the bottom div. This issue seems to occur in browsers like Chrome ...

purging data from javascript objects

In my Node.js HTTP server, I am using 'connect' to build a web service that currently parses JSON requests into an Object, performs operations, and returns a synchronous response. The JSON data comes from an ecommerce cart and results in an Objec ...

Unraveling JSON data within an AngularJS controller

I'm facing an issue with exposing a field in my AngularJS controller. The problem arises when a JSON 'owner' object is returned by a webservice, containing a field named 'Cave'. If this 'Cave' field has a null, empty, or ...

How can I adjust the vertical position of Material-UI Popper element using the popper.js library?

https://i.stack.imgur.com/ZUYa4.png Utilizing a material-ui (v 4.9.5) Popper for a pop-out menu similar to the one shown above has been my recent project. The anchorElement is set as the chosen ListItem on the left side. My goal is to have the Popper alig ...

Tips on running jQuery scripts when a div changes its display style from none to block?

Is there a way to trigger jQuery code when the style of a div transitions from `display: none;` to `display: block;`? I am working with tabs, which is why this div's style changes in this manner. The jQuery code should only be executed when this spec ...

What is the best way to determine the remaining time until a cookie expires in seconds?

I recently set a cookie with an expiration time of 2 minutes. Now, I am looking for a way to display a countdown in HTML showing the seconds remaining before that specific cookie expires using Angular 2. ...

Changing the direction to reverse column will cause the navigation component to be hidden

Issue: The <Navigation/> components disappear when using flex-direction: column-reverse. However, if I switch to flex-direction: column, the component appears at the top of the screen and is visible. My objective is to display my <Navigation/> ...

Struggling to adjust the timeout to exceed 60 seconds

I have been attempting to set a timeout for 120 seconds or more, but no matter what I try, the requests are timing out after only 60 seconds. Things I have tried include: $.ajax({ url: URL, timeout: 120000, success: function(html){ co ...

When using `setState()`, ensure that you are updating a component that is already mounted or in the process of mounting. If you receive this error, it

When using WebSocket to communicate with my server, I call the handleSubmit() function to send data and update my state based on the received response. Everything works fine initially. Upon calling componentWillUnmount, I stop sending data to the websocke ...

Looking to add a dropdown feature to my current main navigation bar

I've been struggling to add a drop-down menu to my website's main menu. Every time I try, something goes wrong - sometimes the menu appears inline, other times it completely messes up the layout. Here is the HTML code snippet: <ul class="m ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...