Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67411

Setting a onClick function to a dynamically created button, the function fires onload

$
0
0

I am currently creating a program which utilizes localStorage to create a site with a wishlist like functionality. However when I go to generate the html page that should create the wishlist with the photo of the item, the name and a button to remove said item from the list. But when I go to assign the onClick functionality to the button, the function fires on page load rather then on click. I have four main java script functions, one to add to the localstorage, one to remove from local storage, a helper function for removing and the one that will generate the wishlist page (where the problem is).

function genWishListPage(){

    for (var i = 0; i < localStorage.length; i++) {

        var item = getWishlist(i);
        var name = document.createElement("p");
        var removeButton = document.createElement("button");
        var image = document.createElement("img")

        image.src = item.image;


        removeButton.innerText = "Remove from wishlist";
        removeButton.onClick = RemoveFromWishList(item.name);
        removeButton.setAttribute("ID","remove");
        name.innerText = item.name;
        document.body.appendChild(image);
        document.body.appendChild(name);
        document.body.appendChild(removeButton);
        document.body.appendChild(document.createElement("BR"));

        //removeButton.setAttribute("onclick", RemoveFromWishList(item.name));
        //removeButton.addEventListener('click', RemoveFromWishList(item.name));
        //document.getElementById("remove").addEventListener("click",RemoveFromWishList(item.name));
    }
}

The commented parts are ways I have already tried and gotten the same bug.

Any help or advice is appreciated.


Viewing all articles
Browse latest Browse all 67411

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>