Seamless transition of background images with Javascript

(>> For best viewing experience, please use a screen size of at least 15 inches as the site is not fully responsive yet)

Hovering over the buttons (moon, planet, etc...) causes the background to change. However, there are issues with the transition on Chrome (image0 > blank > image1). It works smoothly on IE11 but may have occasional lag. I haven't tested it on other browsers.

How can we achieve a smoother transition? We need a quick fade from Image0 to image1, without any intermediate color transitions.

Below is the code for the MOON button, which is similar to the others. (I'm not familiar with Javascript and found the following script on Stackoverflow.)

HTML

<div class="top-logos-home" id="top-logos-moon-front"><img src="moon-logo.png" alt="MOON"></div>

CSS

.image-home {
     position: absolute;
     width: 100%;
     height: 100%;
     background-image: url(Frontpage.jpg);
     background-size: cover;
     display:inline;
     top:0;
}

JAVASCRIPT

jQuery(function(){
    var $body = $('.image-home');
    $('#top-logos-moon-front').hover(function(){
        $body.css('background-image', 'url("Frontpage-moon.jpg")')
    }, function() {
        $body.css('background-image', '')
    })
})

Answer ā„–1

If you're looking to achieve a smooth transition, the key lies in updating your script code.

jQuery(function(){
    var $body = $('.image-home');
    $('#top-logos-moon-front').hover(function(){
        $body.fadeOut('slow',function(){
          $body.css('background-image', 'url("Frontpage-moon.jpg")').fadeIn('slow');
        });
    }, function() {
        $body.css('background-image', '')
    })
})

To optimize this further, follow these steps:

Begin by defining the image paths in your JavaScript using the following code snippet.

var imgs = [
  'http://i.imgur.com/DwLjYhh.jpg',
  'http://i.imgur.com/gAlqfUU.jpg'
];

Next, ensure your buttons have a new attribute like data-id for better organization.

<div class="top-logos-home" id="top-logos-moon-front" data-id='0'>
   <img src="button_image_jpg" alt="MOON">
</div>

Once all variables are set, use your existing hover detection code to dynamically change the background image based on the data-id attribute of the button.

jQuery(function(){
    var $body = $('.image-home');
    $('#top-logos-moon-front').hover(function(){
     $body.fadeOut('slow',function(){
        //fade out slowly element and after change the style of inner elements then fade in slowly.
        $body.css('background-image','url('+imgs[$(this).attr('data-id')]+')').fadeIn('slow');
     });
    });
});

In my personal view, managing image transitions can be improved by creating separate elements for each planet with overlapping animations triggered by user interaction. You can check out a demo showcasing this concept here: http://codepen.io/thegeek/pen/GDwCa

Answer ā„–2

After some experimentation, I discovered a solution using the opacity attribute. Now everything is functioning flawlessly.

HTML

<img id="background-moon-front" class="hover-backgrounds" src="Frontpage-moon.jpg" />

CSS

.hover-backgrounds {
    opacity:0;
    transition: opacity 0.6s linear;
    top:0;
    position:absolute;
    background-size: 100%;
}

JAVASCRIPT

$(document).ready(function (e) {
    $("#top-logos-lune-front").hover(function (e) {
    $("#background-moon-front"].css("opacity", "1");
    }, function() {
        $("#background-moon-front"]).css("opacity", "0")
    })
 });

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

Adjust the size of the image file for uploading

I am attempting to restrict the file upload size to 1MB by using this jQuery code snippet : <td><label> Upload image </label> <input type="file" class="upload" name="image" value="<?php echo set_value('image'); ?>" ...

Optimizing web content for iOS Safari with min-height media queries

I'm currently working on a Bootstrap-based photo browser that needs to have a responsive 4:3 aspect ratio. To achieve this, I have implemented the following approach: #carousel { width: 320px; height: 240px; ... } Additionally, I utilize media ...

Remove an item from an array and keep it stored efficiently without generating unnecessary waste

I'm interested in finding a high-performance method for removing and storing elements from an array. My goal is to create an object pool that minimizes the need for garbage collection calls. Similar to how .pop() and .unshift() remove elements from a ...

listbox fails to populate in Internet Explorer but functions correctly in Firefox and Chrome

Hey there! Iā€™m currently working with PHP and JavaScript on a code snippet that allows an admin to select a name from a dropdown menu, which then displays the locations associated with that name. These names belong to sales guys. The functionality works ...

