samedi 5 avril 2014

Javascript Button not working


Vote count:

0




In this piece of code my button isn't working:



<html>
<body>
<button onclick="buttonChange()">Press</button>
<script>
function buttonChange() {
var button=confirm("Press Me");
if (button==true)
{
fn()
}
}
var color = '#33cc33',
elem = document.getElementById('txt');
function fn() {
elem.style.color = color;
setTimeout(function() {
color = '#'+Math.floor(Math.random()*16777215).toString(16);
fn();
}, 500);
}();
</script>
</body>
<p id='txt'>
Unicorns
</p>
</html>


Well that's not entirely true. This is how I get it to work, I change the fn() function:


Before:



function fn() {
elem.style.color = color;
setTimeout(function() {
color = '#'+Math.floor(Math.random()*16777215).toString(16);
fn();
}, 500);
}();


After:



(function fn() {
elem.style.color = color;
setTimeout(function() {
color = '#'+Math.floor(Math.random()*16777215).toString(16);
fn();
}, 500);
})();


Not much, but it works. Problem is when it the button works the random color doesn't work. When the random color works the button doesn't. My main goal is to have the button ask whether you want the word "Unicorn" to randomly switch colors.


Summary: If you press ok, the fn() function begins, when you press cancel, nothing simply happen.



asked 13 secs ago






Aucun commentaire:

Enregistrer un commentaire