Clicking on different elements in an array using JavaScript to toggle the visibility of a div

Here is a problem I've encountered. This code selects a random element from an array to hide/show a div by toggling it. The issue is that I want it to always open a new one while hiding the previous one with the same button click. Currently, it shows a new element but fails to hide the previous one.
It doesn't have to be randomly selected, but it must consistently open a new element while hiding the others. I'm a bit stuck on this and could use some guidance.

If you have any hints or suggestions, I would greatly appreciate your input. Thank you for your attention!

document.getElementById("rojo").addEventListener("click", show);
var secret =  ["h-ma-1","h-ma-2","h-ma-3" ];
var s = secret[RndInt(0, 2)];

function RndInt(min, max) {
return Math.floor(Math.random() * (max - min+ 1) ) + min;}


function show (){

        for ( var i=0 ; i<=0 ; i++ ){
                if 
            (document.getElementById(s).style.display == "block")
                {
            document.getElementById(s).style.display = "none";
                }
                else 
                {
            document.getElementById(s).style.display = "block";
                }
        }


    }

Answer №1

This piece of code provides a solution for your current task

document.getElementById("rojo").addEventListener("click", show);
var secret = ["h-ma-1", "h-ma-2", "h-ma-3"];
var s = secret[RndInt(0, 2)];

const DEFAULT_VISIBILITY = 'block';

const mapToggle = {
  'block': 'none',
  'none': 'block'
};

function getCurrentVisibility(node) {
  return node.style.display;
}

function getElementFromId(id) {
  return document.getElementById(id);
}

function toggleVisibility(node) {
  node.style.display = mapToggle[getCurrentVisibility(node) ||  DEFAULT_VISIBILITY];
}

function toggle(ids) {
  ids.forEach((id) => {
    var node = getElementFromId(id);
    if (node) {
      toggleVisibility(node);
    }
  });
}

function RndInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}


function show() {
  toggle(secret);
}
<div id="h-ma-1">h-ma-1</div>

<div id="h-ma-2">h-ma-2</div>

<div id="h-ma-3">h-ma-3</div>

<button id="rojo">toggle</button>

Answer №2

Until now, I have found this method to be effective in resolving my issue, although it does not involve using the array directly. This may pose challenges in terms of maintenance.
The approach involves modifying the div name by appending the final segment to it. I have hidden all the div elements in the CSS using display = none.

Thank you

document.getElementById("rojo").addEventListener("click", show);

function show (){

    for (var i=0; i<12; i++){
        var s = "h-ma-" + i;

        document.getElementById(s).style.display = "none";

    }
    
    document.getElementById("h-ma-" + Math.ceil(Math.random() * 11)).style.display = "block";
}

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

"Implementing a function in React to update the state based on target name and value received from

In an attempt to update the state, the current function (handleLabelChange) technically works by updating the state. However, I am looking to dynamically add a name instead of textOne and a value of "????" from the textarea field or another input field. It ...

Issue with React.js button functionality not functioning as expected

