kano
kano

Reputation: 5920

Calling a javascript function with parameters from a dynamically created element

I'm trying to dynamically load pictures to a profile page like site from MySQL with PHP and then add them to an unordered list with javascript. I would like each list item to also have a like button, which upon clicking calls a javascript function, passing the image name as its parameter. I've searched and found answers on how to call a function without passing it any variables, but every time I add the image name to the function call, the console log reads "undefined".

The pictures show up fine and the imgArray[i] is a string containing the file's name (e.g. photo.jpg) But

console.log(imgArray[i]) 

in the onclick function reads undefined. I've also tried

like.setAttribute()

without any results.

function showGallery(imgArray) {
    for(var i=0; i < imgArray.length; i++){ 

        var list = document.getElementById("image-list"),
            li   = document.createElement("li"),
            img  = document.createElement("img"),
            like = document.createElement("a");

        img.src = "user_images/" + imgArray[i];
        like.className = "button-like";

        li.appendChild(img);
        li.appendChild(like);
        list.appendChild(li);

        like.href = "javascript:void(0);";
        like.onclick = function() {
            console.log(imgArray[i]);
            addLike(imgArray[i]);
        };
    }
} 

function addLike(img) {
    console.log("Liking..  " + img);
    $.ajax({
       url: 'like.php',
       type: 'POST',
       data: {
           'photo': img
       },
       success: function(likes){
           console.log(likes);
       }  
   });
}

Upvotes: 1

Views: 2298

Answers (1)

Spock
Spock

Reputation: 4900

The problem is that by the time the click event fires, imgArray[i] doesn't exists.

try doing it like this...

like.href = "javascript:void(0);";
like.imgArray = imgArray[i];
like.onclick = function() {
        console.log(this.imgArray);
        addLike(this.imgArray);
    };

Hope that helps

Upvotes: 2

Related Questions