Issue Encountered While Attempting to Show a Div Element within a Function

Check out this HTML code snippet:

<div class="div1" id ="div1" onclick="onStepClicked()" style ="text-align:center">Step 1</div>

And here is the corresponding Script:

function onStepClicked() {
        var elem = document.getElementById('div2');
        if (Visible = true) {
            elem.style.visibility = 'hidden';
            Visible = false;
        }
        if (Visible = false) {
            elem.style.visibility = 'visible';
            Visible = true;
        }
    }

The issue arises when clicking on the Div for the second time. Although it gets hidden correctly on the first click, making it visible again on the subsequent clicks doesn't seem to work as expected. There might be a simple error that needs addressing.

Answer №1

 function onStepClicked() {
        var elem = document.getElementById('div2');
        if (isVisible === true) {
            elem.style.visibility = 'hidden';
            isVisible = false;
        } else if (isVisible === false) {
            elem.style.visibility = 'visible';
            isVisible = true;
        }
    }

When assigning a value to isVisible, make sure to use === or == for equality comparison.

Moreover, if you don't need isVisible elsewhere, simplify the code like this:

 function onStepClicked() {
        var elem = document.getElementById('div2');
        if (elem.style.visibility === 'visible') {
            elem.style.visibility = 'hidden';
        }
        else {
            elem.style.visibility = 'visible';
        }
    }

Answer №2

 function toggleVisibility() {
    var targetElement = document.getElementById('section2');
    if (targetElement.style.visibility == 'visible')
        targetElement.style.visibility = 'hidden';
    else
        targetElement.style.visibility = 'visible';
}

The error here is mistakenly setting Visible equal to true in the initial if statement. It's crucial to remember the distinction between Visible = true and Visible == true. The former assigns a value to Visible (= is an assignment operator) while the latter compares it with True (== is a comparison operator).

In this particular code snippet, there isn't a need for an extra Visible variable. However, feel free to reintroduce it if it's essential in other sections of your code.

Answer №3

After reviewing your code, I noticed a few things: - You are looking for div2 but the id of your div is actually div1 - The if statement should use == or === instead of just =

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

A technique for calculating the total quantity of each item individually while using v-for in VueJS

Struggling to code (complete newbie) using VueJS and facing a major roadblock. I have a list of orders and I need to sum the quantities of each item separately. The only way to access the items is through v-for. <tr> <td data-th="list"> < ...

Obtain HTML tags from RSS CDATA section

Is there a way to extract HTML tags from a CDATA tag in an RSS feed? I have utilized a basic jQuery function to retrieve the JSON object from the RSS, below is my code: $.get("someURL", function(data) { console.log('InGet'); ...

Best practices for coding in HTML and CSS

Creating my first website for an internship has been quite a learning experience. Throughout my training, I was always advised to avoid embedding styles directly into the HTML code. However, now that I am actually developing a site, I can't help but f ...

Issues with date clicking on FullCalendar in Angular

I'm currently using version 4.4.0 of the FullCalendar plugin, but I am facing an issue where the dayClick event is not being triggered in my code. Below is a snippet of my code: calendar.component.html <full-calendar defaultView="dayGridMonth ...

Using Handlebars JS to incorporate HTML tags such as <li>, <br>, and more in your data

Is there a way to use handlebars to display a list of data in an unordered format, with "title" and "articles" as the main categories? The issue arises when some of the articles contain HTML tags, such as <a> for links. In my current code, instead of ...

Tips on choosing a child element with a parameter in React

Is it possible to pass a parameter in my function and use it to select a child of my JSON parse? I want to create a function (checkMatch) that can check if a username in my database matches with the input value. It should return 1 if there is a match, oth ...

Position child divs at the center of the parent div

I am struggling to center 3 child divs inside a parent div that must remain at a width of 100%. Can someone help me figure out how to achieve this? .parent { width: 100%; border: 1px solid blue; } .child { float: left; borde ...

Determine if the same origin policy is in effect

Is there a method to determine if the same origin policy is applicable to a URL before attempting to use ajax methods? Below is an example of what I currently have: function testSameOrigin(url) { var loc = window.location, a = document.create ...

Using an array as the source for your Mui Autocomplete instead of JSON

I'm attempting to recreate the autocomplete MUI example shown here, but with a slight variation. Instead of utilizing a JSON data structure, I am simply passing an Array. Here is what I have tried: export default function SearchTutorialArray() { con ...

Activate the element only when all input fields are completed. This function can be used repeatedly

I am working on developing a versatile function that will iterate through all input fields. If any of these fields are empty, I want to trigger the toggling of a class name (disabled) on another element (such as an anchor or button). Currently, the functi ...

These specific resources don't have a cache expiration set. Wondering how to properly set a cache expiration for a JavaScript file

I am working on a web application that utilizes external JavaScript files. Upon running Google's page speed tool, I realized that several resources are missing cache expiration settings, including images and CSS files. Can you provide examples of how ...

flash animation on an HTML webpage (fancy pop-up)

Hey, I'm interested in creating a similar effect to this: Check out this example >> Simply click on "Start PicLens Lite Slideshow PicLens". Did you notice how the swf/flash loads on top of the regular page? I want to achieve that :-D If there is an ...

Is it possible to have separate ports for front-end and back-end in NODEJS?

As I develop my NodeJS website, incorporating both front-end and back-end components, it is recommended to organize the files in such a way that the front-end specifically requests data from the back-end via an API. I am curious whether it is considered a ...

Why does jQuery's each function struggle to retrieve the width of hidden elements?

Why is it difficult to obtain the width of hidden elements? Here is my code: .hidden { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <ul class="navbar-items"> <li> ...

Select a random class from an array of classes in JavaScript

I have a collection of Classes: possibleEnemies: [ Slime, (currently only one available) ], I am trying to randomly pick one of them and assign it to a variable like this (all classes are derived from the Enemy class): this.enemy = new this.possibleEn ...

Is there a method to directly download large files from the server without having to wait for the blob response?

I'm currently working on video file requests using axios. I have set the requests with responseType: blob to create a video player once the response is received with window.URL.createObjectUrl(). However, I also have a button that allows the user to d ...

Is there a way to assign a null value to an empty material UI text field when submitting the form, rather than an empty string?

One issue I am facing is that the default value of the text field is zero, but when I submit the form, the value of the text field becomes an empty string instead. This is not the intended behavior as I want the value to remain zero in the end. How can I r ...

The absence of req.body in the app reflects an undefined state

I'm encountering an issue with my app and I believe showing you my code is the best way to explain the problem: var Meetup = require('./models/meetup'); module.exports.create = function (req, res) { var meetup = new Meetup(req.body); c ...

Dynamically loading Ember templates with asynchronous requests

I need a way to dynamically load HTML content from another file using the code below: App.MainView = Ember.View.extend({ template:function(){ $.ajax({ url: 'views/main.html', dataType: 'text', async: false, ...

Iterate through the xml.documentElement in a loop

I want to show 8 men and 2 women in SVG format. However, my current function only displays one man and woman. How can I add a loop to make this work for all individuals? for (i = 0; i < Serie[n].Number; i++) { return xml.documentElement } The data arr ...