Wednesday, August 20, 2008

[jQuery] Creating a jQuery banner with timer and fadeIn/fadeOut (fadeTo) effect

The following example will create a banner that shows a text and then after 5 seconds fades the text out, changes to a new text and then fades back in with the new text.

Create an html page importing two javascript files:
1. jQuery (http://jquery.com/)
2. jQuery timer plugin (http://plugins.jquery.com/project/Timer)

Example:




Then in a javascript area, create an array of texts you wish to display in the banner:
var bannerTexts = new Array();
bannerTexts[0] = 'Java';
bannerTexts[1] = 'JPA';
bannerTexts[2] = 'Maven';


Now use a timer to shift between the texts one at a time:
var i = 0;
$.timer(5000, function (timer) {
if (i == bannerTexts.length) {
i = 0;
}
$('#banner').fadeTo(1000, 0,
function() {
$(this).html(bannerTexts[i]);
}).fadeTo(1000,1,
function() {
i++;
});
});

This will insert the banner text from the "bannerTexts" array in to the element with id "banner".

Here's the full example... Copy paste the following code into an html page and make sure the jquery and jquery-timer plugin javascript files are available in a js/ subdirectory:

<html>
<head>



</head>
<body>
</body> </html>

You can also add a random generator so the texts doesn't appear in the same order every time:

$('#banner').fadeTo(1000, 0,
function() {
// Pick random text from array
var text = bannerTexts[Math.floor(Math.random()*bannerTexts.length)];
$(this).html(text);
}).fadeTo(1000,1, function() {
i++;
});

4 comments:

Jakob Maaløe said...

If you need to change the banner to a vertical one, you can use the following script to parse the bannerTexts and insert
after each character:

// Parse texts to be vertical
for (i=0; i < bannerTexts.length; i++) {
var newTxt = "";
for (j=0; j < bannerTexts[i].length; j++) {
newTxt += bannerTexts[i].substring(j,j+1) + "<br />";
}
bannerTexts[i] = newTxt;
}

Mario said...

Hi...i'd like to use your script but with images, no text...

What i must change in the script for random images every x second?

TNX a lot!

Jakob Maaløe said...

Hi,

Sorry for the late response, I've been on vacation.

The easiest thing to do is to change the array to hold the images you want to display. Here's an example:

var bannerTexts = new Array(); bannerTexts[0] = '<img src="img/jakob.maaloe.png" width="30" height="50"/>';
bannerTexts[1] = '<img src="...." width="30" height="50"/>';


The rest of the code should be the same and will display a random image from the array of images every 5 second.

Did that answer your question?

Muhammod Arifur Rahman said...

Hi,..
U'd like to use php script . So that the div element text comes from mysql.

So how can I change
var bannerTexts = new Array();
bannerTexts[0] = 'Java';
bannerTexts[1] = 'JPA';
bannerTexts[2] = 'Maven';

make this var dynamic. So that it can very with my row no in database.