JS instant Toggle (just one click) - initial value of toggled item

Can you explain why we have to click twice on this link (http://jsfiddle.net/xL8hyoye/4/):

html:

<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>

css: #foo {display: none;}

js:

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'none')
      e.style.display = 'block';
   else
      e.style.display = 'none';
}

However, by just clicking once the text disappears on this link (http://jsfiddle.net/xL8hyoye/5/):

html:

<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo" style='display:none'>This is foo</div> <!-- add display style here -->

css: <!-- delete ccs here -->

js:

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'none')
      e.style.display = 'block';
   else
      e.style.display = 'none';
}

Answer №1

Verify if the style.display attribute is not set

    function change_visibility(id) {
       var element = document.getElementById(id);
       if(element.style.display == 'block' || element.style.display == '')
          element.style.display = 'none';
       else
          element.style.display = 'block';
    }
<a href="#" onclick="change_visibility('foo');">Click here to change the visibility of element #foo</a>
<div id="foo">This is foo</div>

Answer №2

When using .style, it refers to the inline style of an element rather than the styles defined in the CSS stylesheet. For instance, it will work correctly in this scenario:

<div id="bar" style="visibility: hidden;">This is bar</div>

Check out this example. Without inline styles, the .style property is not recognized when placed in the CSS. In the provided example, the first click sets the e.style.visibility, after which it functions as expected. This explains why two clicks are necessary initially.

An alternative solution is to include an else statement to set

e.style.visibility</code as required, assuming the element is initially hidden:</p>

<pre><code>if(e.style.visibility === 'visible')
    e.style.visibility = 'hidden';
else if( e.style.visibility === 'hidden' )
    e.style.visibility = 'visible';
else 
    e.style.visibility = 'visible'; 

Answer №3

In the documentation for getElementById(), it is mentioned that:

Document.getElementById()

This function returns a reference to the element based on its ID.

For more information, visit: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

When using this JavaScript code, keep in mind that it only targets the HTML elements without considering CSS, especially on the first iteration. This explains why it goes to the else statement initially and then changes the value of e.style.display to block on the second click, as it had the value of none before.

If necessary, consider using a different method instead of getElementById().

I hope this information proves useful!

Answer №4

To resolve this issue, consider rearranging the sequence in your if-else statement, for example:

if(e.style.display === 'block') {
    e.style.display = 'none';
} else {
    e.style.display = 'block';
}

DEMO

Note: The reason your original code was not functioning correctly is due to the initial value of e.style.display being empty ("") instead of none. Keep that in mind when troubleshooting the issue. :)

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

Reorganize a list based on another list without generating a new list

Among the elements in my HTML list, there are items with text, input fields, and tables. I also have a specific order list like [3,1,2,0]. Is it feasible to rearrange the items in the HTML list on the page based on this order list without generating a new ...

How can I include a path prefix to globs provided to gulp.src?

Consider the contents of these two essential files: settings.json { "importFiles": [ "imports/data.js", "imports/functions.js", "imports/styles.css" ] } builder.js var build = require("builder"), combine = require("combine-files"), ...

Vue.js encountered an error: Unexpected TypeError in promise. The function $set is not recognized

Currently, I am working on fetching comments from the Reddit API and attempting to update an array using $set in order to refresh the view. However, I encountered an error: Uncaught (in promise) TypeError: $set is not a function Virtual Machine Component ...

Is it possible to send an entire HTML table to the server and then update the database table with it?

Recently, I encountered an issue that has me stumped. Suppose I have a database table A with multiple columns and the server (PHP script) renders this data into an HTML table for the web client. Now, the challenge lies in allowing users to add/delete rows ...

A pop-up window displaying an electron error message appears, but no errors are logged in the console

In a Nutshell: While developing a single-page website with Electron, I encountered the common issue of jQuery not being globally accessible. To tackle this problem, I decided to simplify it by using a quick start example, but unfortunately, I'm strugg ...

React Native: Picker value remains static

I'm encountering an issue where the value of the picker does not change when I select a new value from it. This problem started occurring after I added the onValueChange function. If anyone has any insights or suggestions on how to resolve this, I wou ...

What is the best way to modify an array's property in order to achieve the desired outcome when using json_encode?

Expected Result ['#ff0000','#4caf50','#4caf50','#4caf50','#00bcd4','#00bcd4','#4caf50','#4caf50'] The output I am receiving is as follows: ["'#ff0000','#4caf5 ...

To retrieve the value of a specific row within a table and remove that row

I have utilized handlebars to display a table with data, each row containing an edit button. I am unsure how to retrieve the specific values from the row when the edit button in clicked. Here is the HTML code: <table class="table table-bordered"& ...

Using redux alongside fela and react: A comprehensive guide

First of all, thank you for your attention. I am currently exploring the use of fela for dynamically styling my components and for managing app states, I plan to incorporate redux. In fela, it's necessary to utilize a Provider to encompass all app com ...

The hamburger icon seems to be frozen and unresponsive

I'm struggling to get my hamburger icon to reveal the navigation bar when clicked. The icon itself functions properly and adapts to different screen sizes, but the overlay remains stationary. Check out my code on JSFiddle! <html> <head> ...

Create a web design where two HTML elements with full width are positioned to overlap each other,

I am facing a design challenge where I need sections to span the full width of the page, but the content is contained within an article. Additionally, there is an interactive aside that needs to float above the full-width sections. Both the article and as ...

How can I verify the submitHandler function using the JavaScript id?

Is there a way to implement a submitHandler on an id for validation purposes? I would like to specify a specific id to handle the validation. Here is an example of the current code: $("#validate").validate({ rules: { "name-contact": { ...

Utilizing App Script for Filtering Data with Multiple Criteria

Having trouble transferring data from a data sheet to my report sheet using multiple criteria for matching. I wrote some code that worked, but it's returning all data instead of filtering by criteria. I want the function to search for column criteria ...

Tips for correctly cloning a table row:

Currently, I am engaged with a Django project that involves incorporating a form within a table structure. <table name="mytable" id="table_purchase" role="grid"> <thead> <tr> <th class="text-center" hidden>No</th& ...

Arrange the two buttons in a vertical position

Excuse any weak code you may come across, as I am a backend developer. This is the current appearance of my form: The alignment of these two buttons in Chrome is not correct The issue only occurs in Chrome, with FireFox and Edge displaying the form as e ...

Harness the power of ng-click in conjunction with data-ng-href for a

I am attempting to create a button that takes the user to the product details while also having the ability to increase a counter using an ng-click function. <div class="row center-block save-button" > <a data-ng-href="/savings/{{saving._id}} ...

Unique Identifier - primary export (ReactJS - JavaScript)

I am facing an issue concerning generating ID's for alerts using the uuid library. However, when attempting to import the library in the alert.js file, an error message is displayed: ./src/action/alert.js Attempted import error: 'uuid' does ...

Unable to integrate Django into HTML

Having trouble using Django variables within HTML code Here is the code snippet: models.py from django.db import models from django.urls import reverse # Define models here. class Post(models.Model): title = models.CharField(max_length=255) slug ...

What kind of data does this collection hold, and what is the best method to retrieve its stored values?

I recently received a code to program a logic for and I have successfully figured out my algorithm. However, I am facing difficulty determining the datatype of a particular declaration. My task involves comparing the values of "skills" in each row to &apos ...

Use CSS properties to isolate and extract the logo from the Sprite image

If we have a sprite image, like the StackOverflow sprite, and CSS properties like: background-position: 0px 0px; width: 250px; height: 61px; We can use the Chunky PNG library to crop out a specific part of the sprite. However, some websites use negative ...