HTML - Toggle visibility of div using display property

I'm currently working on implementing a show and hide functionality for a div. I followed a tutorial from a website called w3schools, but the way they implemented it is different from what I'm looking to achieve. In their example, the div is initially shown and then you hide it, whereas in my case, I want it hidden by default and then shown when triggered. To do this, I simply added display: none; to the #myDIV element:

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    #myDIV {
      width: 100%;
      padding: 50px 0;
      text-align: center;
      background-color: lightblue;
      margin-top: 20px;
      display: none;
    }
  </style>
</head>

<body>

  <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

  <button onclick="myFunction()">Try it</button>

  <div id="myDIV">
    This is my DIV element.
  </div>

  <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

  <script>
    function myFunction() {
      var x = document.getElementById("myDIV");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script>

</body>

</html>

However, when I first click the Try it button, the div doesn't show... Why is that happening? Subsequent clicks work as expected, showing and disappearing the div normally. How can I fix this issue? Thank you.

Answer №1

When you encounter the issue for the first time, it is because x.style.display is not defined!

To resolve this, adjust your condition to

if (x.style.display === "none" || !x.style.display)

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    #myDIV {
      width: 100%;
      padding: 50px 0;
      text-align: center;
      background-color: lightblue;
      margin-top: 20px;
      display: none;
    }
  </style>
</head>

<body>

  <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

  <button onclick="myFunction()">Try it</button>

  <div id="myDIV">
    This is my DIV element.
  </div>

  <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

  <script>
    function myFunction() {
      var x = document.getElementById("myDIV");
      if (x.style.display === "none" || !x.style.display) {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script>

</body>

</html>

Answer №2

If you remove the line display: none under #myDIV, it will automatically appear on the screen.

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

How can I address the variations in CSS appearance between Firefox and Google Chrome?

I'm currently working on a table with two cells in each row just for fun. For the first row, I want both cells to display the same picture. To achieve this, I wrote the following CSS: tr:nth-child(1){ background-image:url("cat.jpg"); background-size: ...

What is the best way to ensure grid element takes up 100% of the available height within a flex column

I am working with this HTML structure: https://i.stack.imgur.com/fy5Yz.png My goal is to have the .SceneWithHistory-Container take up 100% of the available height in its parent element. Below is my CSS code: .Module-Container margin-top: 120px; displ ...

Scrolling in iOS 8 causing flickering problem with background image

Utilizing the Supersized jQuery slider plugin to create a full-page background slider with a fade-in effect and added height for scrolling. The slider functions correctly on desktop, but upon testing on an iOS 8 iPad device, there is noticeable flickering ...

Having trouble toggling the dropdown submenu feature in a Vuejs application?

.dropdown-submenu { position: relative; } .dropdown-submenu .dropdown-menu { top: 0; left: 100%; margin-top: -1px; } <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorial ...

PHP's Encoding Woes Are Back in Action

I'm encountering encoding challenges on my website, and it's becoming quite frustrating. Allow me to elaborate My meta tag specifies utf8 as the charset. The scripts I'm using also have utf8 defined (<script type="text/javascript src=". ...

Extracting the content within an HTML element through parsing

I am looking to extract the content inside these two elements and store it in a string: source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>""" >>> text 'Martin Elias' Could someone guide ...

I just obtained the height measurement of a dynamic table - now I must transfer this height value to a different element

Recently, I encountered a situation where I needed to get the height of a dynamic table using code like this: var table = document.getElementById("test"); document.write(table.offsetHeight); However, the challenge arose when I realized that I also needed ...

Creating an image gallery with animated effects: A step-by-step guide

I am looking to develop a creative image gallery with animated effects. I also want to include panels and hyperlinks for each image, similar to the functionality on this website: http://www.microsoft.com/en-lk/default.aspx Can anyone guide me on how to ac ...

Tips for properly formatting large numbers

I am facing a challenge with handling large numbers in my JavaScript code. I came across the nFormatter function for formatting large numbers but I am unsure how to integrate it into my existing code. Below is the nFormatter function that I found: functi ...

Guide on incorporating the font-awesome library in your project

Forgive me if this sounds like a silly question, but I am completely new to javascript and its libraries. I stumbled upon a similar issue as described in this thread, where the accepted solution included the following line: <link rel="stylesheet" href ...

Steps to position images and text side by side in a grid layout

Trying to create a grid layout with profile images and text aligned next to each other, but struggling with CSS. If anyone could provide some guidance, that would be greatly appreciated! Here is the HTML code snippet: <div class="col-sm-3" ...

Troubleshooting Vue.js and Laravel: Having trouble loading new image files, while the older ones load just fine

Currently, I am working on a project that involves Vue.js and Laravel. In this setup, Vue is located inside the resources/js directory of the Laravel project. My current issue revolves around loading an image from the resources/js/assets directory. While ...

What is the best way to deactivate the second selection option?

<select id="title0"> <option value="0">--- disable</option> <option value="1"> books</option> </select> <button id="save" type="submit">Save</button> <select id="title1"> <option value="0"& ...

Enhance <th> elements using CSS classes

I'm encountering some issues with HTML tables. The layout of my table is as follows: <table class="shop_table cart" cellspacing="0"> <thead> <tr> <th class="product-remove">&nbsp;</th> <th clas ...

Guide to generating customized CSS styles on-the-fly in Vue (similar to Angular's dynamic styling capabilities)

When working with Angular, we have the capability to dynamically set CSS properties. For example: <style ng-if="color"> .theme-color { color: {{color}}; } .theme-background-color { background-color: {{color}}; } .theme-border-color { border-color: { ...

Learn how to iterate over an array and display items with a specific class when clicked using jQuery

I have an array with values that I want to display one by one on the screen when the background div is clicked. However, I also want each element to fade out when clicked and then a new element to appear. Currently, the elements are being produced but th ...

`The font appears extremely thin when viewed on Safari and iOS devices.`

I'm struggling to resolve the issue with super-thin fonts on Safari/iOS despite trying all recommended solutions. Here is the comparison: https://i.stack.imgur.com/5DVHz.png The _document.js file: import Document, { Html, Head, Main, NextScript } fr ...

Prevent anchor jumping caused by popstate event in Safari

This situation is really testing my patience. When navigating within the same page using anchors, the browser automatically takes you back/forward to the location of that link in your history when popstate is triggered. One might think that you could prev ...

Creating a tool that produces numerous dynamic identifiers following a specific format

I am working on a function to create multiple dynamic IDs with a specific pattern. How can I achieve this? followup: Vue.js: How to generate multiple dynamic IDs with a defined pattern Details: I am developing an interactive school test application. Whe ...

Connecting Peers in Windows Store App using HTML/JS

I am curious to find out if anyone has successfully created a peer-to-peer app for the Windows Store using HTML5 and JavaScript. I want client A of the app to be able to establish a connection with and send data to client B through either a TCP or UDP sock ...