Pressing the button twice is necessary for troubleshooting when initially opened

After creating a code snippet that hides or shows part of the text when a button is clicked, I noticed that upon launching the page, it requires two clicks on the button to function properly. This issue occurs only during the initial launch, as after the first two clicks, subsequent clicks work as expected with just one click. Can anyone shed light on why this might be happening?

Below is the code snippet:

#myDIV {
    width: 200px;
    background-color:#333;
color:#fff;
display:none;
padding:0;
margin:0;
}

#myDIV2 {
    width: 200px;
    background-color:#333;
color:#fff;
display:none;
}

#arrow{
height:10px;
width:10px;
}

#ok{
height:20px;
width:20px;
}

#button{
background-color:#333;
color:#fff;
width:250px;
empty-cells:hide;
}

table,tr,td{
border:2px solid black;
border-collapse:collapse;
}
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Slides Checkbox</title>
<link rel="stylesheet" href="style.css">
<script src="js/jquery.js"></script>
<script src="js/jquery-3.2.1.js"></script>

<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} 
else {
x.style.display = "none";
}
};
function myFunction2() {
var x = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} 
else {
x.style.display = "none";
}
};
</script>
</head>
<body>
<table id="button">
<tr>
<td><button onclick="myFunction()"><img src="img/arrow.png" id="arrow"></button>
Première liste:</td>
</tr>
<tr>
<td><div id="myDIV">
<ul>
<li>1er item</li>
<li>2eme item</li>
<li>3eme item</li>
</ul>
</div></td>
</tr>
<tr>
<td><button onclick="myFunction2()"><img src="img/arrow.png" id="arrow"></button>
Deuxième liste:</td>
</tr>
<tr>
<td><div id="myDIV2">
<ul>
<li>1er item</li>
<li>2eme item</li>
<li>3eme item</li>
</ul>
</div></td>
</tr>
</table>
<img src="img/ok.png" id="ok">
</body>
</html>

Answer №1

I reorganized the if statement to resolve the issue

function updateDisplay(element) {       
   var target = document.getElementById(element);
   if (target.style.display === "block") {
           target.style.display = "none";
   } else {
           target.style.display = "block";
   }
}

function toggleVisibility() {
    var target = document.getElementById("myDIV2");
    if (target.style.display === "block") {
    target.style.display = "none";
    } else {
    target.style.display = "block";
    }
}
#myDIV {
    width: 200px;
    background-color:#333;
    color:#fff;
    padding:0;
    margin:0;
    display: none;
}
#myDIV2 {
    width: 200px;
    background-color:#333;
    color:#fff;
    display: none;
}
#arrow{
    height:10px;
    width:10px;
}
#ok{
    height:20px;
    width:20px;
}
#button{
background-color:#333;
color:#fff;
width:250px;
empty-cells:hide;
}
table,tr,td{
border:2px solid black;
border-collapse:collapse;
}
<table id="button">
<tr>
<td><button onclick="updateDisplay('myDIV')"><img src="img/arrow.png" id="arrow"></button>First list:</td>
</tr>
<tr>
   <td>
      <div id="myDIV">
      <ul>
      <li>1st item</li>
      <li>2nd item</li>
      <li>3rd item</li>
      </ul>
      </div>
   </td>
</tr>
<tr>
<td><button onclick="toggleVisibility()"><img src="img/arrow.png" id="arrow"></button>Second list:</td>
</tr>
<tr>
<td>
   <div id="myDIV2">
   <ul>
      <li>1st item</li>
      <li>2nd item</li>
      <li>3rd item</li>
   </ul>
   </div>
</td>
</tr>
</table>

Answer №2

It appears that on the initial click, the if condition within the style for myDiv fails to execute. By manually adding a style attribute to the tag, the functionality now works flawlessly.

Upon clicking the first button, both consoles output as anticipated. However, when clicking the second button, the if condition fails to run.

Please note: I purposely added the style attribute to only one of the divs to illustrate the distinction between them.


