The JavaScript function will only run after the user clicks the button twice

I attempted to create a button that toggles the visibility of a div element.

Initially, I added the "onclick" event to the button and wrote this function:

function showElement() {
  var element = document.querySelector('.blocks-fnd-div');
    if (element.style.visibility == 'hidden') {
      element.style.visibility = 'visible';
    }
    else {
      element.style.visibility = 'hidden';
    }
}

However, it only functions properly after the 2nd click. I then tried using just JavaScript and came up with this code:

$('.appr-btn').click(function() {
  var element = document.querySelector('.blocks-fnd-div');
    if (element.style.visibility == 'hidden') {
      element.style.visibility = 'visible';
    }
    else {
      element.style.visibility = 'hidden';
    }
})

Since I am not very familiar with this approach, it doesn't seem to work. I would greatly appreciate any assistance you could provide!

Answer №1

The HTML code you provided does not include any .style property, but it seems like you are trying to access the style attribute of the element. If the element does not have any inline styles initially, clicking on it may not have any visible effect the first time. However, behind the scenes, a style attribute will be set, which is why it works the second time.

It is recommended to avoid using inline styles as they can be difficult to override and may lead to code duplication. Instead, consider using CSS classes that can be easily applied, removed, or toggled without the need for complex if/else statements.

// It is more efficient to get the element reference outside the function
// rather than querying it every time the function is called
const element = document.querySelector('.blocks-fnd-div');

document.querySelector("button").addEventListener("click", toggleElement);

function toggleElement() {
  // Simply toggle the presence of the 'hidden' class
  element.classList.toggle("hidden");
}
/* This class is responsible for hiding or showing the element */
.hidden { display: none;}
<button>Toggle</button>
<div class="blocks-fnd-div">Some content</div>

Answer №2

My preference leans towards utilizing CSS class selectors rather than resorting to javascript in order to alter CSS attributes.

When crafting my response, I make it a point to initialize the two objects at the beginning for future reference.

Subsequently, I attach a click event listener to the btn. Within the button, I simply switch a class on the div named "active".

Within the CSS realm, I establish the div's default state as display none (alternatively, visibility = hidden). Following this, I set the .active state of the div to display block, while visibility = visible could also suffice.

const apprBtn = document.querySelector(".appr-btn");
const blocksDiv = document.querySelector(".blocks-fnd-div");

apprBtn.addEventListener("click",(e) => {
    blocksDiv.classList.toggle("active");
});
.blocks-fnd-div{
  display:none;
}

.blocks-fnd-div.active{
  display:block;
}
<button class="appr-btn">Toggle Div</button>
<div class="blocks-fnd-div">blocks-fnd-div</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

Using Bootstrap CSS and JavaScript specifically for carousel functionality

Custom Styles and Scripts for Bootstrap Carousel Using Carousel with Controls https://getbootstrap.com/docs/4.0/components/carousel/ <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner ...

Matching stroke-dashoffset in SVG between two distinct paths

I am currently working on animating stroke-dashoffset for two different paths to create a drawing effect. There are buttons provided to adjust the stroke-dashoffset values. My goal is to ensure that the filled paths align vertically as they progress. Is t ...

Issue with utilizing addEventListener("load") in Firefox in conjunction with <iframe>

I've encountered an issue with my iframe when it is used as the target for a form. In all major browsers, except for Firefox, the iframe successfully removes the main element upon pressing the submit button. However, in Firefox, the main element is re ...

Ways to eliminate the Vuetify append-icon from the sequential keyboard navigation

In my Vue.js application using Vuetify, I have implemented a series of password fields using v-text-field with an append-icon to toggle text visibility. Here is the code snippet: <v-text-field v-model="password" :append-icon="show1 ? 'mdi-eye& ...

Ensure that Google Tag Manager (GTM) delays the pageview until the SPA URL title is available

