I want to set the background image based on user selection.
Scenario:
User selects a color among color options. Based on this the background image must be changed like theme.
For example, if user selects red color background image should be image_red.png. If user changes the color to violet it should be image_violet.png.
There are multiple images like this the color of which should change according to user selection. So is there a way of setting it in css like background-image: url(../image_colorparameter.png)
So, here's a nice way to do it if you have specific classes
in mind:
(added background functionality for class names)
(additional proof of concept. Type your own dynamic image and it will populate.)
HTML:
<div id="thisThing"></div>
<input id="yellow" type="button" name="yellow" value="yellow" />
<input id="red" type="button" name="red" value="red" />
<input id="blue" type="button" name="blue" value="blue" />
CSS:
#thisThing {
width:200px;
height:200px;
}
.yellow {
background:#FC2;
}
.blue {
background:#00F;
}
.red {
background:#F00;
}
jQuery:
$(function() {
$('input').on('click', function() {
var color = $(this).attr('id');
$('#thisThing').removeClass();
$('#thisThing').addClass(color);
});
});
Obviously you'd change the classes from background
to background:url(...)
but I didn't have your images.
Additional note. No need to use ID
if you don't want. value
, name
also work in this case. See here:
You can change the CSS properties using $.css() method. http://api.jquery.com/css/ Also you can retrieve the CSS property using the same method.
Following method will allow you to change the background image in a parametrized way based on user selection.
function changebackground(var color) {
$('body').css('background-image','url(img/'+ color +'.jpg)');
}
One of simple way is to just assign image name as an id for option. Once any option is selected do :: var v = $("option").id(); $("body").css("background","url("+v+")");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.