Toggle the visibility of divs by swapping image on click

As a beginner in the realm of coding with Javascript, html, and related technologies, I am seeking guidance on how to enhance my current work.

My goal is to create a webpage featuring 4 images serving as buttons, each corresponding to 4 hidden divs with data. Initially, all divs are set to not display. The buttons successfully toggle the visibility of the corresponding divs. However, I also want to show alternative versions of the image buttons when a div is displayed.

Below is the snippet of javascript and html code I have crafted thus far:

<script type = "text/javascript">
    var divState = {}
    function showHide(id) {
        if (document.getElementById) {
            var divid = document.getElementById(id);
            divState[id] = (divState[id]) ? false : true;

            for (var div in divState) {
                if (divState[div] && div !=id) {
                    document.getElementById(div).style.display = 'none';
                    divState[div] = false ;
                }
            }
            divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
        }
    }
</script>

Here is the HTML structure:

<div id="lob">
    <div id="auto">
        <img src="/intact/formindem/SiteAssets/LOB/Jeep_v2.png" alt="Experts auto"
            onmouseover="this.src='/intact/formindem/SiteAssets/LOB/Auto_TXT.png'"
            onmouseout="this.src='/intact/formindem/SiteAssets/LOB/Jeep_v2.png'"
            onclick="showHide('MSOZoneCell_WebPartWPQ3')"
            width="175px" />
    </div>

    <div id="habitation">
        <img src="/intact/formindem/SiteAssets/LOB/House_v4.png" alt="Experts habitation"
            onmouseover="this.src='/intact/formindem/SiteAssets/LOB/Habit_txt.png'"
            onmouseout="this.src='/intact/formindem/SiteAssets/LOB/House_v4.png'"
            onclick="showHide('MSOZoneCell_WebPartWPQ4')"
            width="175px" />
    </div>

    <div id="route">
        <img src="/intact/formindem/SiteAssets/LOB/Road_v1.png" alt="Experts route"
            onmouseover="this.src='/intact/formindem/SiteAssets/LOB/Route_TXT.png'"
            onmouseout="this.src='/intact/formindem/SiteAssets/LOB/Road_v1.png'"
            onclick="showHide('MSOZoneCell_WebPartWPQ5')"
            width="175px" />
    </div>

    <div id="tous">
        <img src="/intact/formindem/SiteAssets/LOB/All.png" alt="Tous les experts"
            onmouseover="this.src='/intact/formindem/SiteAssets/LOB/Tous_TXT.png'"
            onmouseout="this.src='/intact/formindem/SiteAssets/LOB/All.png'"
            onclick="showHide('MSOZoneCell_WebPartWPQ6')"
            width="175px" />
    </div>
</div>

Answer №1

Hello Fred,

After reviewing your approach, have you considered utilizing CSS instead of JavaScript for this task? CSS is designed for precisely this purpose, and while JavaScript can handle it as well, the process may become more intricate (and slower, particularly on sluggish mobile browsers).

For instance:

#route {
    background-image: url("your-image-here.png");
    background-size: contain;
}

#route:hover {
    background-image: url("your-mouseover-image-here.png");
}

Additionally, I find it peculiar that you desire different display properties when the container is set to display: block. What specific outcome are you aiming for with that adjustment? There is likely a more effective solution available to achieve the desired effect.

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

Align the body of the table with the header after populating the table with values

Issue : The data in the table body is misaligned with the headers of each column. Solution : var test_insert1 = '<tr>' + '<td class="td-trad-9">762261</td>' + '<td class="td-trad-7">1.16176&l ...

Best practices for referencing attributes created with the data method in a Vue component

In my application, there is a section that displays a list of users along with a search box to filter names. The user information is fetched from a database and stored in app.users. I have created a component named 'user' to show the details of e ...

Specify a preset selection time in a TextField of time type in Material UI

I am looking to establish a default time for a textfield of type time in Material UI. My requirement is that before the user clicks on the picker, no time should be pre-set, but once they click, 08:00 should appear as the default time to choose from. View ...

A guide on updating a JSON object based on specific criteria

I'm dealing with two JSON files here - the first one is named origin.json, and the second one is called newData.json. My goal is to update the child value of Origin based on the data in NewData. However, I only want this update to impact items that a ...

Tips for enabling scrolling on the correct floating menu when there is overflow

