- 1

I'm trying to hyperlink an image within this array... Having some trouble

Here is my code: var images = [ 'images/gustav-klimt.jpg', 'images/woman-looking-forward.jpeg', 'images/snowy-landscape.jpg' ]; var num = 0; function next() { var slider = document.getElementById('slider'); num++; if(num >= images.length) { num = 0; } slider.src = images[num]; } function prev() { var slider = document.getElementById('slider'); num--; if(num < 0) { num = images.length-1; } slider.src = images[num]; } The slider functions well, but I want the images to be hyperlinked too. I've googled everywhere and havent found an applicable solution. I thought this would work: var images = [ '<a href='#'><img src='images/gustav-klimt.jpg'/></a> ]; but still no luck..

2nd Aug 2017, 8:37 PM
Franklin Sami
Franklin Sami - avatar
3 Respuestas
+ 3
@Franklin Sami Yes and... no ;P Without your whole code (meaning also html structure at least), it's more difficult to answer ^^ Anyway this function works for your purpose, even you can get it more simple by hard coding the link element, rather than testing if exists and adding it if not, just updating its 'href' attribut if yes: var images = [ 'https://www.entreprises.gouv.fr/files/files/ESPACE-EVENEMENTIEL/SEMAINE-INDUSTRIE/img/peinture.jpg', 'https://www.4murs.com/system/generes/cms/000/066/131/2070681567_1x/66131-peintures-couleurs.jpg?1446558423', 'http://www.atelier-des-peintres.fr/img/bandeau/peinture-ecologique.jpg' ]; var links = [ '#', '#', '#' ]; function imgLink(target,index) { var i, a = target.parentNode; if (a.tagName!='A') { a = document.createElement('a'); i = target.parentNode.replaceChild(a,target); a.appendChild(i); } else i = target; a.href = links[index]; i.src = images[index]; } var num = 0; function next() { var slider = document.getElementById('slider'); num++; if(num >= images.length) { num = 0; } // slider.src = images[num]; imgLink(slider,num); } function prev() { var slider = document.getElementById('slider'); num--; if(num < 0) { num = images.length-1; } // slider.src = images[num]; imgLink(slider,num); } ... obviously, you doesn't need a second array for 'href' urls if you want the link target the image itself ;)
3rd Aug 2017, 6:14 AM
visph
visph - avatar
+ 2
there are many possible ways.. just for instance u can create a seperate function that assigns a link depending on the source of the image and bind it to its onclick method
2nd Aug 2017, 8:43 PM
Rik Roy
Rik Roy - avatar
- 1
Would this be close? var images = [ 'images/gustav-klimt.jpg', 'images/woman-looking-forward.jpeg', 'images/snowy-landscape.jpg' ]; function hyperLinks(){ images[0].href='#'; images[1].href='#'; images[2].href='#'; }
3rd Aug 2017, 12:51 AM
Franklin Sami
Franklin Sami - avatar