Conceal or reveal buttons using JavaScript

I am struggling with a function that is supposed to hide certain buttons and create a new button. When I click on the newly created button, it should make the previously hidden buttons visible again. However, the function does not seem to work properly.

function hideButtons(){
    var buttons=document.getElementsByTagName("input");

    for(var i=0;i<buttons.length;i++) {
        if(buttons[i].type=="button"){
            buttons[i].style.display="none";
        }
    }

    var back=document.createElement("input");
    back.setAttribute("type", "button");
    back.setAttribute("value","BACK");
    back.setAttribute("id","btnBack");
    back.onclick=showButtons();
    document.body.appendChild(back);
}


function showButtons(){
    var buttons=document.getElementsByTagName("input");

    for(var i=0;i<buttons.length;i++) {
        buttons[i].style.display="initial";
    }
}

Answer №1

It is crucial to avoid invoking the listener function at the time of attaching the event listener:

function hideButtons () {
  var buttons = document.querySelectorAll("input[type=button]");

  for (var i = 0; i < buttons.length; i++) {
    buttons[i].style.display = "none";
    if (buttons[i].getAttribute("id") === "btnBack") {
      // remove the id from the current "back" button
      buttons[i].removeAttribute("id");
    }
  }

  var back = document.createElement("input");
  back.setAttribute("type", "button");
  back.setAttribute("value","BACK");
  back.setAttribute("id","btnBack");
  back.onclick = showButtons; // important!
  document.body.appendChild(back);
}


function showButtons () {
  var buttons = document.querySelectorAll("input[type=button]");
  for (var i = 0; i < buttons.length; i++) {
    buttons[i].style.display = "initial";
  }
}

Answer №2

As PeterMader pointed out, the issue lies in calling the showButtons() function within the event listener. To address this, you can follow Peter's suggestion and call a reference to the function, or alternatively, encapsulate showButtons() within another function.

function hideButtons() {
  var buttons = document.getElementsByTagName("input");

  for (var i = 0; i < buttons.length; i++) {
    if (buttons[i].type == "button") {
      buttons[i].style.display = "none";
    }
  }

  var back = document.createElement("input");
  back.setAttribute("type", "button");
  back.setAttribute("value", "BACK");
  back.setAttribute("id", "btnBack");
  back.onclick = function() {
    showButtons();
  }
  document.body.appendChild(back);
}

function showButtons() {
  var buttons = document.getElementsByTagName("input");

  for (var i = 0; i < buttons.length; i++) {
    buttons[i].style.display = "initial";
  }
}

hideButtons();
<input type="button>
<input type="button>
<input type="button>
<input>

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

Load styles in Nuxt asynchronously to improve performance

Is there a way to load styles asynchronously on the website or insert them in the footer? I am currently using Nuxt version 2.0.0 Here's what I have tried so far: Adding a plugin in webpack called async-stylesheet-webpack-plugin. However, this res ...

When you add the /deep/ selector in an Angular 4 component's CSS, it applies the same style to other components. Looking for a fix?

Note: I am using css with Angular 4, not scss. To clarify further, In my number.component.css file, I have: /deep/ .mat-drawer-content{ height:100vh; } Other component.css files do not have the .mat-drawer-content class, but it is common to all views ...

Exploring Iconography in Amcharts

Is there a simple way to include images/icons within a chart using x and y coordinates? I'm new to javascript and amcharts (am4charts) so any assistance would be greatly appreciated! I've searched for solutions on stackoverflow, like this one o ...

When we modify the prototype of the parent object, where does the __proto__ point to?

Typically, when a new object is created using the "new" keyword, the __proto__ property of the newly created object points to the prototype property of the parent class. This can be verified with the following code: function myfunc(){}; myfunc.prototype.n ...

What is the process for creating a linked TreeNode in the Ant tree design?