I have been attempting to make the right floating menu scroll when overflowing, but so far, I have been unsuccessful. Here is the link to the JSFiddle demonstrating the issue: https://jsfiddle.net/xuwtqmj3/. .menu { position: fixed; float: right; ...

Press the button to duplicate the cell column separated by commas

In my HTML table, there is a specific column filled with container numbers that I want to copy to the clipboard when a button is clicked. The column has the class ".container" Here is the code I have been working on. HTML: <button onclick="copyToC ...

What exactly is SproutCore and what makes it worth my attention?

After hearing the news that an individual has left Apple to focus on developing SproutCore, it appears to be another javascript framework in the mix. What makes SproutCore stand out and why is there so much buzz surrounding it? What unique features does ...

Ensure that only a single onmouseover event is triggered when hovering over multiple elements

I want to create a simple code snippet like the one below: <span onmouseover="alert('hi')">Hello, <span onmouseover="alert('hello')">this</span> is a test</span> However, I need to ensure that when hovering ove ...

Handling Mongoose Schemas and Database Conflicts in TypeScript

As a newcomer to MongoDB and Mongoose, I am facing a dilemma when it comes to sorting out conflicts between the schema and the database. Specifically, if I have an existing database in place and then decide to update the schema in my project by adding de ...

Having issues debugging in the browser as React seems to be undefined

I am trying to implement a Context system to store the login user's name and use it for protected routes. context.js import React from 'react'; const axios = require('axios'); export const AuthContext = React.createContext(null); ...

Is it possible to convert a leaflet marker into a nuxt-link function?

Recently, I started using nuxt and vue-leaflet to create an interactive map, even though I am quite new to it. This map consists of multiple markers representing different locations. The goal is for the respective page to open when a user clicks on a mark ...

Discover shared characteristics within nested arrays using MongoDB

Here is the schema I am working with: [{ "attributes":[ { "attrId":"123", "values":[ {"name": "asd"}, {"name" ...

When using JSX, it's important to wrap adjacent elements within an enclosing tag to avoid errors. Make sure to properly wrap the JSX tags to

import React, { useState } from 'react'; import ReactDOM from 'react-dom'; function DisplayData(props) { //creating the DataList const dataList = data.map(data => ( <><span>{data.name}</span> nbsp; <span> ...

I seem to be encountering an issue while looping through an array of objects. Instead of retrieving all two elements, only one object is being returned. Can

Just a heads up, I'm new to coding so please bear with me. I'm attempting to run through the "diary" array and the function "howMany" is only showing 2 'Home' elements, although there are actually 4 'Home' elements in total i ...

Utilizing knobs to dynamically incorporate components into templates on Storybook: A guide

I am a novice in the realm of storytelling, attempting to craft tales involving a basic button and a button adorned with icons. My objective is to have the ability to switch out the icons within the button utilizing the knobs section. For example: export c ...

Retrieve the list of users playing certain games using the start.gg API

Is there a way to retrieve all users from Smash Ultimate using the start.gg API? I couldn't find any information about fetching all users, only details about tournaments or specific player sets. You can access the API here: Thank you in advance for ...

tips for understanding the contents of the upcoming css class

I am working with a CSS class that looks like this: #menuAccordion h2 a,.dir-rtl #menuAccordion .viewList{ padding-right:2.5%; padding-left:0 } Is it correct to assume that for any HTML elements using the menuAccordion class, if there is an & ...

Extract information from a webpage and incorporate it into a PHP document

My goal is to develop a PHP page that extracts data from another webpage (e.g. ). By changing the "DisplayName" value, the displayed numbers change accordingly. Below is the code snippet from the webpage I am attempting to retrieve data from: 665249,1159 ...

The Vuex commit has exceeded the maximum calstack size limit

Currently facing an issue https://i.sstatic.net/l1WWH.png The error seems to be isolated to this specific section mounted() { this.$nextTick(() => { let ctx = this.$refs.canvas.getContext('2d') let { chartType, dataOptions ...

Reset additional javascript functions upon completion of loading a page using ajax pagination

Hi there! I'm completely new to this, and I need help with loading other plugins and allowing separate scripts to work after loading an ajax generated page. Here is my current code: jQuery(document).ready(function($) { var $mainContent = $("load-cont ...