Switching background images on click with a smooth transition

I'm in the process of creating a website and I want to be able to change background images with ease when clicked, like using fade in or fade out effects.

The onclick functionality is already implemented with jQuery, but I'm having trouble incorporating easing effects.

I've done some research online, but all the solutions I found involve using a div in a small portion of the page only.

My issue arises because I use these divs as full-page elements, taking up 100% width and height, with content on top of them.

I considered using sprites and animating the background position, but this doesn't work for me as I need my page to be responsive and have percentages in the background URL, whereas sprites require fixed widths (please correct me if I'm mistaken).

Additionally, there's another div behind the ones I'm working with, so adjusting opacity won't solve the problem. The website I am building is similar to this:

HTML:

<div class="Page" id="feauture3">
    <div id="feauture3_content">
        <div id="feauture3_1"><strong>Menu1</strong></div>
        <div id="feauture3_2"><strong>Menu2</strong></div>
        <div id="feauture3_3"><strong>Menu3</strong></div>
        <div id="feauture3_4"><strong>Menu4</strong></div>
    </div>
</div>

CSS:

#feauture3_1:hover {
        background-color:#f2af95;
        cursor:pointer;
}

#feauture3_2:hover {
        background-color:#f2af95;
        cursor:pointer;
}

#feauture3_3:hover {
        background-color:#f2af95;
        cursor:pointer;
}

#feauture3_4:hover {
        background-color:#f2af95;
        cursor:pointer;
}

#feauture3 {
        position: fixed;
        height: 100%;
        width: 100%;
        background: url('http://www.asphaltandrubber.com/wp-content/gallery/2013-kawasaki-ninja-z800-z800e/2013-kawasaki-ninja-z800-02.jpg') 50% 50% no-repeat;
        left:0; 
        background-size: cover;
        background-color:#e18764;
        color:red;
}

Jquery:

jQuery(document).ready(function($){
       $("#feauture3_1").click(function(){
       $("#feauture3").css('background-image','url("http://www.motorcyclespecs.co.za/Gallery%20B/Kawasaki%20Ninja%20650R%2013.jpg")');
    });

    $("#feauture3_2").click(function(){
        $("#feauture3").css('background-image','url("http://images5.fanpop.com/image/photos/31700000/HOT-BABE-KAWASAKI-Z1000-motorcycles-31778270-1920-1200.jpg")')
    });

    $("#feauture3_3").click(function(){
        $("#feauture3").css('background-image','url("http://b296d35169b22ec514a7-3f0e5c3ce41f2ca4459ddb89d451f8d9.r21.cf2.rackcdn.com/wp-content/uploads/2012/11/Kawasaki-Z1-by-Ac-Sanctuary-.jpg")')
    });

    $("#feauture3_4").click(function(){
        $("#feauture3").css('background-image','url("http://4.bp.blogspot.com/-ar4zyO_Ws4M/UekF8jk7nRI/AAAAAAAA1q4/ugQZlRGTLkk/s1600/Kawasaki-Z-1000-.jpg")')
    });

});

Fiddle:

http://jsfiddle.net/9pWhN/1/

Thank you for your time.

Edit: I ended up simply using $

("#feauture3").css('background-image','url("image")')
and setting a background-color to the entire div that matched the images (the actual project doesn't include motorcycles as images). This solution worked well for me.

Answer №1

What are your thoughts on using css transitions for animation?

#feauture3 {
    position: fixed;
    height: 100%;
    width: 100%;
    background: url('http://www.asphaltandrubber.com/wp-content/gallery/2013-kawasaki-ninja-z800-z800e/2013-kawasaki-ninja-z800-02.jpg') 50% 50% no-repeat;
    left:0;
    background-size: cover;
    background-color:#e18764;
    color:red;
    -webkit-transition:all 1.4s ease-in-out;
    -o-transition:all 1.4s ease-in-out;
    -moz-transition:all 1.4s ease-in-out;
}

Check out this demo on JSFiddle

Answer №2

