Guide to switching between 3 classes with mouseover using JavaScript

Currently, I am dealing with an unordered list that contains 4 items. The goal is to have the list grow to 100% of its width when hovered over, while all 'noun hovered li' items should shrink to a width of 0%. Once the cursor leaves, everything should revert back to their original state of 25% width. Here's a similar setup:

<ul id="menu2">
  <li class="color"></li>
  <li class="color"></li>
  <li class="color"></li>
  <li class="color"></li>
</ul>

CSS styling:

#menu2{
overflow: hidden;
padding-left: 0;
padding-right: 0;
margin: 0;
}
.color{
display: inline-block;
position: relative;
list-style: none;
float: left;
height: 110px;
margin-right: 0;
width: 25%;
background-color: blue;
cursor: pointer;
}

.stateHovered{
    width: 100%;
    transition: all 500ms ease-out;
    background-color: #FAA500;
}
.stateOff{
    width: 0;
}

Javascript functionality:

function addListeners(){
document.getElementById('menu2').children.addEventListener("mouseover", toggleClassFunction);
    function toggleClassFunction() {
        for(i = 0; i < menu2.length; i++) {
            if(menu2[i] !=this) {
                menu2[i].className = "stateOff";
            }else if(menu2[i] === this){
                menu2[i].className = "stateHovered";
            }else {
                menu2[i].className = "color";
                }
        }
    }   
}
window.addEventListener("load", addListeners);

Unfortunately, the end result doesn't seem to be functioning correctly...

Answer №1

When the mouse hovers over, switch the classes to "stateOff" or "stateHovered" accordingly. Upon hovering out, revert them back to "color". Utilizing jQuery simplifies this process, although tweaking the CSS may be necessary:

$(document).ready(function(){
    $('#menu2 li').mouseover(function(){
        //Rather than distinguishing between elements, set all to "stateOff"
        $('#menu2 li').attr('class','stateOff');
      
        //Then assign this element to "stateHovered".
        $(this).attr('class','stateHovered');
      
        //The changes won't display until script execution completes,
        //Avoiding abrupt style switches.
    });
    
    
    $('#menu2 li').mouseout(function(){
        $('#menu2 li').attr('class','color');
    });
});
menu2{
overflow: hidden;
padding-left: 0;
padding-right: 0;
margin: 0;
}
.color{
display: inline-block;
position: relative;
list-style: none;
float: left;
height: 110px;
margin-right: 0;
width: 25%;
background-color: blue;
cursor: pointer;
}

