Difficulty in smoothly changing background image using JQuery

Update

After some troubleshooting, I realized that the background image was indeed fading out. The issue was that the background image was being removed before the fade effect could be seen. By removing .css('background',''), I was able to achieve the desired fade out effect. However, despite this fix, some of my CSS styles were still not affecting the element. It seems that a background-repeat: initial; property was overriding the class styles. Could this be due to JavaScript manipulation?


New:

I have gone through several similar questions here, and while they have helped me make progress, I am still struggling to find a solution.

The problem I am facing involves fading background images on hover. I am using jQuery to set the background of a div to an image URL stored as a data attribute in a list of links when hovering over the link.

I have managed to assign the background image and add a class to make it visible. The fading effect works when transitioning in, but not when transitioning out. Manually removing the visibility class in Chrome Dev Tools results in the expected fade out effect, but the same is not achieved when done via jQuery. Additionally, other "background-" CSS styles do not seem to work unless I use !important. I am unable to determine what is causing these overrides.

JSFiddle

HTML

<div class="backdrop"></div>
<ul>
    <li><a href="#" class="item" data-img="http://goo.gl/hbKhMi">one</a></li>
    <li><a href="#" class="item" data-img="http://goo.gl/7p0Kki">two</a></li>
    <li><a href="#" class="item" data-img="http://goo.gl/EHW4Xs">three</a></li>
</ul>

CSS

.backdrop {
    width:450px;
    height:400px;
    opacity: 0;
    -webkit-transition: opacity 0.75s;
    transition: opacity 0.75s;
    background-position:center;
    background-repeat: no-repeat;
}

.visable{
      opacity:1;
}

JS

$(document).ready(function() {
    $('.item').mouseenter(function() {
        $('.backdrop').css('background','url('+$(this).data("img")+')').addClass('visable');
    });
    $('.item').mouseleave(function() {
        $('.backdrop').css('background', '').removeClass('visable');
    });
});

Answer №1

Your JavaScript code needs a slight adjustment. Instead of using background, switch to using backgroundImage to set the images. Also, when handling the mouseleave event, only remove the class rather than the backgroundImage. Update your code as follows:

$(document).ready(function() {
    $('.item').mouseenter(function() {
        $('.backdrop').css('backgroundImage','url('+$(this).data("img")+')').addClass('visible');
    });
    $('.item').mouseleave(function() {
        $('.backdrop').removeClass('visible');
    });
});

Check out the updated code on FIDDLE: https://jsfiddle.net/lmgonzalves/y2v9sa4h/8/

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

Enhance the connectivity of Angular js by activating the link function post transclusion

I am facing an issue with Angular where I have two directives that need to be transcluded within each other. However, I am unable to access the DOM using a simple JQuery selector after the transclude function has been executed. Specifically, I need to comp ...

Ensure equal width for an HTML element by matching it with the dimensions

Hello, I am facing an issue with a dropdown button. Whenever I hover over it, the links to different pages drop down. However, I want the width of these links to be the same as that of the button. The size of the button varies as it is set to 100% width o ...

Utilizing React with file system and path dependent packages

Is there a way to utilize the quick.db package in my ReactAPP with hooks, even though React does not allow the use of FS & Path which are required for this package? I am encountering the following errors: ERROR in ./node_modules/file-uri-to-path/index.js ...

Database stores line breaks in a structured format

As I work on creating a posts section for my readers, I have encountered an issue. When a user adds a new post, it gets saved into the database in this format: Some say the world will end in fire,<br /> Some say in ice.<br /> From what I’ve ...

My webpage's `div` element is not loading properly when using the `.click(function()`, but magically works

