Josh.S
Josh.S

Reputation: 127

Adding onclick event listeners and elements using javascript

I'm trying to add a series of images to the html page using javascript and a for loop. But the event listeners such as onclick and onmouseover aren't responding when I test the page.

function changeText(element)
{   
  var menuItems = ['menu_item1','menu_item2','menu_item3','menu_item4'];
  var galleryImages = ["s1.jpg","s2.jpg","s3.jpg","s4.jpg","s5.jpg","s6.jpg","s7.jpg","s8.jpg","s9.jpg","s10.jpg","s11.jpg","s12.jpg","s13.jpg","s14.jpg","s15.jpg","s16.jpg","s17.jpg","s18.jpg","s19.jpg","s20.jpg"];

  var itemText = document.getElementsByClassName(element);
  var textString ="";           
  if(menuItem == menuItems[3])
  {
    for(var i=0;i<galleryImages.length;i++){
      textString+="<img id='img"+i+"'class='imageGallery'src='galleryImgs/s"+i+".jpg' width='150px' onclick='imageZoom('img"+i+"')'>";  
    }
    itemText[0].innerHTML = 'This is now menu_item4 text Left side';
    itemText[1].innerHTML = textString 
  }
  return;   
}

function imageZoom(img)
{
  var image = document.getElementById(img);
  image.style.width = "400px";
}       

Upvotes: 0

Views: 170

Answers (1)

struthersneil
struthersneil

Reputation: 2750

It's your quote characters.

This--

onclick='imageZoom('img"+i+"')'

Becomes this--

onclick='imageZoom('img1234')'

The HTML parser sees--

onclick='imageZoom(' some junk

So just change the quote characters for escaped double quotes (\").

onclick=\"imageZoom('img"+i+"')\"

Upvotes: 2

Related Questions