Grow your CSS skills. Land your dream job.

Change Main Background Image

  • # April 25, 2009 at 5:10 am

    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.

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

    Any ideas?

    Cheers,
    Niplo.

    # April 25, 2009 at 6:49 pm

    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:

    Code:
    document.getElementById(‘randomID’).style.backgroundImage = “url(images/myimage.gif)”;

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

    Code:

    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

    # April 25, 2009 at 8:37 pm

    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:

    Code:

    and the put this on a button:

    Code:

    This worked, do you have any ideas on how I could get that image to fade in? I’m after a smooth transition.

    # April 25, 2009 at 8:52 pm

    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?

    # April 27, 2009 at 8:20 am

    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/

    # April 28, 2009 at 6:58 am

    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.

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".