change color when onclick javascript code example

Example 1: onclick change text color javascript

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

Example 2: css onclick change color

<style>
.dabutton:focus {
    background-color:yellow;
}
</style>
<button class="dabutton"></button> // <-- usage

Example 3: change color by click event javascript

var button = document.querySelector("button");

button.addEventListener("click", function() {
    const curColour = document.body.style.backgroundColor;

    document.body.style.backgroundColor = curColour === 'red' ? 'blue' : 'red';
});

Tags:

Css Example