Toggle the visibility of three different div elements using JavaScript on mouseover

Trying to create three image links that display different divs when onMouseOver.

<script type="text/javascript>
function toggleVisibility(divid) {
if (divid==="1"){
    document.getElementById("1b").style.visibility = "visible";
    document.getElementById("2b").style.visibility = "hidden";
    document.getElementById("3b").style.visibility = "hidden";
}
else if (divid==="2")
{
    document.getElementById("1b").style.visibility = "hidden";
    document.getElementById("2b").style.visibility = "visible";
    document.getElementById("3b").style.visibility = "hidden";
}
else if (divid==="3")
{
    document.getElementById("1b").style.visibility = "hidden";
    document.getElementById("2b").style.visibility = "hidden";
    document.getElementById("3b").style.visibility = "visible";
}
}
</script>

Apply these onMouseOver events to all three anchor tags.

onmouseover="toggleVisibility('1');"
onmouseover="toggleVisibility('2');"
onmouseover="toggleVisibility('3');"

However,

All three, when rolled over, only show 1a. No change occurs when the other two are hovered over and 2a + 3a remain invisible.

Thank you

HTML + CSS:

<div id="wrapper">
<div style="width:910px;height:300px;margin:0;padding:0;">
<div id="1b">&nbsp;</div>
<div id="2b">&nbsp;</div>
<div id="3b">&nbsp;</div>
<a href="#" onmouseover="toggleVisibility('1');" class="1"></a>
<a href="#" onmouseover="toggleVisibility('2');" class="2"></a>
<a href="#" onmouseover="toggleVisibility('3');" class="3"></a>
</div>
</div>

#wrapper {
width: 896px;
margin: 0px auto;
text-align: left;
overflow: hidden;
}

#1b {
width:303px;
height:150px;
visibility:hidden;
float:left;
background-color:#DED6C5;
}

.1 {
float:left;
height:130px;
width:303px;
display:block;
background-image:url('images/organizational.jpg');
}

I have renamed elements in this post to "1,2,3,1b,2b,3b" for clarity.

The CSS for the remaining elements is identical to 1 and 1b with just the names changed.

Answer №1

Your mistake lies in the condition you used.

When using if, valid operators include ||, &&, ==, ===, <, >, <=, and >=, but you mistakenly used =.

Make sure to use == and your code should function correctly.

UPDATE:

Jane Johnson provided an effective optimization suggestion for your code. Be sure to check it out!

Answer №2

Aside from the previous information on proper conditional formatting, I recommend optimizing your visibility toggle function to minimize repetitive code. This will make it easier to add more divs in the future if necessary. The following code snippet should meet your needs by iterating through the divs and applying a single conditional check to adjust visibility based on the passed-in number.

function updateVisibility(divId) {
    var index;
    for (index = 1; index < 4; index += 1) {
        if (divId === index) {
            document.getElementById(index + "b").style.visibility = "visible";
        } else {
            document.getElementById(index + "b").style.visibility = "hidden";
        }
    }
}

Feel free to give it a try!

Answer №3

If you’re willing to get creative and shift the links above the divs, it's entirely feasible to achieve a solution without using JavaScript.

For instance: http://jsfiddle.net/ABC123/

The idea is simple:

.org:hover ~ #orginfo {
     visibility: 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

Transitioning Opacity in CSS

I found inspiration for my project from the following source: https://codepen.io/plavookac/pen/qomrMw One challenge I'm facing is changing the opacity of the movement, which is not covered by the standard transition markers. .mainInner{ display ...

Encountering a CORS policy error in Three.js when attempting to run locally

I'm just starting out on this website and I'm eager to dive into learning javascript. My initial attempt at following this example from resulted in an error without any animation or background showing up. Instead, all I see is a photo displayin ...

Trouble with Bootstrap accordion staying open even after a different one is chosen

Looking for assistance! I am encountering an issue with using jQuery on Bootstrap. The accordion feature is not functioning correctly as it fails to collapse when another section is selected. https://i.stack.imgur.com/uiZPh.png The problem arises when th ...

