Reputation: 25
I'm pretty sure this is gonna have to be in php... but let me explain what i'm looking for.
I have an input box on my site and what ever the user enters in there is set as the css
for example
body{
Background-color: [text from the input goes here];
}
Upvotes: 2
Views: 132
Reputation: 1567
With javascript/jquery you could do this:
see (try putting in #000, or green, or some other color) : http://jsfiddle.net/mH6MK/
$( document ).ready(function() {
$('input[name=getColor]').change(function() {
var $color = $("#getColor").val();
$('body').css('backgroundColor', $color);
});
});
or php would be like this:
<?
$color = $_GET['color'];
echo '<style type="text/css">body{background:'.$color.';}</style>';
?>
Upvotes: 2
Reputation: 1048
You're absolutely right! you can use PHP but you can consider using jquery and get hold of the input element via $('input') and getting the value and adding the css.
Assuming you have an input with the id of #css, i'm going to use the on() method and use event delegation to target the particular id which in this case is #css.
You would do something like this:
$('form").on('submit', '#css', function()) {
var value = $this.val();
$('body').css('background-color', value);
});
You may want check the value you receive from your user and ensure that it is a proper css hex color value or something. Some form of validation. This is just one of a few ways you can and PHP is also an option.
Upvotes: 0
Reputation: 19645
You can use jquery, but I suggest pure javascript if you aren't using jquery otherwise. It is faster and more powerful.
link to demo => http://jsfiddle.net/77Bjx/
<input placeholder="enter hex color w/o #" id="bg" type="text"/>
<input type="button" value="submit" onClick="setBG()"/>
function setBG() {
var elem = document.getElementById('bg')
document.body.style.backgroundColor = '#' + elem.value;
}
you can than improve this function. maybe set a check to make sure it is a valid hex value? check if it starts with a # and enter one if it doesn't. etc.
Upvotes: 2
Reputation: 4887
With some testing I found that it is possible to set the body background color using:
document.body.style.backgroundColor = "purple";
and if you have the name
/id
of the input
element, then its value is:
document.getElementsByName(elementName).value
So it shouldn't be too difficult to put those pieces together. Just listen for when the focus of the input changes, maybe via an onBlur
listener.
Upvotes: 0
Reputation: 123
Why not use jquery?
$('body').css('backgroundColor', [input from box]);
Upvotes: -1