import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { items: [] } } addItem(e) { var itemArray = this.state.items; ...

Shuffle the setInterval function: How to consistently rewrite with random intervals?

Seeking guidance on how to implement the following task: generate a random number after a random amount of time and then reuse it. function doSomething(){ // ... do something..... } var rand = 300; // initial random time i = setInterval(function(){ ...

Getting React Developer Tools to Function with Webpack

I recently followed a tutorial on how to expose React as a global variable in Webpack using the Expose module. Despite installing the Expose module and adding the appropriate loader configuration in the webpack.config.js file, I am still unable to access R ...

Angular: Retrieving the Time Format from the Browser

Is there a way to retrieve the time format from the operating system or browser within Angular in order to display time in the user's preferred format? I have attempted to search for a solution, but have come up empty-handed. Thank you in advance! ...

Display a JavaScript object as a table in an HTML document using HTML elements

I am having trouble displaying the results of sorting an associative array in JavaScript in an HTML table without using PHP. The sorting itself is working correctly as I can see the results in the console, but the table is not showing up. Below is the code ...

Combining and overriding two JavaScript objects in real time

I possess two objects. userprofile = { id: 1, email: hello@gmail.com, user: { id: 1, username: test, } } userprofile2 = { email: bye@gmail.com, user: { username: testtest, } } My goal is to merge userprofile with userprofile2, e ...

Reduce the length of the text and display it upon hovering with the mouse

I am trying to figure out how to truncate text and have it expand on mouseover in a paragraph element. I attempted to truncate the content using a specific code, but I encountered an issue. While my current code expands the content when clicking on the el ...

Is jQuery validation compatible with mobile phone numbers?

Is there a way to verify an Iranian mobile phone number using jQuery with the input:text? Iranian mobile phone numbers follow a specific numeral system, such as: 091- --- ---- 093[1-9] --- ---- 092[1-9] --- ---- 090[1-9] --- ---- Here are some example pr ...

Adjust the checked state of the checkbox based on the outcome of the promise's data

Whenever the checkbox is clicked and the resolved data in a promise is false, I want the checkbox to remain unchecked. If the data is true, then the checkbox should be checked. I have set up a codesandbox for this purpose. This example utilizes react and ...

Error message "Illegal string offset" encountered while using a foreach loop

After converting a JSON into an array, I am encountering the "Warning: Illegal string offset" error when trying to extract data from it. It seems like the index I am using does exist, and it works perfectly when accessing the array value directly, so I am ...

Displaying the items in an array using the Arrays.toString() method

After using the following code to create and fill an array, I ran into an issue when trying to print the array using the Arrays.toString() function. Instead of the expected output: newArray: [2, 4, 6] newArray: [8, 10, 12] etc.. I am getting: newArray: ...

Issue with automatic form submission

What is the best way to automatically submit my form once the timer runs out and also when the refresh button is clicked? I have encountered an issue where every time I try to refresh the page, it prompts for user confirmation. If I click cancel, it stay ...

Using Javascript to display or conceal a specific child element within a loop, based on which parent element has been clicked

I need assistance with creating a grid of projects where clicking on a specific 'project' in the loop will display the corresponding 'project_expanded' div, while hiding all other 'project_expanded' divs. My initial plan was ...

Utilizing jQuery for manipulating href attributes

Having some trouble with a jQuery selector to click on a link. Any suggestions or solutions? Thanks in advance. $tweet.html(tweet.created_at + ' <a href="#" class="'+tweet.user+'">@' + tweet.user + '</a>: ' + twee ...

Issue with Ajax reload functions malfunctioning

Embarking on a new journey, I am diving headfirst into the world of web development. As an artist and writer, I have recently delved into the realm of creating a project that integrates a cms, project manager, and database front-end using php, mysql, and j ...

Testing HTTP requests on a form click in Vue.js 2 - Let's see how

Within my component, I have the following method: methods:{ ContactUs(){ this.$http.post("/api/contact-us").then((res)=>{ ///do new stuff },(err)=>{ //do new stuff }) ...

Count the number of times an iteration occurs in AngularJS/JavaScript

I need assistance with my code snippet below, as I am trying to determine the count of all instances where $scope.rm is equal to "failed" or when $scope.percentage is less than 50. angular.forEach(result1, function (value, key) { $scope.percentage ...

What is the best way to include the input object in a JSON array?

In the process of creating a weather forecasting console application, I have encountered an issue regarding saving user input locations. The user is asked if they would like to save the longitude and latitude input, which are then stored in a JSON file. Th ...

Prevent excessive clicking on a div element

I am facing a simple issue that I haven't been able to resolve yet. I want to prevent multiple clicks on a button before an AJAX call is complete. This is what I have tried so far: <button id="btn_pay"></button> $("#btn_pay").click( fun ...