Is there a way to disable a JavaScript hover effect when the mouse moves away?

I came across this JavaScript code that swaps the background of a parent div when clicking on a link in a child div. However, I noticed that the hover state remains even after moving the mouse out of the link. Can someone help me modify the code so that the parent div's background returns to its original state after moving the mouse out of the link? Thank you in advance.

    $('.background-changer').on('mouseover', 'a', function () {

    var background = "url('" + $(this).attr('data-background') + "')";

    $('.background-changer').css('background-image', background)
});

}); 


    <div id="navBar" style="background: url(images/navigation-background-0.gif);" class="background-changer">
                <div id="navBarCell1"><a href="#" title="Resort" target="_parent" data-background="images/navigation-background-1.gif">Resort</a></div>
</div>

#navBar {
    height: 38px;
    width: 760px;
    float: right;
    background-repeat: no-repeat;
}
#navBarCell1 {
    float: left;
    width: 75px;
    text-align: center;
    height: 26px;
    overflow: hidden;
    margin: 0px;
    padding-top: 9px;
    padding-right: 0px;
    padding-bottom: 0px;
    padding-left: 0px;
}
#navBarCell1 a:link {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 10px;
    text-transform: lowercase;
    color: #000;
    text-align: center;
    text-decoration: none;
    padding: 20px;
    margin-top: 10px;
}

Answer №1

To retain your current settings, you can enhance it by adding a data attribute to the parent div with the existing background URL before applying the new link. Afterwards, trigger a mouseout event to restore the original background image like this:

var bgChanger = $('.background-changer');
bgChanger.on('mouseenter', 'a', function () {
var background = "url('" + $(this).attr('data-background') + "')";

bgChanger.data('original-background', bgChanger.css('background-image')).css('background-image', background);
}

bgChanger.on('mouseout', function(){
  bgChanger.css('background-image', bgChanger.data('originalBackground'));
});

This code snippet has not been tested yet, but it is expected to function correctly.

Answer №2

For those who require JavaScript to achieve this effect, a hover function can be utilized as shown below:

Check out this Working Example

$('#navBar').hover(function () {
    $('#navBar').css({
        'backgroundImage': 'url( --- )' // image 2
    });
},
function () {
    $('#navBar').css({
        'backgroundImage': 'url( --- )' // image 1
    });
});

Explore .hover() in the official API documentation

However, according to SLaks' suggestion in the comments, it might be more efficient to utilize CSS :hover for this purpose:

View Working Example 2 here

#navBar {
    height: 38px;
    width: 100%;
    background-image: url( --- ); /* image 1 */
    background-size:20px;
}
#navBar:hover{
    background-image: url( --- ); /* image 2 */
}

Learn more about using :hover in the MDN documentation

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

Unable to adjust dimensions with CSS width and height properties

I'm currently working on developing an online game with a login screen inspired by Paper.io. I have created the username input and play button, but there seems to be an issue with the width and height specified in the CSS file for the input field. Eve ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...

Use the zoom feature on D3 to enhance two graphs in an HTML document

I have been experimenting with d3 libraries lately and came across http://bl.ocks.org/jroetman/9b4c0599a4996edef0ab. I successfully used it to draw a graph based on data from a tsv file and enable zoom in and out functionality, which worked well for me. Ho ...

Steps for initiating a $.ajax POST request from a client to a server

Currently, I am working on a phonegap application where I need to transfer some data from an HTML file to a server and receive a response in return. Everything works fine when all the files are on the same server. However, once I separate the files between ...

What is the method for transforming a JavaScript array (without an object name) into JSON format (with an object name)?

Currently, I am using an ajax query to read a local csv file and then loading the extracted values into an array. This is how the string value appears in the csv file: "Tiger","Architect","800","DRP","5421" ...

Would it be beneficial to assign a single class name to all elements with matching styles within a CSS framework?

Currently, I am in the process of creating my own CSS library or framework. However, I have encountered an issue where all 10 li tags share the same classes, such as .pl{ padding-left:10px} .mr{ margin-right:10px}, along with other necessary attributes. Wh ...

Saving a variable's value using Knockout loop within an HTML document

As a newcomer to KO, I have been utilizing the following code in my HTML file to print a specific value: <!-- ko foreach: { data: JSON.parse($parent.options), as: 'option' } --> <!-- ko if: option.label === 'AAA' || option. ...

Tabindex issue arises due to a conflict between Alertify and Bootstrap 4 modal

When trying to call an Alertify Confirmation dialog within a running Bootstrap 4 Modal, I encountered an issue with the tab focus. It seems to be stuck in the last element and not working as expected. I suspect that this might have something to do with th ...

Remove all spaces from input fields in angular Typescript, excluding the enter key

I've encountered an issue where the code below removes all spaces, but it's also removing the enter key. Is there a way to remove only spaces and not affect the enter key? static stripDoubleSpaces(str: string): string { if (!!str) { ...

Difficulty Encountered when Using Colorbox in Internet Explorer (all iterations)

I've been struggling to get Colorbox working properly on this particular page, even after spending more time than anticipated. The link to the page has been removed for privacy reasons. There's a Colorbox test link at the bottom right corner tha ...

Storing JWT API tokens in a secure location

Currently, I am in the process of developing the API portion for an application and focusing on implementing JWT authentication. At this point, I am generating a token and sending it back to the front-end as part of a JSON object when a user is created. Ho ...

Integrating Livefyre npm with Meteor

Currently, I am in the process of creating a custom package to integrate the livefyre npm module into Meteor after receiving a request from a client. Despite following the instructions provided here, I keep encountering errors that state Errors while scann ...

Using AngularJS to pass objects dynamically through ng-include

Below is an example that is fully functional, except for one issue. When using node.title within the HTML code, everything works as expected. However, when trying to use {{node.title}} within the ng-include file, it does not function properly. Only the g ...

Issue: The variable does not appear to be getting updated

After spending the last 2 hours analyzing this JS code, I am still unable to figure out why the variable "message" is not being changed to "User already exists." The bizarre thing is that the code block labeled "Inside first if" is executed, but the "mes ...

Steps for resolving the "endless redirection loop" issue in Sharepoint

I am currently learning Javascript and working on setting up a multi-language Sharepoint site. I am trying to implement a code into each page that checks the user's email and the language in the URL (Portuguese or Spanish) and then redirects according ...

I'm having trouble getting this text to align properly next to the image. Plus, I can't seem to achieve a horizontal screen alignment either

There seems to be an answer available, but I'm clearly not understanding it, so I've come here seeking further explanation and assistance. CSS can be quite complex, right? Here's a screenshot of my current project: https://i.stack.imgur.com/ ...

Can a variable be initialized with a concealed or additional argument?

After just 2 weeks of coding, I'm struggling to find information on how to initialize a variable with an extra argument in a recursive function call. Is this even possible? And if it is, are there any scenarios where it's considered best practice ...

Bringing in Chai with Typescript

Currently attempting to incorporate chai into my typescript project. The javascript example for Chai is as follows: var should = require('chai').should(); I have downloaded the type definition using the command: tsd install chai After refere ...

Facing an obstacle in Angular as I am unable to view my data

How can I bind the model of my controller in the init function and see the data when the init is called? Index.html <!DOCTYPE html> <html ng-app="I-Sign"> <head> <meta http-equiv='X-UA-Compatible' content='IE=edge&apo ...

changing html numbered list to xml format

Looking to convert HTML ordered lists with different types into XML markup? <ol type=a> <li>This is list item a</li> <li>this is list item b</li> </ol> <ol type=i> <li>This is list item 1</ ...