After completing a tree design utilizing Ant Design, I encountered an issue where certain nodes within the tree needed to act as links. Despite my attempts to directly assign links, they were not functioning properly. array.map((node) => { if(node.t ...

Is regex the reason why the website isn't showing up properly on mobile devices?

I encountered an issue on my Vue.js website hosted on Firebase where a blank white page was displayed on mobile devices. After some investigation, I traced the problem back to two objects declared in the data function of one of my components: re: { you ...

The node experiences a crash when the redis-server goes offline

Struggling with a persistent issue here. Despite reading numerous documents and posts from others on the same topic, I can't seem to find a solution to prevent this problem. I am intentionally shutting down the redis server to avoid potential disaster ...

Enhancing the appearance of child elements using CSS modules in Next.js

My Countdown component implementation includes: import styles from "./Countdown.module.scss"; import React from "react"; import useTimer from "hooks/useTimer"; import cn from "classnames"; function Countdown({ date, ...

What is the best way to extract the date and pricing information directly from an interactive graph using Python?

My attempt to gather data from a graph using web scraping with the Selenium library was unsuccessful. The graph can be found at this link. from selenium import webdriver driver = webdriver.Chrome() driver.get('https://www.mtgprice.com/sets/Ravnica_All ...

Chrome browser experiencing a disappearing vertical scroll bar issue on a Bootstrap Tab

<div class="tabs-wrap left relative nomargin" id="tabs"> <ul class="nav ultab" id="fram"> <li class="active"><a href="#history" data-toggle="tab" id="history1" >History< ...

Nightwatch failing to locate element within iFrame

I'm currently facing a challenge when trying to access an element within an iframe. Despite successfully switching to the frame, Nightwatch keeps returning "element not found" whenever I attempt to verify its presence or visibility. Below is a snippe ...

The issue of AngularJS directive failing to update controller variable

After conducting an extensive search on both Google and Stack Overflow, I was unable to find a solution to the issue at hand. So, moving forward, here is the problem I am facing: I have created a directive that is intended to retrieve data selected in a ...

Experiencing an excessive number of re-renders can be a common issue in React as it has limitations set in place to prevent infinite loops. This

I have integrated React context to access the login function and error from the context provider file for logging into the firebase database. I am trying to display any thrown errors in the app during the login process. However, I encountered an issue whe ...

Can you please provide a detailed list of all the events that are compatible with the updateOn feature in Angular's ngModelOptions?

The reference documentation notes the following: updateOn: a string that specifies which event should be bound to the input. Multiple events can be set using a space delimited list. There is also a special 'default' event that aligns with the ...

What is the method for transferring form data to a different page?

Currently utilizing AngularJS version 1.5.6 and looking for guidance on properly passing form data using $location.path. Below is my code snippet for Page A: <form> ... <button type="submit" ng-click="submit(formData)"> ...

Updating lodash when it depends on jshint: A guide to NPM

After successfully passing an audit in npm, I received the following results: Now, I am attempting to update my lodash package but I'm unsure of the correct method to do so. I attempted using npm -i --save lodash, however this created another package ...

Showing hidden JavaScript elements in different parts of a webpage

Update: After making modifications to my JavaScript code, I am now encountering errors in the iPhone Debug Console. Disclaimer: As a newcomer to web development, I have limited expertise in JavaScript. Situation: My current project involves creating an e ...

The validation for decimal numbers fails to function when considering the length

I've been struggling to come up with a regular expression for validating decimal numbers of a specific length. So far, I've tried using pattern="[0-9]){1,2}(\.){1}([0-9]){2}", but this only works for numbers like 12.12. What I'm aimin ...

I attempted to publish my React application using gh-pages and encountered the following error: "The argument for 'file' must be a string. However, it was received as undefined."

I encountered an issue while attempting to deploy my React application with gh-pages. The error message I'm facing states: "The 'file' argument must be of type string. Received type undefined." Initially, I suspected that the problem was wi ...

Tips for positioning a Material UI Button and TextField side by side, perfectly aligned on the same line and height

I am currently working on aligning a <Button> from the Material UI library so that it is positioned at the same height as the <TextField> next to it and perfectly aligned with that field. Both the <Button> and the <TextField> are e ...