I have no knowledge of js, but I am trying to add a class to a div when any point of the screen is clicked. I have this html
<div class="container">
<div class="box"></div>
</div>
And I need to add the class to the container when any point of the screen is clicked.
I tried this js
<script>
let button = document.querySelector('.container');
button.addEventListener('click', function() {
button.classList.add('.hide');
});
</script>
but it is not working, the class is not being applied. What am I doing wrong?
There is a small syntax error: the class should be mentioned without the dot prefix:
button.classList.add('hide');
let button = document.querySelector('.container');
button.addEventListener('click', function() {
button.classList.add('hide');
});
.container {
background-color: #ddd;
cursor: pointer;
}
.box {
background-color: #ccf;
margin: 1rem;
}
.hide {
opacity: 0;
transition: opacity .5s ease-in-out;
}
<div class="container">
<br>
<div class="box">Click anywhere in the grey container to hide it</div>
<br>
</div>