Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Change background image on click 1

Status
Not open for further replies.

ralphonzo

Programmer
Apr 9, 2003
228
GB
I'm trying to get my background images to change when a link or button is clicked. I've got them to alter on a timed rotator, but can't figure out how to change them on demand. I'm developing it from a former site, so there's quite a lot of secondary files associated with what was. It's online @
Any other techniques are welcome, although the background images must be full screen as they currently appear.

Anybody done this before?
 
can't you just use jquery (since it is loaded)?

Code:
jQuery('a').on('click', function(e){
 e.preventDefault();
 var i = '';
 switch (jQuery(this).text()){
   case "Image 1":
     i = '' ;//url to image file
     break;
   ...etc....
 }
 jQuery('body').css('background-image', "url(i)");
});
 
I might be able to if I knew how to link it in. I'll have a play and see where we get. Thanks for the pointer.
 
Either bung it at the end of the page or within a Jquery ready() block.
Ideally you would style the image links with a common class and then narrow the selector to that class. Otherwise you'll find that none of your links work due to the preventDefault.
 
Struggling to figure out what goes where. I've tried to set a variable onclick on the links, as that seems logical...although I don't find JQuery to be anything of the kind! Tried to "style the image links with a common class and then narrow the selector to that class" as you suggested, but I'm sure I grabbed hold of the wrong end of the stick there! This is what I've ended up with:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] xml:lang="en" lang="en">
<head>
    <title>Background Image Changer</title>
    <link rel="stylesheet" media="screen" href="content/css/reset.css" />
    <link rel="stylesheet" media="screen" href="content/css/style.css" />
    <!--[if lt IE 8]><link rel="Stylesheet" media="screen" href="content/css/ie7.css" /><![endif]-->
    <script type="text/javascript">
	$(document).ready(function () {
		jQuery('imgbg').on('click', function(e){
		 e.preventDefault();
		 var i = 'content/images/a.jpg';
		 alert(jQuery(this).text());
		 switch (jQuery(this).text()){
		   case "Image 1":
			 i = 'content/images/a.jpg' ;//url to image file
			 break;
		   case "Image 2":
			 i = 'content/images/b.jpg' ;//url to image file
			 break;
		   case "Image 3":
			 i = 'content/images/c.jpg' ;//url to image file
			 break;
		   case "Image 4":
			 i = 'content/images/d.jpg' ;//url to image file
			 break;
		 }
		 jQuery('body').css('background-image', "url(i)");
		}); 
	});
    </script>
</head>
<body>
    <div id="Floater">&nbsp;</div>
    <div id="MainContainer">
        <div id="Header">
            <h3>Change the images</h3>
            <p><a href="#" class="imgbg">Image 1</a></p>
            <p><a href="#" class="imgbg">Image 2</a></p>
            <p><a href="#" class="imgbg">Image 3</a></p>
            <p><a href="#" class="imgbg">Image 4</a></p>
        </div>
    </div>
    <script type="text/javascript" src="scripts/jquery-1.6.2.min.js" ></script>
    <script type="text/javascript" src="scripts/cufon-yui.js"></script>
    <script type="text/javascript" src="scripts/script.js" ></script>
</body>
</html>

Absolutely no image renders either prior to or post click.

Perhaps when you've finished laughing, you could tell me why I'm such an idiot??
 
nearly perfect.
some minor changes as follows

