0

i need some help here about a script javascript for a website i assuming it's kinda obvious. Let me explain, i have a gallery, a loop and on every click on an image of the gallery, the clicked image will move in an other div which is for now hidden. So on the click i call 2 functions, the first one to show the div and the second one to change de src of the image in the hidden div by the href of the clicked image.

   function OnClickGallery(){ 

      var Galerie = document.getElementById('GPNPHide'), 
          liens = Galerie.getElementsByTagName('a'),
          imgkids = Galerie.getElementsByTagName('img'),
          ImageBig = document.getElementById('ImageFull'); 

        for (var i = 0 ; i < liens.length ; ++i) { 
             liens[i].onclick = function(){ 

                  GalerieVueShowToggle(); 
                  ImageBig.src = this.href; 
                  return false; 
               }; 
        } 
  } 
  window.onload=OnClickGallery; 

Everything was working well until i tried to avoid jshint error "don't make function within a loop" by creating my function onClick outside of the loop and just calling my function in the loop but in my onClick function the i is obviously not defined here, i'm stuck here, how can i get the i of the loop in my onClick function?

   function onClick() {
        "use strict";
        var ImageBig = document.getElementById('ImageFull'),
            Galerie = document.getElementById('GPNPHide'),
            liens = Galerie.getElementsByTagName('a');

        ImageBig.src = liens[i].href;
        return false;
    }


    function OnClickGallery() {
        "use strict";
        var Galerie = document.getElementById('GPNPHide'),
            liens = Galerie.getElementsByTagName('a'),
            imgkids = Galerie.getElementsByTagName('img'),
            ImageBig = document.getElementById('ImageFull'),
            i;

       for (i = 0; i < liens.length; i += 1) {
            liens[i].onclick = galerieVueShowToggle;
            liens[i].onclick = onClick;
        }

    window.onload = OnClickGallery;
lalithkumar
  • 3,480
  • 4
  • 24
  • 40
Jeyko
  • 1
  • For starters, I would use `addEventListener` instead of `onclick`. To be able to help you please provide a working snippet(`HTML, CSS` too) – Ionut Necula Jul 19 '17 at 09:03
  • The "this" reference is not persistent. You should still pas this on. Rewrite the function function onClick() as function onClick(this) and change the onclick declaration of liens[i].onclick = onClick; to liens[i].onclick = function(){ onClick(this) }; – Gilles Lesire Jul 19 '17 at 09:05

1 Answers1

-1

Pass the value of "i" to the onClick function like this:-

onClick(i)