I'm a frustrated newbie who is trying to get some projects done, but I always get stuck... at the same principle (I believe). Can somebody help me, please? ;)
PROJECT 1:
When an image is clicked, I want to change its src
attribute. When I'm looping through the array of images
, I don't know how to get the index of the image that has just been clicked on, I'd always end up with the index of the last image - I guess that's because the loop would go through the whole array, that's why I added break; which should get me out of the loop. It doesn't work (obviously).
for (var i = 0; i < images.length; i++) {
images[i].onclick = function() {
images[i].src = "noun_2.png";
};
break;
}
PROJECT 2:
When the button is clicked, I want the images with class="new"
to fade out. I don't understand why the code is not working.
<img class="new" src="media/1.jpg">
<img src="media/france.jpg">
<img class="new" src="media/2.jpg">
<img src="media/france2.jpg">
<img class="new" src="media/3.jpg">
<p id="button">Click me!</p>
<script>
var button = document.getElementById("button");
var images = document.getElementsByClassName("new");
button.onclick = function() {
for (var i = 0; i < images.length; i++) {
images[i].setAttribute("class", "fadeOutClass");
}
};
</script>
*EDIT: IIFE solves the project 1, I'm adding the whole source code of the project 2:
<!DOCTYPE html>
<html>
<head>
<title>Fade Out</title>
<meta charset="utf-8">
<style>
#button {
padding: 15px;
background-color: grey;
margin: 0 35%;
}
img {
opacity: 1;
transition-duration: 3s;
}
.fadeOutClass {
opacity: 0;
}
</style>
</head>
<body>
<img class="new" src="media/1.jpg">
<img src="media/france.jpg">
<img class="new" src="media/2.jpg">
<img src="media/france2.jpg">
<img class="new" src="media/3.jpg">
<p id="button">Click me!</p>
<script>
var button = document.getElementById("button");
images = document.getElementsByClassName("new");
button.onclick = function() {
for (const i = 0; i < images.length; i++) {
images[i].setAttribute("class", "fadeOutClass");
}
};
</script>
</body>
</html>
I want all the images with class=new
to fade out at the same time, but when I click the button, only the first image fades out. When I click the button again, the next image fades out and so on.