Code:
//needs a dot to denote a class or a hash to denote an id
jQuery('[red].[/red]imgbg').on('click', function(e){

Code:
//variables are not expanded inside quotes in javascript
jQuery('body').css('background-image', "url(" + i + ")");

lastly, personally I'd load jquery from google's CDN with all the smart cacheing et alia that they do (not to mention the saving of your bandwidth ...
Code:
//instead of
<script type="text/javascript" src="scripts/jquery-1.6.2.min.js" ></script>
// use this
<script src="[URL unfurl="true"]http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>[/URL]
 
It's usually the minor changes that cause the major headaches! Sorry to hark on, but what's the relationship between the imgbg class (which doesn't exist by the way) and the overall functionality? I've made the changes and it still stubbornly refuses to budge. Could the imgbg class be the culprit? I don't get it, I thought this script was dynamically setting the background image through the body 'object'? Why is the click function utilised via the imgbg class??
 
the class 'identifies' the clickable links so that jquery knows which clicks to heed and which to ignore. beyond that level of identification it is not needed. you could set an arbitrary property instead.

there does not need to be a corresponding css declaration for the named class.

I'm sorry it is not working for you. It does for me.

Code:
<!DOCTYPE html >
<head>
    <title>Background Image Changer</title>
    <script type="text/javascript" src="[URL unfurl="true"]http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>[/URL] 
    <script type="text/javascript">
	$(document).ready(function () {
		$('.imgbg').on('click', function(e){
		 e.preventDefault();
		 var i = '';
		 switch ($(this).text()){
		   case "Image 1":
			 i = '[URL unfurl="true"]http://digitalartanddesign.org/assets/illustrator/images/abstract-background-example.png';[/URL]
			 break;
		   case "Image 2":
			 i = '[URL unfurl="true"]http://www.colourbox.com/preview/1948627-920-beam-example-background.jpg';[/URL]
			 break;
		   case "Image 3":
			 i = '[URL unfurl="true"]http://diariogamer.webege.com/videos/themes/default/member_images/example_background.png';[/URL]
			 break;
		   case "Image 4":
			 i = '[URL unfurl="true"]http://www.magicboxinc.com/images/gallery/MagicBox_Background_Example_1.jpg'[/URL] ;
			 break;
		 }
		 $('body').css('background-image', "url(" + i + ")");
		}); 
	});
    </script>
</head>
<body>
            <h3>Change the images</h3>
            <p><a href="#" class="imgbg">Image 1</a></p>
            <p><a href="#" class="imgbg">Image 2</a></p>
            <p><a href="#" class="imgbg">Image 3</a></p>
            <p><a href="#" class="imgbg">Image 4</a></p>
</body>
</html>
 
That works a treat. I think there was something conflicting amongst all the other css and js files involved. Is there any way to link it to the body, html style? I've been working with the following:

Code:
body, html {
	margin-left: 0px;
	margin-top: 0px;
	margin-right: 0px;
	margin-bottom: 0px;
	background: #00121E url("images/a.jpg") no-repeat center center fixed;
	-webkit-background-size: cover; /*for webKit*/
	-moz-background-size: cover; /*Mozilla*/
	-o-background-size: cover; /*opera*/
	background-size: cover; /*generic*/
}

which fills the background really nicely on it's own, but messes up with the click code. I've tried changing the .imgbg to body, but it doesn't like it. Is there any way to fill the background as this style allows (without tiling) whilst being changeable via clickage?
 
sure
Code:
 $('body').css('background', '#00121E url("' + i + '") no-repeat center center fixed');
 
That changes the image nicely, but the margin and cover don't take. I've tried adding .css elements but I'm damned if I can get it to play.

You'll be relieved to hear however, that I'm working through a JQuery course at the moment, but this lot's a bit too far down the line just yet.
 
all that the line does is apply the same css rule that you wanted applied.
if it does not look right it is because the rule is incorrect, not the javascript. change the rule however you like. the only important bit for the image is the url() piece. remember that variables are not expanded in quotes in javascript. you must break out of the quotes and use + to concatenate the variable and the string.
 
you are applying the background image to the html element, not the body element.

to mimic this in jQuery you need

Code:
$('html,body').css('background', '#00121E url("' + i + '") no-repeat center center fixed');

alternatively apply a reset such as that published by Eric Meyer.
 
'html,body' is exactly what I had/have online. I've had a play with the Eric Meyer reset code. I don't pretend to understand what it's supposed to achieve, but it certainly didn't improve matters for me. I have cracked it however (and I couldn't have got there without your help - please don't think I don't appreciate all of your help and pointers). What I did to get it to work is this:

Code:
$('html,body').css('background', '#fff url("' + i + '") no-repeat center center fixed');
$('html,body').css('-webkit-background-size', 'cover');
$('html,body').css('-moz-background-size', 'cover');
$('html,body').css('-o-background-size', 'cover');
$('html,body').css('background-size', 'cover');

I couldn't believe it when it finally worked out.

Thank you so much. That's twice in a week that you've really helped me out.
 
I tried it with just this code

Code:
$('body,html').css('background-image', 'url("[URL unfurl="true"]http://qudosbeta.co.uk/bgchange/'[/URL] + i + '") ');
in each of firefox, chrome and safari and found it worked fine in all (i.e. full screen, no banding, auto-rescaling etc).

So I am very surprised that you needed to reset all the other css background declarations for your implementation. I wonder what browser you are using to test with.

If you use the above code, the other declarations that are set in your css do not get changed (thus there should be no need explicitly to set them). You can prove this to yourself by examining the computed css for the html element in firebug.
 
Little things make all the difference. I've been playing with it again, and the differences I had were as follows:

'html,body' instead of 'body,html',
'background' instead of 'background-image', and
"' + i + '" instead of " + i + '"

although the latter doesn't seem to matter one way or the other. It's awkward when you're not used to a language/environment. It's sinking in quite nicely now though with no small thanks to you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top