Good afternoon, I need to know how I can assign the same function to different elements, without repeating the code as I am currently doing:
<section id="projects">
<h6>PORTAFOLIO</h6>
<h1 onclick="style()">Algunos de mis trabajos</h1>
<article id="projectsList">
<div class="project-title-div" onmouseover="myStyle()" onmouseout="myStyleOff()">
<img src="img/portfolio/ada-lovelace.jpg" alt="trabajo web natalia cancino">
<div class="overlay"> Sitio web Ada Lovelace</div>
</div>
<div class="project-title-div" onmouseover="myStyle2()" onmouseout="myStyleOff2()"><img src="img/portfolio/cecor.jpg" alt="trabajo web natalia cancino">
<div class="overlay"> Sitio web Cecor</div>
</div>
<div class="project-title-div" onmouseover="myStyle3()" onmouseout="myStyleOff3()"><img src="img/portfolio/cloudbreak.jpg" alt="trabajo ilustracion natalia cancino">
<div class="overlay"> Ilustraciones estampados Cloudbreak</div>
</div>
</section>
<script>
//project 1
function myStyle() {
var x = document.getElementsByClassName("overlay");
x[0].style.visibility = "visible";
x[0].style.opacity = "1";
}
function myStyleOff() {
var x = document.getElementsByClassName("overlay");
x[0].style.visibility = "hidden";
x[0].style.opacity = "0";
}
//project 2
function myStyle2() {
var x = document.getElementsByClassName("overlay");
x[1].style.visibility = "visible";
x[1].style.opacity = "1";
}
function myStyleOff2() {
var x = document.getElementsByClassName("overlay");
x[1].style.visibility = "hidden";
x[1].style.opacity = "0";
}
//project 3
function myStyle3() {
var x = document.getElementsByClassName("overlay");
x[2].style.visibility = "visible";
x[2].style.opacity = "1";
}
function myStyleOff3() {
var x = document.getElementsByClassName("overlay");
x[2].style.visibility = "hidden";
x[2].style.opacity = "0";
}
</script>
I’ve been searching for a long time, I found something about the delegation of events in javascript but I do not know how to apply in this case, please if you could help me, I would greatly appreciate it.
Excuse my English, I’m from Chile.
Greetings from a distance!