OnClick function does not work properly

2

I have a very simple application where I want to change the color of the text when I click the button. Being that I want to handle the onClick event directly in the .js file, not in HTML. Could anyone point out what is wrong in my code? NOTE: All files are in the same directory.

HTML

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">

    <title>JS - Change Color</title>
</head>
<body>
    <h1 id="header">Click to change the color!</h1>
    <input type="button" id="colorButton" value="Click me!"></input>

    <script type="text/javascript" src="script.js"></script>
</body>
</html>

CSS

.red-text {
    color: red;
}

Javascript

var colorButton = document.getElementById('colorButton');

colorButton.onClick = function () {
    console.log('clicked');
    header.className = 'red-text';
};
    
asked by anonymous 05.12.2017 / 16:09

1 answer

4

The problem is how onclick was written.

The error occurs because JS is case sensitive and the correct syntax is in lowercase.

var colorButton = document.getElementById('colorButton');

colorButton.onclick = function () {
    console.log('clicked');
    header.className = 'red-text';
};
.red-text {
    color: red;
}
<h1 id="header">Clique para mudar a cor!</h1>
<input type="button" id="colorButton" value="Clique aqui!"></input>
    
05.12.2017 / 16:25