Steps to create a custom function that can manage numerous onclick actions to toggle the visibility of a specific field

I'm relatively new to coding and JavaScript. I'm working on a basic webpage that involves showing and hiding parts of sentences for language learning purposes. Is there a way to create a single function that can show and hide the sentence when a button is clicked?

If I use document.getElementsByClassName() to get an array of buttons and iterate through them, I'm unsure how to connect them to one function that performs the showing and hiding functionality. I've seen examples using getElementById but I'm looking to achieve the same result with document.getElementsByClassName().

const a = document.getElementById("button1").addEventListener( "click" , function(){
  if(document.getElementById("para1").style.visibility === "hidden"){
    document.getElementById("para1").style.visibility = "visible";
  }else{
    document.getElementById("para1").style.visibility ="hidden";
  }

I've checked other questions related to this topic, but they seem too advanced for what I'm trying to accomplish. I understand this is basic stuff, but any guidance would be greatly appreciated.

I attempted the solution above as described, but I'm struggling to figure out how to connect one function to multiple buttons.

Answer №1

If you're looking to implement event bubbling, consider utilizing the mechanism explained in this resource: https://javascript.info/bubbling-and-capturing

  1. Place the event on a top-level container
  2. Determine the button triggered by the event
  3. Retrieve the ID of the element to toggle
  4. Toggle the visibility of the element
// Check out the code example here: https://jsfiddle.net/shiningfinger/b5uxcwpo/4/

const getControlElement = (element) => {
    if (
        element.tagName === "A" ||
        element.tagName === "BUTTON" ||
        (element.tagName === "INPUT" &&
            (element.type === "submit" || element.type === "button"))
    ) {
        return element;
    }

    const { parentElement } = element;
    if (!parentElement) return false;
    return getControlElement(parentElement);
};

document.addEventListener("click", (event) => {
    const controlElement = getControlElement(event.target);
    // Place element ID in data-toggling-element-id attribute
    const { togglingElementId } = controlElement.dataset;
    const togglingElement = document.getElementById(togglingElementId);

    if (!togglingElement) return;

    togglingElement.style.visibility =
        togglingElement.style.visibility !== "hidden" ? "hidden" : "visible";
});

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

Ways to show the existing value of a <select> in a label without altering the function

I currently have a label that changes to display the selected option from a dynamic select dropdown, but it only updates when the selection is changed. I would like it to also display the current value when the page first loads. I attempted to change &apos ...

TypeScript and the Safety of Curried Functions

What is the safest way to type curried functions in typescript? Especially when working with the following example interface Prop { <T, K extends keyof T>(name: K, object: T): T[K]; <K>(name: K): <T>(object: T) => /* ?? */; ...

What is the best way to retrieve the name of a dynamic form in a Controller

How can I retrieve the dynamic form name in my controller? See below for the code snippet: HTML <form name="{{myForm}}" novalidate> <input type="text" ng-model="username" name="username" required/> <span ng-show="(submit & ...

Audio suddenly no longer working after transferring project to React

View my reproducible example here. This is a demonstration of the issue I am facing. Previously, when the page consisted only of static html with javascript, the sounds were functioning correctly. However, after refactoring into a React app, the sounds ha ...

Exploring the secure synergy between Laravel 5.5 Passport client_secret and Vue JS authentication

Greetings to all, Currently, I am delving into the world of Laravel Passport and Vue.JS (standalone) simultaneously. In my authentication process, I am utilizing the Password Grant Token. An issue that has come up is the necessity for keeping the secret_ ...

Receiving and monitoring events triggered by a Vue component that was dynamically mounted

I am currently mounting a Vue component dynamically within a mixin to incorporate the resulting HTML into a map popup. While everything is functioning correctly, I am facing an issue with listening to events emitted by the component. I am unsure of how to ...

contenteditable -- Utilizing AngularJS to create a block element for the title only

When I click on an input field that is editable, I want the background color to change to white within the box. Can someone please assist me with this? Below is my code: HTML <div id="section{{section.index}}"> <h2 class="title" contentedit ...

Utilizing the Twitter API variable within ExpressJS while incorporating AngularJS

Using the "twit" Twitter package from GitHub, I am able to call the Twitter API and retrieve data that is logged in the console. However, I am unsure of how to pass this data to AngularJS in order to display the tweets on the front-end. T.get('search ...

"Using Node.js for proxying requests and implementing OAuth authentication

Having a small node.js application that relies heavily on oAuth, I encountered an issue: the server where I intend to install it is concealed behind a proxy. This necessitates rewriting a portion of the code to incorporate proxy usage. Here's my query ...

Switch out single quotation marks and double quotation marks

I have a variable stored in my MySQL database that needs to be able to handle both simple and double quotes. For instance: $variable = "I'm feeling great" or $variable = I'm feeling great or $variable = "I am feeling great" In my database, the ...

Resizable dimensions for the dark mode switch

My latest project involves creating a toggle button for switching between light and dark themes using CSS, HTML, and JavaScript: id("theme-btn").addEventListener("change", function() { if (this.checked) { qs(".box").setAttribute('style', ...

Formik's handleChange function is causing an error stating "TypeError: null is not an object (evaluating '_a.type')" specifically when used in conjunction with the onChange event in DateInput

When using the handleChange function from Formik with the DateInput component in "semantic-ui-calendar-react", I encountered an error upon selecting a date. https://i.stack.imgur.com/l56hP.jpg shows the console output related to the error. AddWishlistFor ...

Is it possible to nest Route components in react-router version 4.x?

How can one properly implement nested routes in react-router version 4.x? Previous methods like the one below worked well, but upgrading to version 4.x now results in a warning... <Route path='/stuff' component={Stuff}> <Route path=&a ...

Is Babel necessary for a Node.js server application, and what are the benefits of using it?

My fondness for ES6 syntax and its new object-oriented style makes coding much easier for me. However, as a newcomer to JavaScript, I am curious about the advantages and disadvantages of using Babel in terms of performance, maintenance, readability, and ...

Having trouble displaying images in Express JS

Here are the lines of code that I wrote in Express: res.write("The current temperature is "+temp+". "); res.write("Weather is currently "+weatherDes); res.write("<img src=" +imageURL+ ">"); res.send() ...

Discovering whether the incoming request to an AngularJS application is a GET or POST request can be efficiently accomplished

I recently started learning angularjs and I successfully built an application using the angular seed skeleton https://github.com/angular/angular-seed for the client side. For my API server, I utilized expressjs server. The URL of my home page is localhost ...

Tips on Extracting Data from a JSON Object with an Embedded Array

Check out this example of a Json Object: {"UserName":Mike,"IsActive":0,"ChbxIsActive":false,"MyAccountsAvailable":[{"Id":"157A","MyAccount":"CHRIS MCEL","MyCheckBox":false,"Tags":null},{"Id":"157B","MyAccount":"DAN BONE","MyCheckBox":false,"Tags":null} He ...

I have implemented a code snippet that verifies if the incoming week aligns with the existing week, triggering an alert accordingly

One of the challenges I faced was checking if a newly created week matched with an existing one, and then displaying an alert. Here's how I approached it: $scope.addWeek = function(type,newWeek,index){ var c = $scope.weekList.length + 1; var ...

Jump straight to the top of the page with just a click using the Google Maps Store Locator

When I use my Store Locator and click on an anchor like "Zoom Here," "Directions," or "Street View," the href hash always brings me back to the top of the page. How can I prevent this from happening? I've tried examining the minified source code for t ...

When I run my app with the wxPython GUI I developed, the functions seem to not be executing as expected

Currently, I am working with Python 2.7 to build a GUI for a specific text editor using wxPython. For this purpose, I have developed two scripts, namely gui.py and app1.py, which are located in the same folder. The issue arises when I execute app1.py as i ...