Thursday, July 9, 2009

Change HTML background image

In a similar vein to changing the background colour of a HTML page, this script will allow you to change the background image. Add the following Actionscript and a movieclip with an instance name of "btn":
import flash.external.*;
var jsCall:String;
btn.onPress = function() {
jsCall = String(ExternalInterface.call("changeBgImg", "myNewImg.jpg"));
};

Add the following Javascript to your HTML code:

<script language="JavaScript">
function changeBgImg(newBgImg) {
document.body.background = newBgImg
}
</script>

As before, you can still add a little random spice by using the following Actionscript:
import flash.external.*;
bgImages = new Array("film0.jpg", "film1.jpg", "film2.jpg", "film3.jpg", "film4.jpg", "film5.jpg", "film6.jpg", "film7.jpg", "film8.jpg", "film9.jpg");
var jsCall:String;
btn.onPress = function() {
ranImg = bgImages[Math.floor(Math.random() * 10)];
jsCall = String(ExternalInterface.call("changeBgImg", ranImg));
};

You can see an example here along with the code.

Note that this script will follow the default behaviour and cause your image to be tiled across your HTML background. If you don't want it to be tiled, try changing the script to this:

<script language="JavaScript">
function changeBgImg(newBgImg) {
document.body.background = newBgImg
document.body.style.backgroundRepeat='no-repeat';
document.body.style.backgroundPosition='center';
}
</script>

You can see an example of a non-tiled image change here.

3 comments:

amitabhaghosh197 said...

your post is a good post but i want to ask you that the AS to be written in flash? and the swf and the jpg file to be kept in the same folder of html folder?

glosrfc said...

You place all of the Actionscript into your FLA, and any Javascript in your HTML code.
The SWF and JPGs don't have to be in the same folder (although it's easier if you do so) as you can edit the file information to use relative paths to the JPGs from your HTML folder.

amitabhaghosh197 said...

Thanks glosrfc for your reply and distributing your knowledge. It's a great job of yours. Please keep on developing