I want to change the color randomly on hovering <a class="c-link"
but it doesn't work and I wonder what I am doing wrong here.
<!doctype html>
<html>
<script>
window.onload = function() {
function randomColor() {
let color = [];
for (let i = 0; i < 3; i++) {
color.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + color.join(', ') + ')';
}
document.querySelector('c-link').addEventListener("mouseover", function() {
document.a.style.fontcolor = randomColor();
});
}
</script>
</head>
<body>
<div class="c-text__layer">
<div class="c-text">Lorem ipsum dolor sit amet consetetur,<br> sadipscing elitr,
<a class="c-link" href="https://stackoverflow.com/"> sit amet dolor</a></div>
</div>
</body>
</html>
You need to specify the class with a . within the query selector. Therefore querySelector('.c-link').
You cannot just call document.a because a is not a property or method of the document object.
Also, there is style.color and style.font but not fontcolor.
Instead use another selector: querySelector('a') to select all the anchors in the document. This will affect every link though. If you only want it to work for one or a few elements you could use the data-attribute, an id or even other CSS classes instead of targeting a in the querySelector.
You can also read a bit on MDN to learn more about JS and the web.
<!doctype html>
<html>
<script>
window.onload = function() {
function randomColor() {
let color = [];
for (let i = 0; i < 3; i++) {
color.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + color.join(', ') + ')';
}
document.querySelector('.c-link').addEventListener("mouseover", function() {
document.querySelector('a').style.color = randomColor();
});
}
</script>
</head>
<body>
<div class="c-text__layer">
<div class="c-text">Lorem ipsum dolor sit amet consetetur,<br> sadipscing elitr,
<a class="c-link" href="https://stackoverflow.com/"> sit amet dolor</a></div>
</div>
</body>
</html>