Search code examples
javascriptonclickhrefaddeventlistener

dynamic list in javascript how to call function from specific <li>


I get the message list from the API and create a dynamic array using javascript. I would like a new page with message details to be started when a specific row is pressed. How do I implement a call to showMessage () on a specific table row?

var list = document.getElementById("listOfMessage");
init();
function init() {
    for (var i = 0; i < messageList.length; i++) {
        var message = messageList[i];
        var li = document.createElement("li");
        var a = document.createElement("a");
        var text = document.createTextNode("Nadawca: " + message.fullName);
        a.appendChild(text);
        a.setAttribute('onclick', showMessage(message));
        list.appendChild(li);
        //list.innerHTML += "<li><a href="showMessage(message)"><h2>Nadawca: " + message.fullName + " 
        //</h2></a></li>";
    }
    //list = document.getElementById("listOfTask");
}
function showMessage(message) {
    window.sessionStorage.setItem("message", JSON.stringify(message));
    window.location.href = 'message.html';
}

In the code above, the showMessage () function is immediately called when the array is initialized. How to make it run only after clicking on a row?

I could add an id attribute to the (a) or (li) element in the init () function, but how to find it later and use it in this code:

var a = document.getElementById('1');
a.addEventListener('click', function() {
    window.sessionStorage.setItem("message", JSON.stringify(messageList[0]));
    window.location.href = 'message.html';
});

Solution

  • I found a way to solve this problem. Using this code fragment, we can call a function for a specific element in a dynamically created list.

    function init() {
        for (var i = 0; i < messageList.length; i++) {
            var message = messageList[i];
            list.innerHTML += "<li id="+i+"><a onClick="+
            "><h2>Nadawca: " + message.fullName + "</h2></a></li>";
        }
    
        //$(document).on("click", "ui-content", function(){ alert("hi"); });
        $(document).ready(function() {
    
            $(document).on('click', 'ul>li', function() {  
                var idName = $(this).attr('id');
                showMessage(messageList[idName]);
            });
        });
    }