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>
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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
}
Edited by Ch0cu3r
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.