.stateHovered{
    width: 100%;
    transition: all 500ms ease-out;
    background-color: #FAA500;
}
.stateOff{
    width: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu2">
  <li class="color">A</li>
  <li class="color">B</li>
  <li class="color">C</li>
  <li class="color">D</li>
</ul>

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 customizing the appearance of the react-stripe-checkout form

Could someone please provide guidance on applying custom styles to the react-stripe-checkout form component, such as changing the background color? Visit this link for more information ...

JavaScript-enhanced HTML form validation

I encountered a small glitch while working on simple form validation with JavaScript. I tried to catch the issue but have been unable to do so. Here is the code snippet, where the problem lies in the fact that the select list does not get validated and I ...

Pretending to determine the exact height of the body

I am facing a challenge with my JavaScript application that is loaded within an iframe through a Liferay portlet. The HTML container is currently empty and the JS is loaded only when the document is fully loaded. Upon loading the page in the iframe, Lifer ...

Uncertainty surrounding the concept of JavaScript objects

What is the reason for this not functioning properly? function displayValue(a,b){ this.a = a; this.b = b; $('p').text(a + " " + b); } var display = new displayValue(); display('1','2'); How does this still work ...

IE 11 does not support the use of absolute positioning with a height of 100%, however, this functionality works perfectly on Microsoft Edge

It appears that in IE 11, my absolutely positioned element is not displaying within another element with a height:100%. Strangely, it only works if I assign a fixed height to the element (even though its parent has a fixed height). Here is the HTML code: ...

v-autocomplete not displaying full list of items in selection dropdown

I have a question regarding sending an array with values ranging from 1 to 100 on the v-autocomplete item props. However, when scrolling through the list, only numbers up to 40-50 are visible. <template> <v-app> <v-container> ...

HapiJS commences an extended duration background process

Is there a way to achieve the functionality of a PHP exec function in HapiJS? I have a scenario where the user submits a processing job that requires running in the background for a significant amount of time. An essential requirement is to provide the us ...

Ways to display the ChaptersButton in Videojs-Player

I'm trying to incorporate videojs (version 8.10.0) into my project and provide viewers with a way to select chapters within the video. According to the official documentation, it seems that simply including a track element linking to a VTT file within ...

Instructions for accessing and printing text from a nested ul tag with Selenium in Java

Hello everyone, I am currently learning about Selenium Automation and have created a website as shown below. Here is the HTML code: <!DOCTYPE html> <html> <head><title>Shop</title></head> <body> <ul> < ...

Aligning the last element within a list

I'm having a major issue with this code. Despite reading all related posts, I still can't get it to work. Seems like I might be missing something obvious. LOL. Here is the site (best viewed in Chrome): and here is what I believe is the simplifi ...

Tips for including an additional label on a data point within a scatter plot using the Highcharts JavaScript framework

Incorporating the Highcharts JavaScript library, I am visualizing float values by passing them from PHP to the JS code. In the image below, you can observe that upon hovering over each point, the corresponding axes values are displayed along with the text ...

Echo command fails to work with location.href

I am facing a small issue with my PHP echo. I have a JavaScript link function that is not working because the HTML code shows this type of link onclick="location.href="http://www.link.com/";". It's clear that this syntax won't work. However, if w ...

Tips for effectively using the parseInt function to access and verify a span element from inside a chrome extension

Trying to utilize parseInt to ascertain if a span element is greater than or equal to 1 within my Google Chrome Extension. Attempting to monitor this "0" for changes and trigger a specific URL upon change - Refer to the Image View of the "inspect" option ...

Issue with Promise.all not waiting for Promise to resolve

After making a request to the server, I receive the data as a promise, which contains the correct information. However, for some reason, the program fails to execute properly. Prior to uploading it on Zeit, this program was functioning correctly. Fetch R ...

A guide on implementing listings in React Native through the use of loops

I am trying to display the data retrieved from an API, but I am encountering an error. // Retrieving the data. componentWillMount() { tokenner() .then(responseJson => { const token = "Bearer " + responseJson.result.token; ...

The Splitter remains inactive until a peculiar series of actions is taken

Trying to troubleshoot this issue with a library called Split.js, which can be found here: https://github.com/nathancahill/Split.js I've encountered an interesting problem where I have to disable the height CSS property of my container, move the spli ...

Validating JSON against a JSON schema using JavaScript

My current task involves validating approximately 100 JSON Objects against a specific JSON schema to ensure that all fields and their types align with the schema requirements. Initially, I attempted to use a JSON schema generated from a website. However, ...

Issue with strange symbols appearing in Safari on Mac

Hey there! I have this website built with asp.net and I have a text-box for filling in quantities. Sometimes, I notice this strange icon that looks like a human appearing on the text box. It only seems to show up when using Mac Safari browser. Check out th ...

Utilizing jQuery to add elements to a webpage

I need to populate an empty div on my webpage using jQuery. Here's an example: <div class="content"> </div> After the first insertion, I want the markup to look like this: <div class="content"> <div class="inserted first"& ...

Adjust the background color of child divs when the parent div is being hovered over

I am facing a challenge with my current setup: <div class="parent"> <div class="child"> </div> <div class="child"> </div> <div class="child"> </div> </div> My goal is to change the background co ...