<!DOCTYPE html>
<html lang="fr">
    <head>
        <meta charset="utf-8">
        <title>Slides Checkbox</title>
        <link rel="stylesheet" href="sample.css">
        <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>

        <script>    
            function myFunction() {
                var x = document.getElementById("myDIV");
                console.log("1", x.style.display);
                if (x.style.display === "none") {
                    console.log("2");
                    x.style.display = "block";
                } 
                else {
                    x.style.display = "none";
                }
            };
            function myFunction2() {
                var x = document.getElementById("myDIV2");
                console.log("3", x.style.display);
                if (x.style.display === "none") {
                    console.log("4");
                    x.style.display = "block";
                } 
                else {
                    x.style.display = "none";
                }
            };
        </script>
    </head>
    <body>
        <table id="button">
            <tr>
                <td><button onclick="myFunction()"><img src="img/arrow.png" id="arrow"></button>
                First List:</td>
            </tr>
            <tr>
                <td><div id="myDIV" style="display: none;">
                    <ul>
                        <li>1st item</li>
                        <li>2nd item</li>
                        <li>3rd item</li>
                    </ul>
                </div></td>
            </tr>
            <tr>
                <td><button onclick="myFunction2()"><img src="img/arrow.png" id="arrow"></button>
                Second List:</td>
            </tr>
            <tr>
                <td><div id="myDIV2">
                    <ul>
                        <li>1st item</li>
                        <li>2nd item</li>
                        <li>3rd item</li>
                    </ul>
                </div></td>
            </tr>
        </table>
        <img src="img/ok.png" id="ok">
    </body>
</html>

Answer №3

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="utf-8>
    <title>Checkbox Slides</title>
</head>
<body>
    <table id="button">
        <tr>
            <td><button onclick="myFunction()"><img src="img/arrow.png" id="arrow"></button>
            First list:</td>
        </tr>
        <tr>
            <td><div id="myDIV">
                <ul>
                    <li>1st item</li>
                    <li>2nd item</li>
                    <li>3rd item</li>
                </ul>
            </div></td>
        </tr>
        <tr>
            <td><button onclick="myFunction2()"><img src="img/arrow.png" id="arrow"></button>
            Second list:</td>
        </tr>
        <tr>
            <td><div id="myDIV2">
                <ul>
                    <li>1st item</li>
                    <li>2nd item</li>
                    <li>3rd item</li>
                </ul>
            </div></td>
        </tr>
    </table>
    <img src="img/ok.png" id="ok">
    
        <script>    
        function myFunction() {
            var x = document.getElementById("myDIV");
            if (x.style.display === "none") {
                x.style.display = "block";
            } 
            else {
                x.style.display = "none";
            }
        }
        function myFunction2() {
            var x = document.getElementById("myDIV2");
            if (x.style.display === "none") {
                x.style.display = "block";
            } 
            else {
                x.style.display = "none";
            }
        };
    </script>
</body>

It appears that your code is functioning as intended. I have made some adjustments, such as relocating your script to the end of the body and removing jQuery links. It's possible that your CSS file may be affecting the initial styling of the page, with your JavaScript taking over upon user interaction.

Answer №4

The HTMLElement.style attribute is utilized for both retrieving and modifying the inline style of an element.

When executing this code block:

var x = document.getElementById("myDIV");
if (x.style.display === "none") {
    x.style.display = "block";
} 
else {
   x.style.display = "none";
}

The condition is based on the inline display style. Upon first click, the else block is triggered and sets display: none as the inline style for the element.

To ensure proper functionality upon initial load, consider using the following approach:

if (window.getComputedStyle(x).getPropertyValue("display") == "none") {
    x.style.display = "block";
} else {
    x.style.display = "none";
}

You will only need to click once to observe the applied changes.

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 generate an incidence array using randomly generated array elements?

