Jump to content

I need a php button to change background color


bulldog11

Recommended Posts

I need a button in php to change my background color every 5 presses with a random one, every five presses the color have to change once and need to stay for the next 5 presses. here is my code <head>

<title>click 5 times</title>
 
<?php 
 
$a=array(0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f");
$culoare="#";
for($i=1; $i<6;$i++)
$culoare.=$a[rand(0,16)];
 
session_start();
$_SESSION['counter'] = isset($_SESSION['counter']) ? $_SESSION['counter'] : 0;
if($_POST['sub']) {
 $_SESSION['counter']++;
 
 echo "<br/>";
 echo $culoare;
echo "<body bgcolor='<?phpecho $culoare;?>'></body>";
}
 
?>
 
</head>
<body >
 
<form action='' method="post">
<input type="submit" name="sub" value="click" />
<input type="hidden" name="counter" value="<?php print $_POST['counter']; ?>" />
</form>
</body>

Hi, bulldog11!

Maybe you should use a Javascript. Change your input submit to button and use the .onclick event to trigger a function that will change the background color.

For example:

<button onclick="thisFunction()">Change color.</button>

And the script goes:

<script>
function thisFunction() {
  ...
}
</script>

You can also refer to this example: http://www.webcodingtech.com/javascript/change-background-color.php#

I hope this helps. Thank you.

Not the sort of thing PHP should be used for. Javascript would be better suited for this.

 

But to answer your question.

 

To generate a new colour every five button clicks you need to check when $_SESSION['counter'] becomes divisible by 5. When this is the case you'd generate a new background colour.

 

NOTE: in order to maintain the current background colour you will need to save its current value to the session. You'd then get the background colour from the session on page load.

 

Example code

if($_SESSION['counter'] % 5 == 0)
{
    // generate new background colour

    // save new background colour to the session
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.