I have 4 divs (colored box) and each div represent a different color.
When a user hovers over one of the colored boxes the text to display (“Hello world”) should change to the color that is being hovered over – this is how it looks like .
I wrote the code for each color, but it seems worng because I’m copying the code many times for each color.
How can I make this code shorter and more efficient?
html:
<body>
<h1 id="change_heading">Hello World</h1>
SELECTED COLOR <span class="selected">None!</span>
<section>
<div class="brown"></div>
<div class="green"></div>
<div class="blue"></div>
<div class="yellow"></div>
</section>
<script src="script.js"></script>
css:
div {
width: 50px;
height: 50px;
display: inline-block;
}
.brown {
background-color: brown;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
javascript:
document.addEventListener('DOMContentLoaded', function () {
const textToChange=document.getElementById('change_heading');
const brownColor=document.querySelector('.brown');
const greenColor=document.querySelector('.green');
const blueColor=document.querySelector('.blue');
brownColor.addEventListener('mouseover', function(){
textToChange.classList.add('brown');
});
brownColor.addEventListener('mouseout', function(){
textToChange.classList.remove('brown');
});
greenColor.addEventListener('mouseover', function(){
textToChange.classList.add('green');
});
greenColor.addEventListener('mouseout', function(){
textToChange.classList.remove('green');
});
blueColor.addEventListener('mouseover', function(){
textToChange.classList.add('blue');
});
blueColor.addEventListener('mouseout', function(){
textToChange.classList.remove('blue');
});
});