We can break down these issues into separate parts:

  1. One way to incorporate easing or fading effects into images is by using CSS 3

    #feauture3 {
    position: fixed;
    height: 100%;
    width: 100%;
    background: url('http://www.asphaltandrubber.com/wp-content/gallery/2013-kawasaki-ninja-z800-z800e/2013-kawasaki-ninja-z800-02.jpg') 50% 50% no-repeat;
    left:0; 
    background-size: cover;
    background-color:#e18764;
    color:red;
    -webkit-transition: all 500ms cubic-bezier(0.250, 0.100, 0.250, 1.000); 
    -moz-transition: all 500ms cubic-bezier(0.250, 0.100, 0.250, 1.000); 
     -o-transition: all 500ms cubic-bezier(0.250, 0.100, 0.250, 1.000); 
        transition: all 500ms cubic-bezier(0.250, 0.100, 0.250, 1.000);
    }
    

  2. Another method to check if an image has loaded and then add the source is through a JavaScript hack

$("<img>").attr('src', 'http://picture.de/image.png').load(function() {
     $(this).remove();
     $('body').css('background-image', 'url(http://picture.de/image.png)');
});

Experiment with CSS3 easing and fading

For questions about image loading, visit this link

Answer №3

Here's a neat trick for enhancing your features:

    $("#feauture3_2").click(function(){
    $("#feauture3").css({
        'background-image' :  'url("http://images5.fanpop.com/image/photos/31700000/HOT-BABE-KAWASAKI-Z1000-motorcycles-31778270-1920-1200.jpg")',
        'opacity': 0
    })
    .animate({
        'opacity': 1
    }, 800);
});

Simply insert that code snippet into each click event.

Answer №4

Would you like to give this a try?

Check out the demonstration here

To improve the transition, use .fadeOut() before changing the image, then follow with .fadeIn() using setTimeout().

JQUERY

$("#feauture3_1").click(function(){
   $("#feauture3").fadeOut(1000);
   setTimeout(function() {
       $("#feauture3")
           .css('background-image','url("http://www.motorcyclespecs.co.za/Gallery%20B/Kawasaki%20Ninja%20650R%2013.jpg")')
           .fadeIn(1000);     
   }, 1000);       
});

Answer №5

Try this solution - make sure to check if the external images are fully loaded before proceeding:

  jQuery(document).ready(function($){
  var img1 = 'http://www.motorcyclespecs.co.za/Gallery%20B/Kawasaki%20Ninja%20650R%2013.jpg',
      img2 = 'http://images5.fanpop.com/image/photos/31700000/HOT-BABE-KAWASAKI-Z1000-motorcycles-31778270-1920-1200.jpg',
      target = $('#feauture3');

      $("#feauture3_1").click(function(){
          target.fadeOut(1000, function(){
              target.css('background-image', 'url('+img1+')');  
              target.fadeIn(500);
          });
      });

      $("#feauture3_2").click(function(){
          target.fadeOut(1000, function(){
              target.css('background-image', 'url('+img2+')');  
              target.fadeIn(500);
          });
      });  

});

Answer №6

It seems like this could be the solution you're seeking:

http://css3.designsolutions.com/cfimg/#cfimg7By loading all images on top of each other before transitioning, the 'flash' issue you mentioned should be eliminated.

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 are the implications of using eval() to interpret function parameters?

I've recently utilized Hopscotch to create a interactive tour on my Website. To implement this, you need to create a JavaScript object as a parameter to trigger the startTour() function which will kick off the tour. For instance, in this case, the tou ...

Angular is encountering a CORS issue with the "No Access-Control-Allow-Origin" error when trying to access a CSS file

Currently, in my Angular 5 application with a Web API back-end, my main goal is to reference a CSS file on a production server. I'm facing a cross-origin issue when trying to access the CSS file hosted on the IIS server website. Even though CORS is e ...

Eliminate empty space in the table cell

I am working with a table that looks like this: <table> ... <td> <div class="btn-group btn-group-sm"> <button class="btn btn-info mini"><span class="glyphicon glyphicon-duplicate"></span></button&g ...

Angular Material - truncating selected text in a list

I'm having trouble implementing the Angular Material list with checkboxes, where the text needs to be truncated instead of word-wrapped due to limited UI space. I have modified an example on the Angular Material site to demonstrate the issue. The text ...

Unveiling the hidden secrets of HTML code through scraping

