lundi 4 février 2019

Why will my not Background change on click with hexadecimal colors?

I have an html document where i wanted to change the background color of the document by clicking on a button.

This works totally fine as long as i am using colors like "yellow, "blue", "red", etc.

But when i am using hexadecimal colors like "#000000" the if-condition doesnt seem to notice, that color and uses the else function.

If i use "black" instead of "#000000" the function works and the background turns red.

I've uploaded the working sample on jsfiddle.

Do you know where the mistake is?

https://jsfiddle.net/c2gv9x01/

<button>COLOR SWITCH</button>



<script>
window.onload=function(){
    document.querySelector("body").style.backgroundColor = '#000000';
    document.querySelector("button").addEventListener("click", color);
}

function color() {

    if (document.querySelector("body").style.backgroundColor == '#000000') 
{document.querySelector("body").style.backgroundColor = 'red'; }


     else {document.querySelector("body").style.backgroundColor = '#000000';}
}
</script>

Aucun commentaire:

Enregistrer un commentaire