Antonio Gvardijan Antonio Gvardijan - 6 months ago 13
HTML Question

Onclick function does nothing in image gallery

I'm learning to make image gallery and when i click on thumbnail, it does nothing. Bellow is my code, I'm trying for some tome to make it work, can I get some help ?
HTML :

<script src="galerijaSlika.js"></script>
<img id="glavnaSlika" src="Slike/infogamer_galerija/info1.jpg">
<div id="sveSlike" onClick="promjeniSliku(event)">
<img src="Slike/infogamer_galerija/info1.jpg">
<img src="Slike/infogamer_galerija/info2.jpg">
<img src="Slike/infogamer_galerija/info3.jpg">
<img src="Slike/infogamer_galerija/info4.jpg">
<img src="Slike/infogamer_galerija/info5.jpg">
<img src="Slike/infogamer_galerija/info6.jpg">
<img src="Slike/infogamer_galerija/info7.jpg">
<img src="Slike/infogamer_galerija/info8.jpg">
<img src="Slike/infogamer_galerija/info9.jpg">
<img src="Slike/infogamer_galerija/info10.jpg">
<img src="Slike/infogamer_galerija/info11.jpg">
<img src="Slike/infogamer_galerija/info12.jpg">
</div>


Javascript :

function promjeniSliku(event){
event = event || window.event;
var trazeniElement = event.target || event.srcElement;
if(trazeniElement == "IMG"){
document.getElementById("glavnaSlika").src = trazeniElement.getAttribute("src");

}
}

Answer

Your typo is:

if(trazeniElement == "IMG"){

The correct test must be:

if (trazeniElement.tagName == "IMG") {

For details see MDN

function promjeniSliku(event){
  event = event || window.event;
  var trazeniElement = event.target || event.srcElement;
  if (trazeniElement.tagName == "IMG") {
    document.getElementById("glavnaSlika").src = trazeniElement.getAttribute("src");
  }
}
<img id="glavnaSlika" src="Slike/infogamer_galerija/info1.jpg">
<div id="sveSlike" onClick="promjeniSliku(event)">
    <img src="Slike/infogamer_galerija/info1.jpg">
    <img src="Slike/infogamer_galerija/info2.jpg">
    <img src="Slike/infogamer_galerija/info3.jpg">
    <img src="Slike/infogamer_galerija/info4.jpg">
    <img src="Slike/infogamer_galerija/info5.jpg">
    <img src="Slike/infogamer_galerija/info6.jpg">
    <img src="Slike/infogamer_galerija/info7.jpg">
    <img src="Slike/infogamer_galerija/info8.jpg">
    <img src="Slike/infogamer_galerija/info9.jpg">
    <img src="Slike/infogamer_galerija/info10.jpg">
    <img src="Slike/infogamer_galerija/info11.jpg">
    <img src="Slike/infogamer_galerija/info12.jpg">
</div>