How can I retrieve the current background color and revert it back after a .hover event?

I am trying to use the .hover function to change the background color of a menu. Each menu item has a different background color, so I want it to return to its original color when the user hovers off. In other words, I want the script to read the current background color and then reset it after the hover.

However, the code below is not working as expected. I'm struggling to figure out how to pass the variable for background-color in the second part of the hover script:

$('#dmenu ul li a').hover(
  function () {
    var bgOn = $(this).css('background-color');
    $(this).css('background-color', '#efefef');
}, 
  function () {
    $(this).css('background-color', (bgOn);
}
);

I admit that I'm not very experienced with JQuery, so I'm sure it's just a simple fix. Any help would be greatly appreciated. Thanks!

Answer №1

Give this a shot:

let backgroundColor;
$('.menu ul li a').hover(
  function () {
    backgroundColor = $(this).css('background-color');
    $(this).css('background-color', '#efefef');
}, 
  function () {
    $(this).css('background-color', backgroundColor);
}
);

In the provided code snippet, backgroundColor is within scope.

Answer №2

Consider implementing a similar solution like this one, where a data-background-color-orig attribute is set on hover to store the original background color. Then, a callback function can be used to restore the original background color using that attribute.

Check out this example on JSFiddle for reference.

I have utilized a comparable method in the past when dealing with dynamically generated background colors for an element, especially when inline hover styles were not supported.

Here's some relevant JavaScript code:

$('#dmenu ul li a').hover( function() {
    $(this).attr('data-background-color-orig', $(this).css('background-color'));
    $(this).css('background-color', '#EFEFEF');
}, function() {
    $(this).css('background-color', $(this).attr('data-background-color-orig'));
});

Answer №3

Experiment with mouseenter and mouseleave functions to alter the background hues.

Another option is to utilize CSS similar to the example below:

ul li a:hover
{
    //define background color
}

Answer №4

Utilizing CSS is the way to achieve this.

See an example on jsfiddle

Below is the HTML code:

<ul id="menu">
    <li><a id="home" href="#">Home</a></li>
    <li><a id="products" href="#">Products</a></li>
    <li><a id="services" href="#">Services</a></li>
    <li><a id="about" href="#">About</a></li>
</ul>

This is the CSS code:

#menu {margin:0;padding:0;font-family:Helvetica,Arial,sans-serif;font-size:16px;color:#fff;text-shadow:1px 1px 2px #888}
#menu li {float:left;}
#menu a {display:block;padding:15px 35px;color:#fff}
#menu a:hover {background-color:#efefef;color:#888;text-shadow:1px 1px 2px #fff}
#home {background-color:red;}
#products {background-color:orange;}
#services {background-color:green;}
#about {background-color:blue;}

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

What is the best way to have dual backgrounds displayed on a single webpage?

Looking to recreate the background design featured on this website: www.zucoffee.com. Does anyone have any tips? In addition, I'm curious about how to achieve that curved separation effect. I understand it involves two divs, but how did they manage t ...

Is it possible to programmatically set focus on a DOM element using JavaScript or jQuery?

My code dynamically loads select boxes based on user selections. I have a specific instruction to select an option, which looks like this: //returns a string of <option>s by ID $('#subtopic_id').load('ajax.php?f=newSubtopic&am ...

What is the best way to have rails ajax register when a date has been modified and display that change on the webpage?

There is a link present. %a{href: "#", :data => {verifying_link: 'yes', id: link.id, table_row: index}} verify_by_js This link triggers the following: $(function(){ $("a[data-verifying-link]='yes'").click(function(){ // sp ...

Can someone please provide guidance on how to focus on these boxes? (see image below)

My goal is to specifically target the boxes with white dots inside them. Each black box in this picture represents a blog post, even including the larger one at the top. I initially considered using the nth-child selector, but I'm not confident in how ...

Despite my server responding with a status code of 200, my Ajax POST request is still displaying an error. Strange

When making an AJAX post to a Jersey Resource and returning an image, I encounter an issue where no matter what status code I return, Ajax interprets it as an error. Despite this, I can still utilize the error message (through error.responseText) and it fu ...

How to make a letter stretch all the way down the paper?

As I'm creating a table of contents for my website, I was inspired by an interesting design idea that I came across: I am particularly drawn to how the T extends down and each section is numbered with the title wrapped around it. How can I achieve th ...

jQuery allows us to set two separate conditions for two distinct variables

I've written this function: settings_rc_left.on('click', function(){ var settings_list_last_element_id_one = settings_menu_element.attr('id') == 'r_02', settings_list_last_element_id_two = settings_menu_eleme ...

Using Express, Node, and JQuery to handle form submissions

I am struggling with form submissions while working on a web app using HTML, Express, and Node.js. Despite being new to these technologies, I have created a script that generates a dynamic form based on certain factors: $FormContainer.html(''); ...

Revamping Footer Text

Hey there, I'm feeling a bit inexperienced with this question, so after struggling on my own for a while I decided to turn to stackoverflow for help. So, I have a website located at , and at the very bottom of the page there's some copyright inf ...

Updating a database using the $json_encode() PHP Function: A Step-by-Step Guide

Looking to enhance my database using a combination of jQuery, PHP, and Ajax with json_encode and Ajax Post. However, I'm struggling with understanding how to utilize an array $json_encode to update the database with a foreach loop. How can I achieve t ...

Retrieving, storing, and implementing the classes of child elements directly from an array using jQuery

With the help of jQuery, you can retrieve child elements of the #parent element that have the class .west. In this case, we are not interested in fetching the content of these child elements but instead their class names. For example: <div id="parent" ...

Parsing JSON data received from Angular using JSP

As I navigate through my Angular application, I'm encountering a challenge when trying to save data on the server side using JSP. The issue arises when Angular's $save method sends the object data in a JSON format that is not familiar to me. This ...

Is there a way for me to determine the size of this JSON structure?

Can anyone help me figure out the length of this JSON object? I need to know how many data are in it. var ddData = [{ "01":"United States", "02":"United Kingdom", "03":"Aruba", "04":"United Kingdom", ...

Utilize Ajax datatable to showcase information in a visually interactive format

I've been grappling with this problem for an entire day. Essentially, I have a table and I need to pass data in a multidimensional array $list through a datatable using AJAX. This way, I can JSON encode it and send it back for display: $('#table ...

Jquery error - parser issue - JSON input unexpectedly terminated

I am facing an issue with retrieving information from my database and displaying it in a table using JQuery. Previously, I was able to do this successfully with the same code, but now it seems to be malfunctioning. Despite researching various resources for ...

Adjusting the Underline Navigation Effect with jQuery

My current setup includes a basic navbar with an up arrow that slides underneath it when a navigation title is clicked. The arrow initially rests between two nav titles, and when one of them is clicked, some text also slides in. I am looking to implement ...

The nb-install mixin is not recognized

While working with angular5, I encountered the 'No mixin named nb-install' error when running npm start or serve Module build failed: undefined ^ No mixin named nb-install Backtrace: stdin:13 in E:\mrb_bugfixes& ...

"What are some best practices for utilizing the $.ajax method in conjunction with the

Utilizing AJAX, I send data to my Apache/PHP webserver (XAMPP). The shorthand syntax $.post works perfectly fine for me. Here is the code snippet: return $.post('http://localhost:8099/login.php', { loginDataInput : loginDataInput }).th ...

Search for documents using jQuery on the page

Here is the layout of a page: HTML <div class="alert alert-dismissable"> <div class="form-group text-center"> <div id="Section"> <div class="row"> <div class="col-md-12"> ...

Modify the color of the select element when it is in an open state

If you're new to Material UI, I have a select element that I would like to change the color of. When 'None' is selected, I want the background color of the input field above it to match the 'None' section. Then, when the dropdown m ...