Retrieve information from a MySQL database and integrate it into a different application

This php script is used to generate a table with a "book" button next to each row. The goal is to extract the values of "phase" and "site" from the specific row where the "book" button is clicked, and transfer them to another form (in "restricted.php") fo ...

Adjust the CSS of the currently dragged item using jQuery sortable

I am currently using jQuery-ui sortable and facing an issue with changing the appearance of a dragged item. I would like the text value of the component inside the red background container to be displayed while dragging. Can someone please assist me with t ...

Is there a way to immobilize an object in JavaScript without resorting to Object.freeze()?

Is there a way to freeze the following object without relying on Object.freeze()? Let's find out: const obj = { a:'test', b:'Something' } ...

Change the input value by clicking different buttons

Looking for a way to change the value or source of an input when clicking on different buttons? For example, clicking on Button 1 changes the input to "apple" and Button 2 changes it to "orange", etc. Here is a snippet of what I have tried so far: $(doc ...

Avoid having logs displayed on the server end when utilizing console.log commands

Being new to JavaScript and Node.js, I am attempting to have my application output logs on the server side. getUser.onclick = function () { console.log('Server running at http://127.0.0.1:1337/'); var req = new XMLHttpRequest(); r ...

Troubleshooting navigation problems in AngularJS Bootstrap Navbar

Currently, I am working on integrating AngularJS with Bootstrap3 for a mobile application. In my index.html file, I have added a navbar (navbar-fixed-top) and there are forms loaded through partials/myform.html. However, when I scroll the page and a textbo ...

What is the preferred default value for a property awaiting assignment from a GET response: Undefined or Null?

Say I need to display information about a product, but first I must make a GET request to get the data and assign it to the product. I'm wondering, should the default value for product in the data() function be undefined or null, and is there a differ ...

Expanding the width of three floating divs in the center to match the width of the parent container div

In my design, I have a parent container with three inner divs that are floated. The left and right divs have fixed sizes, however, I need the center div to expand and fill the space available within the parent container. <div class="parent-container"&g ...

Using JavaScript to add a JSON string from a POST request to an already existing JSON file

I am currently working on a basic express application that receives a post request containing JSON data. My goal is to take this data and add it to an existing JSON file, if one already exists. The key value pairs in the incoming JSON may differ from those ...

Loading images in advance using jCarousel

I need help with preloading images on a jCarousel that loads a JSON feed and generates necessary HTML. Can anyone suggest a way to accomplish this task efficiently? $(".banner ul").jcarousel({ itemLoadCallback:loadTopBanner, auto: 6, wrap: ...

Adjusting elements within nested JavaScript arrays

When using the code below, an empty array containing 7 empty arrays is expected to be created, essentially forming a 7x7 grid. While accessing elements within nested arrays seems to work correctly, attempting to modify their values causes all elements in ...

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

Transform a two-element array into a single key/value pair JavaScript object

Looking to convert the array ["description", "asc"] into an object like this: { "description": "asc" } Any ideas on how to achieve this quickly? My attempt: const obj = { array[0] : array[1] } Struggling to dyna ...

Show the response obtained after making a POST request

In my current project, I am utilizing vanilla JavaScript to send a POST request to my Flask App. I have implemented a validation feature that checks for duplicate usernames when a user is signing up. If the username already exists, a 406 status response is ...

Activate a function in Jquery after iterating through all elements in a JSON file

Below is the code I am using to ping a list of computers with Jquery and asp.net. function ping() { $('#progress').css("display", ""); $('.comp').each(function () { var $computer = $ ...

Determine whether the response originates from Express or Fastify

Is there a method to identify whether the "res" object in NodeJS, built with Javascript, corresponds to an Express or Fastify response? ...

The FOSJsRoutingBundle is unable to detect a route coming from the FOSRESTBundle

I am facing an issue with accessing an API route to a FOSRESTBundle Controller from my JS. Even though I am using the FOSJSRoutingBundle, the route is not visible, and I keep getting the 'the route xxx does not exist' error. The following is an ...