I've encountered a challenge with assigning IDs to elements containing the "img" tag. I've attempted to find solutions from others facing similar issues, but none of them quite align with my own problem. I am fairly new to Javascript and suspect that I might be approaching it incorrectly. Nevertheless, here is my current Javascript code:
var imgs = document.getElementsByTag('img');
var count = imgs.length;
window.onload = function() {
for (i = 0; i < count; i++) {
imgs[i].setAttribute('id', i.toString());
}
}
function toggleOverlay() {
var overlay = document.getElementById('overlay');
var container = document.getElementById('container');
overlay.style.opacity = .8;
if (overlay.style.display == "block") {
overlay.style.display = "none";
container.style.display = "none";
} else {
overlay.style.display = "block";
container.style.display = "block";
}
}
function draw(ID) {
var canvasContainer = document.getElementById("container")
var c = document.createElement('canvas');
c.width = 500;
c.height = 110;
c.id = "product";
var img = document.getElementById(ID);
var ctx = c.getContext("2d");
ctx.rect(0, 0, c.width, c.height);
ctx.drawImage(img, 0, 0);
canvasContainer.appendChild(c);
}
div#overlay {
display: none;
z-index: 2;
background: #000;
position: fixed;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
text-align: center;
}
div#container {
display: none;
position: relative;
z-index: 3;
margin: 150px auto 0px auto;
width: 600px;
height: 360px;
background: #FFF;
color: #000;
border-style: solid;
border-color: #f00;
border-radius: 5px;
border-width: 4px;
box-shadow: 5px 6px RGBa(0, 0, 0, 0.4);
}
div#wrapper {
position: absolute;
top: 0px;
left: 0px;
padding-left: 24px;
}
#product {
position: relative;
width: 85%;
height: auto;
z-index: 4;
margin-top: 10px;
margin-left: 10px;
}
.clickable::after {
width: 25%;
height: auto;
}
#addtocart {
position: absolute;
bottom: 0;
right: 0;
margin-bottom: 5px;
margin-right: 5px;
background-color: #f00;
color: #FFF;
border: none;
border-radius: 3px;
width: 6em;
height: 3em;
}
#addtocart:hover {
transition-duration: 0.2s;
background-color: #e00;
opacity: 0.8;
}
.clickable {
cursor: pointer;
}
div#view {
position: absolute;
text-align: center;
background: #f00;
color: #FFF;
border-radius: 2px;
width: 6em;
height: 2em;
}
div#view:hover {
display: block;
z-index: 2;
}
div#images:hover {
background-color: RGBa(0, 0, 0, 0.2);
}
#link {
background-color: #f00;
border: none;
border-radius: 3px;
display: none;
color: #FFF;
}
<div id="overlay"></div>
<div id="container">
<p id="information"></p>
<button id="addtocart">Add to Cart</button>
</div>
<div id="wrapper">
<h2>Test</h2>
<p id="name"></p>
<div id="images">
<img class="clickable" onmousedown="toggleOverlay(); draw(this.id);" src="PIXEL-TITANIUM-SHAFT-GOLD-MEDIUM-133000.gif" /img>
<img class="clickable" onmousedown="toggleOverlay(); draw(this.id);" src="MichaelVanGerwen.gif" /img>
</div>
</div>