onClick function does not work properly

Asked

Viewed 835 times

2

I have a very simple application where I want to change the color of the text by clicking the button. Since I want to handle the onClick event directly in the . js file, not in HTML. Could someone point out what’s wrong with 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';
};

1 answer

4


The problem is in the way the onclick.

The error occurs because the 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.