"Guide to triggering the display of a particular div based on its class when clicked

I have multiple div elements with the class name dis

HTML:

<div class="dis">Content</div>
<div class="dis">Content</div>
<div class="dis">Content</div> and so on ...

Additionally, there are various images:

<img src="icons/image1.png" class="admoicn" onclick="toggle_visibility('dis');" >
<img src="icons/image2.png" class="admoicn" onclick="toggle_visibility('dis');" >
<img src="icons/image3.png" class="admoicn" onclick="toggle_visibility('dis');" > 

CSS:

.dis{  
    display:none;
    width:100px;
    height:100px;  
}

Javascript:

function toggle_visibility(id) {
    var e = document.getElementsByClassName(id)[0];
    if(e.style.display =="block"){
        e.style.display ="none";
    }
    else{
        e.style.display ="block";
    }
}

Upon clicking any image, the corresponding div with class dis should open. For example, clicking on the third image3.png should reveal the third dis div while closing all others that may be open.

I suspect there may be an issue with arrays in the Javascript class causing this functionality problem, but being new to Javascript, I am unsure how to resolve it.

Answer №1

One potential enhancement could be adding an additional parameter to the toggle_visibility function:

<img src="icons/image1.png" class="admoicn" onclick="toggle_visibility('dis', 0);" >
<img src="icons/image2.png" class="admoicn" onclick="toggle_visibility('dis', 1);" >
<img src="icons/image3.png" class="admoicn" onclick="toggle_visibility('dis', 2);" > 

This new parameter can be used as an index for accessing elements in an array:

function toggle_visibility(id, index) {                    
    // Close all divs
    var els = document.getElementsByClassName(id);
    for (var i = 0; i < els.length; i++) {
        els[i].style.display ="none"
    }

    // Show selected div
    els[index].style.display = "block";
}

Check out this JSFiddle demo for a better understanding.

Additionally, it's important to name variables appropriately. If the argument represents a class name, use a more descriptive name like className instead of id.

Answer №2

If you're looking to achieve this, check out this helpful codepen link.

$(document).ready(function(){
    $("img").click(function(){
        var classname = this.id;
        $('div').removeClass('show');
        $("."+classname).addClass('show');
    });
});
img{
      cursor:pointer;
      width : 30px;
      padding:20px;
      border:1px solid #333;
}

