javascript newbie: what's the right way to apply the same behavior to multiple elements? -


i'm taking first adventure javascript, , totally without bearings. i'd show thumbnail opens modal larger view of picture (and front end fanciness i'll need, i'm trying keep simple). i've copied this code w3schools, uses getelementbyid. works great first image on page clicking subsequent images doesn't pop up. reading around on stack overflow sounds that's because i'm matching on id, each element on page will/should have different id (which makes sense).

i saw post here person made ids unique appending element's id. that, (a) wanted check if that's kosher , (b) id no longer match, there different attribute tack on match html styles? must common problem- what's right way apply same behavior multiple elements on page? example can give them

thanks!

update: based on everyone's feedback below i've modified code use getelementbyclassname instead of getelementbyid- see gist here: https://gist.github.com/dianekaplan/1602a7c0a1c1ec6aa103b61d6530ff15

if i'm reading code correctly, important lines me change line 115 line 116- (to set image info based on classname, not id)- , replacing 'myimg' popup' in style lines 5 , 11, clicking first image no longer opens modal, missed something. see what's wrong need work?

you should use class name (the same in img) instead of ids , use getelementsbyclassname() fetch of them, instead of getelementsbyid() gets 1 (as ids must unique).

then, should store full size image's url somehow in order fetch regardless of img clicked. 1 way may using data attributes.

example:

<img src="thumb1.jpg" data-fullsize="full1.jpg" class="popup"> <img src="thumb2.jpg" data-fullsize="full2.jpg" class="popup"> <img src="thumb3.jpg" data-fullsize="full3.jpg" class="popup"> 

var elems=document.getelementsbyclassname("popup"); for(var i=0;i<elems.length;i++) {     elems[i].onclick=function() {          var fullsize=this.dataset.fullsize;          //open de popup, fullsize has clicked image url     } } 

code not tested, idea only.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -