Search code examples
javascriptjqueryhtmlcssfade

Trigger a fade when swapping between classes using jQuery


I have following code working so far: JSFIDDLE DEMO

The relevant JS is here:

// Define classes & background element.
var classes = ['bg1','bg2','bg3','bg4'],
    $bg = document.getElementById('blah');
// On first run:
$bg.className = sessionStorage.getItem('currentClass') || classes[0];
// On button click:
$('.swapper').mousedown(function () {
  // (1) Get current class of background element,
  // find its index in "classes" Array.
  var currentClassIndex = classes.indexOf($bg.className);
  // (2) Get new class from list.
  var nextClass = classes[(currentClassIndex + 1)%classes.length];
  // (3) Assign new class to background element.
  $bg.className = nextClass;
  // (4) Save new class in sessionStorage.
  sessionStorage.setItem('currentClass', nextClass);
});

For my purposes, this functionally working great -- I can click a single button to continually swap between those four classes while also storing the current class to sessionStorage, so that when I click links on my website, the currentClass is loaded right away. (Note: on my website the setup is the same, but the classes bg1, bg2, bg3, and bg4 contain background images.)

What I'd like it to do: When swapping from one class to another, I'd like it to do a quick/short cross-fade. Right now it just snaps from one class/background to another.

My thinking was: is there a way I can trigger a CSS class transition or animation that contains the fade, perhaps as a parent class? I know there's a jQuery fade function, but I haven't been able to get it working with my setup so that it triggers on mouseClick.


Solution

  • Here's an updated jsfiddle based on your comment where you said you've sort of having it work.

    I've added the timeout functions

    setTimeout(function(){$bg.className = nextClass}, 500);
    setTimeout(function(){$($bg).fadeIn(500)}, 500)
    

    The first timeout makes it so that the image is swapped right after the first image fades out. The second timeout gives it a bit of time to load in so it's not so jittery.

    You can play with the }, 500); number to get it timed just like you want, 500 is half a second, 1000 is a second etc.