We can easily change the background color of webpage using post method in jQuery.
Create a input type=”color”, give its name and id. Add style tag and a div tag with id=”preview” to preview the CSS styles that we are using to change the background color.
Color:<input type="color" name="color" id="color">
<style></style>
<div id="preview"></div>
Now the jQuery part, write on change event trigger for the color input. Take the color value in a variable $color. Post the value to php script using post method in jQuery.
Next make sure the style tags does not contain any styles using .empty() in jQuery. Add the styles that we have got from the php script to style tag and also to div tag.
$('#color').on('change', function() { // fires only after clicking OK
var $color = $("#color").val();
$.post("color.php",{color:$color}, function(data){
//console.log(data);
$("style").empty();
$("style").text(data);
$("#preview").text(data);
});
});
Now the PHP script.
<?php
$color = $_POST['color'];
$code = <<<str
html{
background-color:$color;
}
str;
echo $code;
?>
In the PHP script we are capturing the posted color value in a variable $color. Next we are using heredoc in PHP to write the css styles and finally echo it.
0 comments:
Post a Comment