Axios promise handler in Vue Js is limited to processing only a single statement at a time

I'm currently utilizing Vue Js in my Laravel project to execute a POST request. Everything seems to be functioning properly, but I'm encountering some issues while dealing with the promise: axios.post('/customer/update',this.custo ...

Dynamic canvas feature

Struggling with making a rectangle element inside a responsive canvas? You're not alone. The challenge lies in ensuring the rectangle always occupies 100% of the canvas width while maintaining a static height of 50px. Canvas Markup <div id="newCa ...

Validating Laravel emails with JavaScript blur and utilizing AJAX and jQuery

Looking for a way to validate a form in Laravel without hitting the submit button? I've tried some code, but only the email format validation seems to be working. Any tips on what I should do next? I'm new to Ajax. PS: When I enter a valid email ...

Issue: The serializer is receiving more than one value for the 'instance' argument

Recently, I started working with Django My current project involves performing CRUD operations using serializers, but I encountered this particular error: Here is the function in question: def updateemp(request, id): Updateemp = EmpModel.objects.get( ...

apply a visible border to the item that is clicked or selected by utilizing css and vue

I have a list of items that I want to display as image cards with an active blue border when clicked. Only one item can be selected at a time. Below is the code snippet: Template Code <div class="container"> <div v-for="(obj ...

What is the proper way to utilize useRef with HTMLInputElements?

Dealing with React and hooks: In my code, there is a MainComponent that has its own operations and content which refreshes whenever the value of props.someData changes. Additionally, I have designed a customized InputFieldComponent. This component generat ...

It seems like Flexbox is ignoring the flex-direction: column property set for a header element

I'm a bit confused because it seems like setting flex-direction: column on an element should display the children of that element in a horizontal row. My layout is simple - at the top, I have the logo, navigation links, and some controls. Below that, ...

What is the purpose of employing useMemo in the Material-UI autocomplete documentation?

My focus is on this specific demo in the autocomplete documentation. In the google maps example, there is a throttled function that is returned from a useMemo with an empty array as the second parameter. However, it raises the question of what exactly is ...

Can you explain the meaning of the '&&' expression in this JavaScript code snippet?

Hey there! I recently came across a JavaScript code snippet on this website. Can anyone help me understand how this line of code functions: (jq=jq.slice(1)).length && hidenext(jq); in the following function? (function hidenext(jq){ jq.eq(0).f ...

Pug: perform a task depending on the presence of an element within a variable

I'm currently working with Express js to create a web application. I make use of an API to fetch some data, which is then sent to a pug file in the following format. res.render('native.pug', {product_name: body.products, cart_items:body.car ...

Line breaks showing up on the page that are not present in the HTML source code

Why are unwanted line breaks appearing in my rendered DOM that are not in the source code, causing the content to be displaced? And how can I resolve this issue? Below is the code snippet: <div class="float-left" style="position:relative;left:15px"> ...

Combining a serialized date with an array for an Ajax post: What you need to know

Is there a way to combine a serialized date with an array using jQuery for AJAX post requests? For example, var array = { name: "John", time: "2pm" }; $.post( "page.php", $("form").serialize() + array); Currently, the output is: Array ( [url] => ...

What's the best way to determine the background image on this website? I'm in the process of replicating a site on

I have been asked to clone the website in order to create a Wordpress site. The original site is currently on Kajabi platform. I managed to download all images from the Kajabi site by right-clicking and selecting download. However, there are certain image ...

The invocation of $.ajax does not work as a function

I'm encountering an issue when running npm start and trying to access the browser, I keep getting this error message in the stack trace. Error: $.ajax is not functioning properly at findLocation (G:\CodeBase\ExpressApp\routes\ind ...

What is the process for incorporating a backup font for displaying unsupported characters in font-face?

I have incorporated a unique font for the Hebrew language on my website, but I am encountering an issue with missing English characters from a-b, A-Z. Currently, I have applied the font (reformaregular) to the body tag: body { font-family: 'reformar ...

jQuery UI Datepicker extending beyond its bounds

My Datepicker is expanding and filling the entire screen. What could be causing this issue? Here is my code: Additionally, how can I change the date format in jQuery to appear as dd-mm-yyyy? https://i.stack.imgur.com/IQzVV.png HTML: <!DOCTYPE html&g ...