div{
      display:none;
}
.show{
      display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://image.flaticon.com/icons/svg/149/149384.svg" id="Phone" />
<img src="http://image.flaticon.com/icons/svg/149/149181.svg" id="chem" />
<img src="http://image.flaticon.com/icons/svg/149/149098.svg" id="cam" />

<div class="Phone">
    <h1>Hi This is phone</h1>
</div>
<div class="chem">
    <h1>Hi This is chem reaction</h1>
</div>
<div class="cam">
    <h1>Hi This is camera</h1>
</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

Converting MongoDB Queries to MySQL in Node: A Step-by-Step Guide

I am currently facing a challenge where I need to migrate my app's database from mongoDB to mysql. The application was initially developed using node.js, but I encountered an issue with the "Create table" query while attempting the conversion process. ...

Generating Arrays of Varying Lengths in ReactJS

When receiving data from the API, I have an array structured like this: [ { "clicks": { "2019-01": [ { "clicks": "194", "type": 0, "user": 19 }, { ...

HTML control for adjusting the pan and tilt of a device

I'm looking to develop an interactive input where users can drag a dot within a box and see the 2D coordinates of that dot displayed. The goal is to use this feature to control pan and tilt values. A similar functionality from another application is s ...

The planebuffergeometry does not fall within the three namespace

I am currently working on a project using three.js and next.js, but I keep encountering this error: 'planeBufferGeometry is not part of the THREE namespace. Did you forget to extend? See: As a beginner in three.js, I'm unsure what exactly is ca ...

Storing user input from a dynamic form into a database using Kendo UI

I've successfully populated dynamic input form fields. However, I'm unsure how to save the data into a database using a put/post API since I have only used a get API so far. HTML code <div id="renderform" class="form horizontal-for ...

Implementing Google Fonts into Next.js with the combination of Sass, CSS, and Semantic UI React

I have set up my next.config.js file with the following configuration: const withSass = require('@zeit/next-sass'); const withCss = require('@zeit/next-css'); module.exports = withSass(withCss({ webpack (config) { config.module. ...

Embed a Vaadin component within an element dynamically generated by a Javascript component

I am currently designing a Vaadin application and working on a custom Javascript component, which is a subclass of AbstractJavascriptComponent. This component uses jQuery to generate a table-like structure. In certain scenarios, users should be able to in ...

Tips for effectively showcasing the counter outcome amidst the increase and decrease buttons

Currently, I am in the process of learning Angular and have created a component called quantity-component. Within the quantity-component.component.html file, I have implemented 2 buttons for increment (denoted by +) and decrement (denoted by -). The decrem ...

jQuery AJAX Concurrent Event

I have encountered a problem similar to ones discussed on SO, but none exactly match my specific issue. Here's the situation: var x = 5; if( some condition ){ $.ajax({ url:"...", success: function(response){ x = respo ...

The outcome of Contains function is coming back as negative

Recently, I was working on a project that I cloned from GIT, which involved a bot. However, I encountered an issue where the 'contains' function used by the bot was not functioning properly. After conducting some research using Google, I discove ...

Is there a way to incorporate tailwind classes into each react component when utilizing the map() function?

While working on a React Movie app, I encountered an issue with the tailwind class mx-auto. It was not applying properly to all items in the array; only the first element was affected. const MoviesList = () => { return( <div className=&a ...

Ways to determine if a date matches today's date within a component template

I am currently displaying a list of news articles on the webpage and I want to show the word "Today" if the news article's date is equal to today's date. Otherwise, I want to display the full date on the page. Is there a way to compare the news.D ...

What is the best way to generate JSX from a callback function in ChartJS?

I am currently utilizing react-chartjs-2 within a React application and I am interested in incorporating JSX code into the Y axis. However, when attempting to do so, it only shows [Object object]. const chart = new Chart(ctx, { type: 'line', ...

What if there was a magical jQuery method that could automatically trigger a callback function? What could it possibly be named?

Is there a way to load only images and iframes, similar to the .load() function? I want to automatically add a selector element into the "this" variable for this purpose. $('document').ready(function({ $('a').<Something to trigg ...

Incorporate CSS file into the head section or directly within the HTML section without the need for JavaScript

I'm facing an issue with adding a CSS file to my webpage using JavaScript code at the bottom of the page. When users disable JavaScript, the file cannot be added. Is there a way to include the CSS file in the page without relying on JavaScript? $(doc ...

Load charts.js synchronously into a div using XMLHttpRequest

At the moment, there is a menu displayed on the left side of the page. When you click on the navigation links, the page content loads using the code snippet below: if (this.id == "view-charts") { $("#rightContainer").load("view-charts.php"); $(thi ...

Extracting Query Parameters from a Successful Ajax Call in Javascript

How can I extract data from the success response? Take a look at my code snippet: $.ajax({ async: 'true', url: 'https://exampleapi.com/product', type: 'GET', data: {page: idQuery}, success:(response => { v ...

Struggling to concatenate array dynamically in Vue using ajax request

I am working on a Vue instance that fetches objects from a REST endpoint and showcases them on a web page. Most parts of the functionality work smoothly like filtering, however, there is an issue when attempting to add new objects by requesting a new "page ...

The Vue component with the export default directive could not be located

Whenever I try to create a dashboard component, I keep encountering the same error in my command prompt. "export 'default' (imported as 'DashboardLayoutComponent') was not found in '@syncfusion/ej2-vue-layouts' Has anyo ...

What is the purpose of using a visually striking and prominent HTML tag?

After 15 years of working in html development and managing multiple websites, I have come to realize that bold and italic tags essentially serve the same purpose. I can apply CSS styles to both to achieve similar effects. I have even experimented with maki ...