mardi 28 septembre 2021

how to attach onclick function on every list item which is created through Javascript Dynamically | Vanilla Javascript [duplicate]

I am trying to create an animated side nav bar through vanilla javascript. the problem I am facing is to attach an on click function on every li element and I have already tried addEventListener but it is running that function immediately can I somehow get the expected result that on every single list item on click function is attached when anyone click on that list item then that function should run.

Code and screenshot is attach below

var navObject = {
"item1":[],
"item2":[],
"item3":[],
"item4":[],
"item5":[],
"item6":[]
}

console.log(Object.keys(navObject))

function next(){
console.log("welcome")
}

const container = document.getElementById('container')
const ul = document.createElement("ul")
objectKeys = Object.keys(navObject)

for (let i =0; i<=objectKeys.length-1;i++){
 
const li = document.createElement('li')
li.innerHTML = objectKeys[i]
li.addEventListener("click",next())
ul.appendChild(li)
}

container.appendChild(ul)

enter image description here




Aucun commentaire:

Enregistrer un commentaire