Looking to extract data from the cadastral records in Poland available at . Specifically, I am interested in retrieving information from the element tagged with id 'gfi_0'. The challenge is that this element is not immediately accessible; it only ...

Using line breaks and horizontal scrolling in HTML and CSS

I am struggling with a div that contains multiple small spans. My goal is to implement a horizontal scrollbar that extends up until the line break tags (a-z on each line) in order to view the full content on narrow screens. Although I have applied the &ap ...

What is the best way to retrieve the value of the button that was clicked using JQuery?

Looking to capture the selected value from a dropdown menu in order to execute a database query for rendering the next page. How can I extract only the clicked value from the dropdown menu? The dropdown menu is dynamically generated from the database: ...

Replacing Bootstrap CSS with a custom stylesheet

Within my bootstrap.css file, the following styling is defined: .form-control { display: block; width: 100%; height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.428571429; color: #555555; ve ...

Switching the displayed image depending on the JSON data received

As a beginner in javascript and jQuery, I am working on displaying JSON results in the browser. My goal is to generate dynamic HTML by incorporating the JSON data. Below is an example of the JSON structure: [{"JobName":"JobDoSomething","JobStatus":2,"JobS ...

Issue with AnimeJS Motion Path causing element to deviate from desired SVG path

I'm attempting to use an SVG element and the AnimeJS library to make the orange marker follow the course of this RC car race track. https://i.stack.imgur.com/8FKHC.png Despite my efforts, I am encountering strange and undesirable outcomes. At times ...

Designing a Custom Wordpress Extension and Integrating External Scripts

As I dive into the world of WordPress plugin development, I'm seeking guidance from the codex to enhance my skills. Currently, I have a basic plugin that loads a javascript file from a CDN and is supposed to display tooltips. However, I'm facing ...

Verify if a set of Radio buttons contains at least one option selected

Need help with validating a Feedback Form using either JQuery or Javascript. The requirement is to ensure that every group of radio-buttons has one option selected before the form can be submitted. Below is the code snippet from form.html: <form id=&ap ...

Adjust the width of the dropdown menu for the v-combobox

I am currently working on creating a multiple search filter similar to the one found in Gitlab dashboard. https://i.sstatic.net/YHivl.png For this task, I am utilizing Vuetify's v-combobox like this : <v-combobox id="mycombo&quo ...

Display a hidden div upon loading the page if a certain condition is met

As a beginner in this field, I am struggling to assist a friend with a project. He needs a simple quote form that can generate HTML quotes for his client on a private WordPress page. The form should display a specific div based on the radio button selecti ...

Problem with loading images on an HTML webpage

https://i.sstatic.net/aQ0oD.png After refreshing the page, I'm encountering an issue where the image is not loading. However, if I switch tabs from MEN to WOMEN and back again, the image will display without any problem. Even making changes in the CS ...

The Layout of Bootstrap4 Form is Displaying Incorrectly

I'm attempting to create a basic email form similar to the one shown in the Bootstrap 4 documentation. However, I am facing an issue where the formatting is not displaying correctly. Here is what the example should look like: https://i.sstatic.net/qx ...

Is there a way to superimpose multiple PNGs and ensure that each one is clickable within its designated area?

I am looking to implement a interactive image system for dynamically generated content. The image includes a background image and various grey-scale mask images. Background Image: https://i.sstatic.net/NWzQ1.jpg (source: goehler.dk) Masks: https://i.ss ...

Looking to showcase elements within an array inside an object using ng-repeat

In this JSON dataset, we have information about various anchoring products. These products include anchors, cleats, snubbers, shackles, and more. When it comes to displaying these products on an HTML page using Angular, make sure to properly reference the ...

The attempt to showcase items in a div element using inline display did not produce

I am having trouble with creating a webpage. I have designed a website but I am struggling to get it right. I have included my HTML and CSS code below. What I am trying to achieve is a header at the top, followed by several sections containing a photo on ...

The userscript will keep the window open as long as it remains inactive

Hello everyone, I'm excited to join the StackOverflow community and dive into userscripts for the first time! Putting aside any unnecessary details, I'm encountering a small issue with a script I recently created. (function () { $("#enbut"). ...