Considering the following: var dataset = [ {X: 0, Y: 0, ApiKey: "Something"}, {X: 100, Y: 0, ApiKey: "Something"}, {X: 1500, Y: 200, ApiKey: "Something"}, {X: 1600, Y: 850, ApiKey: "Something"}, {X: 0, Y: 750, ApiKey: "Something"}, {X: 0 ...

Is employing the HTML 'confirm' method considered a best practice?

How can I alert a user before they discard changes in a form while switching to another page? Is using if (!confirm("Are you sure")) return false;... considered a good practice for this type of message? Or should I consider using a modal panel instead? (W ...

Angular utilizes ZoneAwarePromise rather than a plain String output

I expected the giver code to return a string, but it is returning ZoneAwarePromise. Within the service: getCoveredPeriod() { let loanDetails = this.getLoanDetails().toPromise(); loanDetails.then((res: any) => { const coveredPeriodStart ...

Issues with implementing Bootstrap tabs in Vue application

Currently, I am in the process of developing an application using vue, vue-router, and bootstrap. My goal is to integrate tags in bootstrap as shown below: <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-l ...

Change the boxShadow and background properties of the material-ui Paper component

I am currently referencing their documentation found at this link in order to customize default Paper component properties. Below is the code snippet I have: import { styled } from '@mui/material/styles'; import { Modal, Button, TextField, Grid, ...

Tips on personalizing Jquery Accordion UI

Why is the accordion panel's height set to 230, but when the webpage opens, it remains at its default height? It only resizes when I move my mouse over it. Also, why does the background color behave this way, changing to white after some height inste ...

Transform the appearance of a button when focused by utilizing CSS exclusively or altering it dynamically

As a newcomer to coding, I am currently working on a project that involves changing the color of buttons when they are clicked. Specifically, I want it so that when one button is clicked, its color changes, and when another button next to it is clicked, th ...

Having difficulty with sorting an array of objects

I am currently facing an issue in React where I have an array of objects with a createdAt attribute that I need to sort. Despite my efforts, the sorting doesn't seem to be working correctly as the output is not in the expected order. I have included t ...

Exploring the issue of nested subscriptions causing bugs in Angular

My current challenge involves nesting subscriptions within "subscribe" due to the dependency of some data on the response of the previous subscription. This data flows down the subscription chain until it is stored in an array. Starting with an array of I ...

Building a contact form in Angular and sending emails with Nodemailer

Currently, I am in the process of setting up a contact form for my website. Since I am utilizing a MEAN stack, it made sense to incorporate the nodemailer module for sending emails. In order to handle this functionality, I have established an endpoint &ap ...

Why isn't the input appearing on the succeeding line below?

<label for="email2">Enter Your Email Address</label> <input type="text" name="email2" id="email2" placeholder="example: [email protected]"> <label for="phone2">Phone Number</label> <input type="text" name="phone2" id= ...

Over time, the FPS of the JavaScript canvas game is decreasing

I've recently delved into a JavaScript canvas project, and a few days ago I began the coding process. I have enemies that are generated with random points on the canvas and move towards them. These enemies are created by running the createEnemy() func ...

Achieving CSS centering with translate and avoiding content overflow

I have a code snippet for centering content both horizontally and vertically. It functions properly unless there is too much content, in which case it gets cut off. Is there a CSS solution to prevent this overflow issue without involving JavaScript? .b ...

JavaScript-Based Header Features Similar to Excel

Currently, I am in the process of developing a function that generates a sequence of strings similar to Excel headers. For those who may not be familiar with Excel, the sequence goes like this: A,B,...,Z,AA,...,AZ,BA,...,ZZ,AAA,...,etc. Here is the code ...

GWT's Stylish Image Carousel

Can anyone recommend a simple image slider for GWT that meets the following requirements: Slides several images from right to left when user clicks on the image (selected image should be at the center) Has endless looping capability (the last image shoul ...

Can the columns of a table be evenly spread out if their width is based on the content within them?

Is there a way to evenly distribute the columns of a table when the width is determined by the content? The table can have 3 or 4 columns that contain dynamic data, with one column potentially having large amounts of data. Here are three example tables: ...

Using CSS3 to target the final <li> element within the main list in a nested <ul> structure

I have a complex list structure: <ul> <li>Item</li> <li>Item</li> <li>Item</li> <li> <ul> <li>Nested Item</li> <li>Nested Item</li> <li>L ...

Struggling to make Vue.js transition effects function properly?

I'm having trouble getting a vue.js (version 1) transition to work. I copied the code from their official website, but it's not running the javascript console.logs! Vue.transition('fade', { css: false, enter: function ( ...

The Vanishing Act of Bulma Dropdowns in Vue Router

On regular pages, the dropdown feature functions flawlessly. However, when using Vue-router in a single-page application (SPA), the dropdown menu seems to vanish between the navbar-item and its child navbar-link unless the cursor is moved quickly from one ...

“Can you confirm if this syntax is correct for defining methods in Vue.js?”

When defining methods in my Vue app, I have chosen to use the following format: methods: { myMethod(arg) { // do something here } } Although it is more common to see it written like this: methods: { myMethod: function (arg) { // do somethi ...