Set Background Image From Dropdown Menu - Javascript
I want to make a menu to select different backgrounds for a website about my artwork. This (link works perfectly for just background colors and I was able to replicate it just fin
Solution 1:
Here you go, just add more options to the dropdown with the image url as the value to give more background options.
HTML:
<select id="backgrounds">
<option>Select a background</option>
<option value="http://t2.gstatic.com/images?q=tbn:ANd9GcT-wQk0CTwl93EmiaUaoIjpMVmwHDNBz_7hN0UNpAz5DCWq66Sp-w">Background 1</option>
<option value="http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg">Background 2</option>
</select>
Script:
$(document).ready(function()
{
var body = $(document.body);
$('#backgrounds').bind('change', function(event){
var bg = $(this).val();
if(bg == null || typeof bg === 'undefined' || $.trim(bg) === '')
body.css('background-image', '');
else
body.css('background-image', "url('" + bg + "')");
});
});
To allow a combination of background images and background colors you can use the code below:
HTML:
<select id="backgrounds">
<option>Select a background</option>
<option value="url('http://t2.gstatic.com/images?q=tbn:ANd9GcT-wQk0CTwl93EmiaUaoIjpMVmwHDNBz_7hN0UNpAz5DCWq66Sp-w')">Background Image 1</option>
<option value="url('http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg')">Background Image 2</option>
<option value="none #000">Black</option>
<option value="none red">Red</option>
</select>
Script:
$(document).ready(function()
{
var body = $(document.body);
$('#backgrounds').bind('change', function(event){
var bg = $(this).val();
if(bg == null || typeof bg === 'undefined' || $.trim(bg) === '')
body.css('background', 'none transparent');
else
body.css('background', bg);
});
});
Solution 2:
With background image options instead of just colors.
<form name="bgcolorForm">View my artwork:
<select name="backArt" id="backArt">
<option value="image1.gif">A Wedding Photo</option>
<option value="image2.jpg">Beautiful Sunset</option>
<option value="image3.gif">Canyon Lights</option>
<option value="image4.gif">Morning Dew</option>
<option value="image5.jpg">My Wife's Ugly Wart</option>
<option value="image6.gif">My Beautiful Children</option>
</select>
</form>
$(function () {
$('#backArt').on('change', function () {
var backImg = $('option:selected', this).val();
$('body').css('background-image', 'url(' + backImg + ')');
});
});
Post a Comment for "Set Background Image From Dropdown Menu - Javascript"