Personal Website Issue Encountering a problem with a hidden div not fully loading when triggered by an .click(function(). After researching the issue and attempting both $(document).ready(function() and window.onload, my problem persists. IMPORTANT: The ...

Divide a PDF document into individual files using QR code identifiers

I need assistance with organizing a scanned pdf that includes multiple answer scripts from students for a specific exam. Each student's answer script ends with a qrcode that serves as a unique identifier for the student. Is there a way to divide the ...

When I'm working on iPhone css hover effects, I find that I need to include a

Why do I have to add a touch event to my element in order for it to trigger hover styles? Is this typical behavior? It seems a bit unconventional. This is the code I need to include to make :hover work; without it, no hover style is applied. Apologies f ...

Stop Bootstrap 5 Accordion from collapsing

I have successfully implemented the Accordion component in Bootstrap 5, and it is working perfectly! However, I am facing an issue with the size of the collapse button in the accordion, which is too big. I want to add an additional link to it for some ext ...

Ways to create a scrollable div with the help of Javascript

I am currently developing a web app on the Tizen platform. Within my HTML5 code, I have a div element with an image set as its background. In certain scenarios, I need to display random text within this div multiple times. The text can vary in size and ma ...

Employ the setInterval function to run a task every 15 minutes for a total of

I have a task that requires me to use setInterval function 5 times every 15 minutes, totaling one hour of work. Each value retrieved needs to be displayed in an HTML table. Below is the table: enter image description here For example, if it is 7:58 p.m. ...

Utilizing personalized markers to encapsulate correct HTML elements

Recently, I came across a discussion on the implications of using custom tags in HTML. After reading about it, I have decided to avoid using custom tags in order to adhere to standards and ensure that search engine bots can properly read my code. However, ...

Discovering identical objects by property and combining them with the help of JavaScript or UnderscoreJS

Below is an array that I have: var somevalue = [{ code: 1, name: 'a1' }, { code: 2, name: 'b1' }, { code: 1, name: 'a2' }, { code: 1, name: 'a3' }, { code: 2, name ...

Creating a customized CSS selector to pinpoint distinct values among numerous elements sharing a common name

There are 6 buttons on the page layout, all named "Add content" and belonging to the class "addContent". In order to perform separate tasks, I need to click on each button one at a time using Webdriver. The buttons are nested deep within div's that ha ...

What is the best way to adjust the footer width to match the sidebar using Bootstrap 5?

Currently working on a Bootstrap 5 template for my website, but being new to it makes it a bit challenging. Specifically struggling with aligning the footer to fit the full width of the sidebar. <!DOCTYPE html> <html lang="en"> <head&g ...

What is the best way to display a particular JavaScript variable in an HTML document?

Is there a way to display the value of a Javascript variable in an HTML form, such as showing it on the screen? Below is my JavaScript code: <script type="text/javascript"> var howLongIsThis = myPlayer.duration(); </script> The variable howL ...

The issue is that the Push() function is not functioning properly when it is invoked from within

I am currently incorporating the jQuery drag and drop formbuilder plugin into my project. My goal now is to retrieve drag and drop elements from my database and integrate them into the drag and drop builder. Here is the function I am using for this reques ...

Warning: React Element creation caution with flow-router integration

Whenever I incorporate the following code into my Meteor app: Home = FlowRouter.route("/", { name: "App", action(params) { ReactLayout.render(App); } }); An error message pops up in the Chrome console: Warning: React.createElement: type shoul ...

Error: React.js - operationStore.getItems function is not defined

I've encountered an issue while running my Web App with the command: node --harmony gulpfile.babel The error message states: Uncaught TypeError: operationStore.getItems is not a function I'm struggling to identify the root cause of this problem ...

Custom sized box causing Bootstrap Navbar to be unresponsive

I am having trouble loading the Bootstrap 3 navbar inside a .box class with specific CSS rules: .box { height: 600px; width: 320px; position: relative; border: 2px solid #eee; } Unfortunately, it is not displaying re ...

Transformation of Object into Number through Function Execution in Javascript

I am currently facing an issue with my animate() function while using Three.js to generate an animation. Below is a simplified version of the code: let obj; let camera = new THREE.PerspectiveCamera(fov, asp, near, far); let scene = new THREE.Scene(); const ...