0

I wrote a little javascript that was supposed to change the size of all images on my web page when a user clicks on it. But I resive an error when I try to run it.

<script  type="text/javascript">

function changeSize(img){

var bigsize = "800"; 
var smallsize = "500"; 

  if(img.height == bigsize) img.height = smallsize;
  else img.height = bigsize;
  }
var element = document.getElementsByTagName("img");
element.addEventListener('click',changeSize(this),false  );
</script>

What am I doing wrong?

Lemmy
  • 319
  • 2
  • 4
  • 10

1 Answers1

0

Access your img in changeSize as event.target, also addEventListener called incorrectly, see code snippet below in details because a lot of code were updated:

Working code snippet, you could see that image border changed after clicking on image.

function changeSize(event){

var bigsize = "800"; 
var smallsize = "500"; 

  if(event.target.height == bigsize) event.target.height = smallsize;
  else event.target.height = bigsize;
  }

var elements = document.getElementsByTagName ("img");

for (var i = 0; i < elements.length ; i++) {
    elements[i].addEventListener("click", 
        changeSize, 
        false);
}
img{
border: 1px solid black;
}
<img onclick="changeSize(event)" width='30' height='40'/>

<img width='30' height='40'/>
<img width='30' height='40'/>
<img width='30' height='40'/>
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82