treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Change Main Background Image

  • I was wondering if anyone knew of a way to change the main fixed background image (on the <body> tag) triggered by the click of a button. I preferably want this to cross fade between images (the dude's creepy stare!) and have looked at Javascript and Jquery as possible methods but can get my head around it, don't know how to target the background image element. I wanted to avoid putting the image in a div as I don't want scroll bars and I want the content to float on top.

    http://www.get-over.net/Images/over/shot1.jpg

    Any ideas?

    Cheers,
    Niplo.
  • Hi Niplo,

    Good question. Basically, you will use CSS to assign the background like normal, and then use Javascript to change the background image.

    Here's the basic Javascript code for changing an element's background:

    document.getElementById('randomID').style.backgroundImage = \"url(images/myimage.gif)\";


    Then you could use a "onclick" attribute to run the code. Simple example:

    <a href=\"#\" onClick=\"document.getElementById('[i]randomID[/i]').style.backgroundImage = \"url(images/myimage.gif)\";\">Click Me</a>


    Note: that you will need to replace randomID with the ID of the item you will be replacing. You may need to give an ID to <body> if that is where you background is applied to.

    -Ashton Sanders
    -www.WebssitesinaFlash.com
  • Thanks for the help, it put me on the right track! I couldn't really get your code to work, so I used it as a starting point and wrote this:

    <script type=\"text/javascript\">

    function changeImage(newImage)
    {
    elem = document.getElementById(\"changer\");
    elem.style.backgroundImage = newImage;
    }
    </script>


    and the put this on a button:

    <button onclick=\"changeImage('url(images/sky2.jpg)');\">Sky</button>


    This worked, do you have any ideas on how I could get that image to fade in? I'm after a smooth transition.
  • Excellent. I'm glad you got it to work.

    Hmm... I have limited knowledge of Javascript, etc. so can't recommend a good tool for making the background fade in. Anyone else?
  • You could add almost exactly the same code via jquery then you could use the fade to make it look pretty.

    Take a loot at http://www.css-tricks.com/video-screencasts/20-introduction-to-jquery/
  • I thought Jquery could provide a solution, but I'm new to it and not sure of the syntax to adapt my basic code to Jquery so that it fades in. Could 'lyleyboy' or anyone for that matter set me off on the right track.

    Much appreciated.