I'm creating bunch of images with ( let obrazek = document.createElement("img"); ) and i set their opacity to 0.9 with ( obrazek.style.opacity = 0.9; ) and i also add onclick.
Basically I just want to change their opacity to 1.0 after i click one of images, but it doesn't work, error - Uncaught TypeError: Cannot set properties of undefined (setting 'opacity').
I tried with obrazek.addEventListener("onclick", zaznacz); , but with this the function itself doesn't work, but there are no errors.
I have JQuery on,
new to JS and I have no idea why this doesn't work.
function zaznacz() {
this.style.opacity = 1.0;
}
let obraz = document.createElement("div");
obraz.setAttribute("class", "obraz");
content.style.textAlign = "center";
content.style.color = "#ffffff";
for(let i = 0; i < 8; i++) {
let tiles = document.createElement("div");
tiles.setAttribute("class", ("tiles"+i));
tiles.style.height = "40px";
for(let j = 0; j < 8; j++) {
let obrazek = document.createElement("img");
obrazek.setAttribute("class", "tile");
obrazek.style.opacity = 0.9;
obrazek.setAttribute("onclick", "zaznacz()");
tiles.appendChild(obrazek);
}
obraz.appendChild(tiles);
}
You're nearly there, but you have some errors here.
There are specific methods for manipulating the class list on an element, so I've changed your code to use .classList.add() instead of attempting to set the class list directly as an attribute.
I changed the code that attempts to set the onclick attribute to use .addEventListener() instead. Note that the event name is 'click', and I pass just the name of the function.
When you create obraz your code then attempts to set the style on content, which comes up as undefined.
I've added a line to append the elements created to the <body>.
I've added a little styling to my test page to help visualise the results, since there are no images.
function zaznacz(){
console.log("Zaznacz called")
this.style.backgroundColor = "lightgrey"; // Added to help visualise
this.style.opacity = 1.0;
}
let obraz = document.createElement("div");
obraz.classList.add("obraz");
obraz.style.textAlign = "center"; // changed content to obraz
obraz.style.color = "#ffffdd";
for(let i=0; i<8; i++) {
let tiles = document.createElement("div");
tiles.classList.add("tiles"+i);
tiles.style.height = "40px";
for(let j=0; j<8; j++) {
let obrazek = document.createElement("img");
obrazek.classList.add("tile");
obrazek.style.opacity = 0.9;
obrazek.addEventListener("click", zaznacz);
tiles.appendChild(obrazek);
}
obraz.appendChild(tiles);
}
document.querySelector('body').appendChild(obraz);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.tile {
min-width:40px;
min-height:40px;
border:1px solid grey;
}
</style>
</head>
<body>
</body>
</html>