Sebastien Bolh Sebastien Bolh - 3 months ago 10
HTML Question

How can I make a button that that triggers a script?

My goal is to create a button that you can click to start a script. I want to have the button be able to be clicked more than once to do the script multiple times, and make the button have a price that takes from my "clicks" variable.

<div class="game-object">
<script type="text/javascript">
var clicks = 0;

document.getElementById("push").addEventListener("click", updateClickCount);

function updateClickCount() {
var el = document.getElementById("clickCount");
el.innerHTML = clicks;
el.style.color = '#'+Math.floor(Math.random()*16777215).toString(16);
el.style.fontSize = '70px';
}

</script>

<script>
var clicks = 0;
window.setInterval(
function () {
clicks = clicks + 1;
document.getElementById("clicks").innerHTML = clicks;

}, 1000);
</script>

<button type="button" onClick="clicks++;updateClickCount();" id="push" style="width:400px;height:60px;"><font size="5" face="verdana" color="white">Click me for Cola!</font></button>
<div id="clickCount"></div>




I do not know where in the code to put the button.

Seb

Answer

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="push" style="width:400px;height:60px;">
    <font size="5" face="verdana" color="white">Click me for Cola!</font>
</button>
<div id="clickCount"></div>

<script type="text/javascript">
    var clicks = 0;

    var h = null;
    $("#push").click( function(){
        var el = document.getElementById("clickCount");
        el.innerHTML = clicks;
        el.style.color = '#'+Math.floor(Math.random()*16777215).toString(16);
        el.style.fontSize = '70px';
        if(!h){
            h = window.setInterval(function () {
                clicks = clicks + 1;
                document.getElementById("clickCount").innerHTML = clicks;
            }, 1000);
        }
    });

</script>