JavaScript code to display elements upon button click

I've been working on creating some code that displays elements when a button is clicked. While I can make them appear, I'm having trouble getting each button to show its own set of elements separately (i.e., hiding other elements when a different button is clicked). Where should I focus my efforts to fix this issue?

function showElements(element1, element2) {
  'use strict';
 document.getElementById(element1).className = element1;
 document.getElementById(element2).className = element2;
}

function init() {
  'use strict';
  document.getElementById("btn1").addEventListener("click", function() {
    showElements("red1", "blue1");
  });
  document.getElementById('btn2').addEventListener('click', function() {
    showElements("red2", "blue2");
  });
  document.getElementById('btn3').addEventListener('click', function() {
    showElements("red3", "blue3");
  });
  document.getElementById('btn4').addEventListener('click', function() {
    showElements("red4", "blue4");
  });
  document.getElementById('btn5').addEventListener('click', function() {
    showElements("red5", "blue5");
  });
  document.getElementById('btn6').addEventListener('click', function() {
    showElements("green6", "red6", "blue6");
  });
}

window.onload = init;
.hidden{
  display: none;
}

/* CSS styling for the various color boxes */
<!DOCTYPE html>
<html lang="en">
<!-- HTML structure for displaying the buttons and elements -->
</html>

Answer №1

If I were to suggest an improvement, it would be to create a separate function that hides all elements and then call this function at the beginning of your other functions. Here's an example:

function hideAll() {
 document.getElementById("red1").className = "hidden";
 document.getElementById("blue1").className = "hidden";
 ...
}

You can then call this function in your other functions like so:

function button1() {
 hideAll();
 document.getElementById("red1").className = "red1";
 document.getElementById("blue1").className = "blue1";
}

Don't forget to adjust your CSS rules accordingly by removing the display: none property as shown below:

.red1{
  width: 600px;
  height: 600px;
  background-color: red;
  display: block;
}

.blue1{
  width: 300px;
  height: 300px;
  background-color: blue;
  margin-top: -600px;
  display: block;
}
 ...

It's important to note that this method of programming may not be the most efficient and there are alternative ways to refactor the code for improved readability and adaptability.

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

Tips for formatting angular text sections

Within the scope of a controller, I have a status variable. After a successful rest PUT request, I add a message to this JavaScript variable. This message is displayed in my template using the {{status}} Is there a way to customize the styling of this mes ...

The collapse feature of Bootstrap 5 navbar is experiencing delays

Can anyone assist me with the bootstrap navbar collapse issue I am facing? When I click on the burger menu, there is a slight delay of less than a second before it fully expands. Additionally, if I click very quickly multiple times on the burger icon, the ...

Determine the appropriate text color to use according to the background color

I am looking for a CSS or SASS solution to apply red text color to paragraphs with white or transparent backgrounds, and yellow text color to paragraphs with non-white backgrounds. Here is an example of what I'm trying to achieve: p { @if $selectedP ...

Maximize background width with a gradient that is compatible with web-based email clients such as Outlook and Gmail

Recently, I was given the task of creating a newsletter to support cancer fundraising. Excitedly, I accepted the assignment but encountered a frustrating issue with web-based email clients (such as outlook.com and gmail.com) not accepting some of my stylin ...

propagate the previous state using a variable

Currently, I am in the process of refactoring a codebase but have hit a roadblock. My main aim is to update the state when the onChange event of a select box occurs. Specifically, the parameter searchCriteria in my handleFilterChange function is set to in ...

When retrieving data from a PHP $_SESSION using an Ajax $_POST call, outdated information is being returned

I am encountering an issue that I cannot seem to figure out. Currently, my application consists of three pages: Home.php Nearmiss.php Reports.php Each of these pages includes code at the top with a specific "thispage" variable unique to that page. < ...

Exploring MongoDB through proxyquire

To simulate a MongoDB dependency using proxyquire in my testing scenario, I have the following code snippet: var proxyquire = require('proxyquire'); var controller = path.resolve('.path/to/controller/file.js'); inside the before each ...

Tips for obtaining the most recent HTML element in Angular

I was able to include HTML content in an Angular (7) UI using the DomSanitizer this.sanitizer.bypassSecurityTrustHtml("htmlstr") Once the content is sanitized and displayed in the HTML view, users have the ability to modify the values as desired ...

Using the select method in JavaScript arrays

Are the functionalities of JavaScript and Ruby similar? array.select {|x| x > 3} Could it be done like this instead: array.select(function(x) { if (x > 3) return true}) ...

Layering one canvas on top of another

Here is the code I am working with. With a JavaScript library, I can draw on the first canvas and then merge it onto the second canvas. My question is, how can I make the first canvas stay in place or float, regardless of where I scroll on the second canv ...

Using jQuery to detect when text is pasted into a contenteditable division

On my HTML page, I have a contenteditable div acting as a textarea: <div id="txt" contenteditable="true"></div> To capture the user's input, I am using jQuery to listen for "input paste" $('#txt').on('input paste',fu ...

"Understanding the impact of CSS margin on elements nested within a container with position

I find myself in a tricky situation right now. To make things easier, I'll show you what I've created and highlight the issue, rather than explaining it all. I've been on the hunt for a solution for quite some time, to no avail. If you vis ...

What is the procedure for generating a mouse event for clicking a tab in Selenium WebDriver?

As I work with Selenium WebDriver and Java, there is a tab named PR Per Product. Under the PR Reports tab, there are multiple tabs. In the PR tab, I used: WebElement menuHoverLink = driver.findElement(By.id("ext-pr")); actions.moveToElement(menuHoverLink) ...

The positioning of Material UI InputAdornment icons is located beyond the boundaries of the TextField input area

I am struggling to understand why my InputAdornment is not positioned correctly. There doesn't seem to be any style in my code that would affect the location of the icon within the TextField (such as padding or flex properties). Currently, the calen ...

The exact problem with aligning the table

Below is a simplified version of my code: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> </head> <body style="font-size: 36px"> </body> </html> <html> ...

Is there a way to showcase a countdown timer on an Angular Toaster?

I am utilizing the ng-Idle and Angular Toaster modules in my project. I aim to exhibit a toaster notification during the IdleWarn event of ng-idle, along with the countdown value. $scope.$on('IdleWarn', function(e, countdown) { console.log ...

What is the recommended element for managing data in React?

Let's consider a scenario where we have 2 main components: class App extends React.Component { state = { comments: [1, 2, 3, 4] } render() { return ( <Comments /> ) } } class Comments extends React.Component { rende ...

Vue.js not populating select option tags

I've encountered an issue with my profie.html code that is intended to display division dropdown values using vue.js v-for and {{ val.division_name }}. However, the dropdown is rendering blank values even though there are supposed to be values present ...

Creating a button in ReactJS with text displayed under an icon

Presently, I am working with a component that looks like this: https://i.stack.imgur.com/qGCwj.png This is the code for the component: import React from "react"; import {withStyles} from "material-ui/styles"; import Settings from "material-ui-icons/Setti ...

Connecting icons in Laravel: A step-by-step guide

I have experience linking style CSS using the code: {{ HTML::style('css/styles.css') }} However, I am unsure how to link an icon in Laravel since it is not a standard CSS or JS file. Can anyone provide guidance on this? ...