I'm dealing with a React SPA that manages all the URL titles on the frontend, so the historyChange event registered on GTM captures the visited URLs along with their titles correctly. However, I've noticed that on the initial load of the SPA, su ...

Click on link after animation has finished

I'm currently facing an issue with my script not functioning correctly. The code I'm utilizing is from a resource provided by Codyhouse to implement a 3D rotating navigation menu on my webpage. Essentially, when you click the hamburger icon, it o ...

Error: Unable to instantiate a THREE.Scene object in Three.js due to TypeError

Recently, I decided to experiment with Three.js in order to incorporate it into a project of mine. However, upon running the initial example provided in the documentation: <html> <head> <title>My first Three.js app</title& ...

Issue encountered while constructing an array within the component data following the 'created' event

It's been a while since I've dealt with Vue.Js, so my memory is a bit fuzzy. I'm facing an issue where I can't seem to modify a data array within a function that is called in the created hook. My goal is to create a multidimensional ar ...

Add items to a separate array only if the material UI checkbox is selected

Exploring the world of React, I decided to create a simple todo app using React JS and Material UI. With separate components for user input (TodoInput.js) and rendering individual todos with checkboxes (TodoCards.js), I aim to display the total number of c ...

Browserify does not provide access to the require function in the browser environment

I am currently in the process of developing a web application using node.js along with express. My goal is to leverage Browserify in order to expose my local modules to the browser. Here is the structure of my application: ├── app.js ├── lib ...

The "src" attribute is missing from the image on the left side

I'm currently facing an issue with the src attribute in this code: An event updates the src based on a variable retrieved from a form. The image files cannot be renamed, so I must work with their existing names. The problem arises as all file names c ...

ajax: ensure utf-8 encoding is applied

I am facing an issue with my webpage that is saved in UTF-8 encoding. In the head section of the HTML document, I have defined it as follows: <meta charset="utf-8" /> Within an external JavaScript file, there is a function called ajax_db() which ma ...

jQuery Issue DetectedSlight complication spotted with jQuery

I've encountered a peculiar problem with jQuery's contains function: HTML <span class="tag diaTags label label-info">Teststring<span data-role="remove"></span></span> JS When I directly use $('span.diaTags:contai ...

How to Force a jQuery Redraw Following Data Retrieval Using Ajax

Hey everyone, It's been a long time since I started listening, but this is my first post... I have a client who needs a complex feature on their website. They want to merge the content of 3 different pages into one seamless experience for users afte ...

Each time a new client connects, socket.io replicates the information

Exploring Node.js and socket.io for the first time, I have developed a small application where a table is meant to be displayed in real-time via socket.io when a function is triggered through a websocket (function triggers an "emit"). However, I'm fac ...

Vue.js 2 components encountering issue with parent-child relationship due to undefined item

I recently started working with Vue and encountered the error referenceError: items is not defined. Can anyone help me figure out why this error is occurring or provide some guidance? Upon initial inspection of the code, it seems like the issue may be rel ...

How to choose the desired day within a specific month when creating a calendar from scratch?

Hi there! I need some assistance. I'm currently working on enhancing a calendar by adding an extra feature. The idea is that when the user selects one or more days, those specific day(s) should be highlighted. However, I'm facing an issue where s ...

The function $.getJSON() seems to be non-responsive

I've been struggling to solve this issue for quite some time now. The users.json file that I am using can be found in the "JSON" folder alongside the other files. The alert("Before") is functioning properly, but I'm facing difficulty with getting ...

If the user decides to change their answer, the current line between the two DIVs will be removed

After clicking on two DIVs, I created two lines. Now, I am facing an issue with resetting the unwanted line when changing my answer. To reset the line, you can refer to the code snippet below: var lastSelection; ...

Is there a way to asynchronously load image src URLs in Vue.js?

Why is the image URL printing in console but not rendering to src attribute? Is there a way to achieve this using async and await in Vue.js? <div v-for="(data, key) in imgURL" :key="key"> <img :src= "fetchImage(data)" /> </div> The i ...