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

Generate a unique ID each time the page is loaded or refreshed

I'm currently working on a function that will display a unique ID or a different video each time the page is loaded or refreshed. My main objective is to design a splash intro popup that features a <section> with a full-screen YouTube video bac ...

The <transition> element is not being recognized by VSCode

It seems like my VSCode is highlighting the transition element in red, indicating that it may not be recognizing this element. I'm a bit perplexed by what's happening here. Moreover, the code isn't functioning as expected because there is no ...

An issue related to AngularJS and the injection of ui-bootstrap components has been encountered

I'm encountering an issue with injection errors in my code, and unfortunately, the debugger in Firefox isn't providing much help. Here are snippets of the code: This is the Controller file causing the error: App.controller('ModalInstanceCt ...

Tips on how to lock the ag-grid to the highlighted row's position and force it to scroll

We have integrated ag-grid into our system, and I am facing an issue with displaying the scrollbar in a child window based on the selected row position in ag-grid. Please refer to the Plunkr link below and click on source_id which will lead you to an edit ...

Exploring the ways to access inner contents of a Div element using ajax

Looking to update the SQL database with a list of variables sent from an HTML page. Some data is being sent correctly, while others are not. The list is placed in a div divided into two parts: "h1" and another "div". The header data is being sent correctly ...

Leveraging the outcome of a Promise within webpack's configuration file

Currently, I am facing a challenge in accessing a Promise which is essentially an array of file paths created within recursive.js. This script navigates through my directories and organizes my stylesheets. The main issue arises when trying to utilize this ...

Disabling vertical scrollbar in textarea within Bootstrap modal using CSS, jQuery, and C# in .NET MVC framework

I am passing data to the Bootstrap modal using jQuery from my database. The form values can change from a single row to multiple rows. I do not want a scrollbar, but instead I want the textarea element to automatically adjust its height to fit the content. ...

Javascript continues to conceal my web background without my permission

After loading my webpage, I click on a link and the expected javascript runs as planned. However, once it completes and presents the results, the page goes blank to a white screen displaying only the outcomes. My goal is to have these results showcased o ...

You can click on the link within the Leaflet Popup to trigger JavaScript functionality

My leaflet map is functioning with GeoJSON polygons and popups attached to each one. These popups display information about the polygon. I want a link inside the popup that, when clicked, triggers a JavaScript function to retrieve and display smaller polyg ...

It is not possible for AngularJS to retrieve values using ng-model when ng-repeat is being used

Is there a way to capture dynamically generated data using ng-model (data created with ng-repeat) so that I can send it as an object to Firebase, my flat database? Currently, the ng-model is only retrieving empty strings as values. Any ideas for a solution ...

Locate the position of the cursor within a rectangular shape

I'm struggling to determine the location of a cursor within a rectangle, specifically which part (one of 4 triangles) it is in. This visual representation helps me grasp it better than any explanation I can come up with :s Working in javascript (whe ...

Is there a way to create a table with "cells that can be controlled individually" similar to the image provided using HTML and CSS?

I have been searching online for solutions on how to create a table similar to the one in this image, but so far I haven't had much luck. I attempted to use colspan, however, it didn't yield the results I was hoping for. Does anyone have any alt ...

Pause before proceeding to the next iteration in the loop

I am currently facing an issue while trying to send a message through an API using a function. The function returns a value called messageLogId, which I'm attempting to update in the main loop at Attendence. However, when executing the code, the value ...

Spring MVC: Incorporating Java Map into Optgroup Options

In my Spring MVC project, I am currently passing a Map from Java to my webpage using the variable "userLocales" through request.setAttribute('userLocales', bluh bluh bluh). I am looking for a way to extract the strings from this variable and use ...

Error: Unable to access 'target' property as it is undefined in React JS

I am currently working on capturing the value of a select tag that triggered an event, but I am encountering an issue when changing the tag. An error message pops up saying TypeError: Cannot read property 'target' of undefined. It seems to indica ...

Obtain asynchronous view model for component

Is it possible to retrieve a view model from the server and incorporate it into my component? I attempted to do so with the following code snippet, but it is not working as expected: function fetchViewModelFromServerAsync(){ setTimeout(function(){ ...

Placing a div over a JavaScript element

Is it feasible to overlay a div(1) with a background image on top of another div(2) that contains JavaScript (like Google maps API v3)? I have experimented with z-index without success, and I am unable to utilize absolute positioning because I depend on t ...

Guide on submitting a form via Ajax on a mobile app

Looking for a way to submit the form located in components/com_users/views/login/tmpl/default_login.php using Ajax. <form action="<?php echo JRoute::_('index.php?option=com_users&task=user.login'); ?>" method="post"> <fie ...

Incorporating a header include on every page throughout my website

Is there a way to include headers and footers in your HTML web pages without having to duplicate code on every page? I understand that this can be done using PHP, but what if you are creating a website solely with HTML? If there is no solution to avoid r ...

Retrieving information from a hyperlink or input field within a list using jQuery

I'm working with the following script : <script> $().ready(function(){ $('.request_list').click(function(){ requesting_dept = $('#requesting_department_name').val(); alert(requesting_dept); $. ...