Banner ad animation with jQuery

· 1 Comment · in HTML5, jQuery

This is an example of using two images to create simple banner ad animation. Perfect for quick and easy HTML5 banner ad creation.

There are two versions, both use jQuery.

One runs animation on hover, the other loops the animation and pauses when hovered over.

Animations run independently of each other.

HOVER EXAMPLE

First image (this is the hover state and must be first)

Second image (default)

Markup
The “hover” image must be first.

The images have absolute positioning and are wrapped in an <a> tag. The <a> will live inside a container element with a class of “rollover”. The “data-speed” attribute is the speed/length of the animation in seconds. Setting to “0″ will swap the images without any fading effects.

<div class="rollover" data-speed="800">
    <a href="">
        <img src="/img/cocacola_hover.jpg" alt="" />
        <img src="/img/cocacola.jpg" alt="" />
    </a>
</div>

CSS

div.rollover {
    width:320px;
    height:100px;
    position:relative;
    float:left;
    display:block;
    clear:both;
}
div.rollover a {
    float:left;
    display:block;
}
div.rollover a img {
    position:absolute;
    top:0px;
    left:0px;
    z-index:1;
}

jQuery
We’re making use of the jQuery fadeIn() method. We grab the “data-speed” attribute value on the parent container to set the animation speed.

$(".rollover").hover(
    function(event){
        var ds = $(this).attr("data-speed");
        $(this).find("img:first")
            .css("display","none")
            .css("z-index",2)
            .stop(true)
            .fadeIn(parseFloat(ds),"linear")
    },
    function(event){
        var ds = $(this).attr("data-speed");
        $(this).find("img:first")
            .stop(true)
            .fadeOut(parseFloat(ds),"linear",function(){
				$(this).css("z-index",1)
			})
    }
);

Put it all together and you have simple hover animation. See the examples here.

 

LOOPING EXAMPLE

First image (this is the animation state and must be first)

Second image

Markup
The “animated” image must be first.

The images have absolute positioning and are wrapped in an <a> tag. The <a> will live inside a container element with a class of “loop”. The “data-speed” attribute is the speed/length of the animation in seconds. Setting to “0″ will swap the images without any fading effects. The “data-delay” attribute is the amount of seconds between showing the animation.

<div class="loop" data-speed="800" data-delay="3000">
    <a href="">
        <img src="/img/red_bull_hover.jpg" alt="" />
        <img src="/img/red_bull.jpg" alt="" />
    </a>
</div>

CSS

div.loop {
    width:320px;
    height:100px;
    position:relative;
    float:left;
    display:block;
    clear:both;
}
div.loop a {
    float:left;
    display:block;
}
div.loop a img {
    position:absolute;
    top:0px;
    left:0px;
    z-index:1;
}

jQuery
We bind events to the “.loop” class we set in the markup above. To start the animation(s), we need to init/trigger one of the events on our “.loop” class. The last line does this via a trigger. This one init will start all animations that are bound.

When hovered over, the animation is stopped and restarts when mouse leaves.

We are not using a setTimeout or setInterval, since we would need to keep track of the timers. Even though this can be done, see my post on JavaScript timers, we don’t need it here. Instead we will use a delay to cycle the animation.

We’re not using jQuery’s “.delay()” either, since there are known issues with this method and clearing animation queues.

Instead, we use a more clever approach by using “.animate()” as a delay. Basically, when the image has finished fading in and has an opacity of 1, we run “.animate()” again with an opacity of 1 and length set in our “data-delay” attribute. The animate isn’t really doing anything since the opacity already has a value of 1, it’s the length of time that the animate runs that gives us our delay. Cool, huh?

This also allows us to use the “.stop()” method to clear the animation queue. If you have a “.delay()” on an animation, running “.stop()” does NOT cancel the “.delay()”. Some consider this a jQuery “bug” – either way, we avoid this issue by using animate as the delay. Hopefully, I’ve saved you some time by noting this since it was painful finding out the hard way.

$("body").on("anim mouseenter mouseleave", ".loop",function(event){
     var ds = $(this).attr("data-speed");
     var dd = $(this).attr("data-delay");
     var $img = $(this).find("img:first");
	 if( event.type === "mouseenter" ){
         $img.stop(true);
         $img.css("z-index","1");
         return false;
     }
     if( event.type === "mouseleave" ){
         $img.stop(true);
         $(this).trigger("anim");
         return false;
     }
     if( parseFloat($img.css("z-index")) === 1 ){ //fadein
         $img.css("opacity",0)
			 .css("z-index",2)
			 .animate({opacity:1},parseFloat(ds),function(){
			 	//use animate as a delay
			 	$(this).animate({opacity:1},parseFloat(dd),function(){
					$img.parents(".loop").trigger("anim");
				});
			 });
      }
      else { //fadeout
	  	 $img.animate({opacity:0},parseFloat(ds),function(){
				$img.css("z-index",1);
				//use animate as a delay
			 	$(this).animate({opacity:0},parseFloat(dd),function(){
					$img.parents(".loop").trigger("anim");
			 	});
		 });
	  }
});
//init
$(".loop").trigger("anim");

Put it all together and you have looping animation. See the examples here.

Keep in mind that animations in this manner are processor intensive since we are using client-side processing as opposed to a self-contained object like Flash or an animated gif.

There is no error checking, this is just the basic code. You can add your own error checking to fit your needs. You might find my post on JavaScript logging useful.

Sure, there are many other ways to do this. The above is an exercise.

Tested in:
jQuery version 1.7.2
FF 3.6+, Safari, Chrome, IE8+
iOS

Great books are available on JavaScript and jQuery.
 

This entry was posted in HTML5, jQuery and tagged , , , , , .
Bookmark the permalink.

One Response to Banner ad animation with jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *

*

To include code in your comment: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag(or shortcode) and format it when submitted.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">