Trying to figure out a way to use addEventListener with List.js
Order of JS loading:
1 - List.js
2 - List.js scripts file (with list js functions like creating the list etc)
3 - Main scripts file (with main JS code, including addEventListener code)
If I load the main scripts file first, then the event listener doesn't get created(i believe it gets refreshed when List.js loads and creates the different pagination pages.
With the files ordered the way I have above, the event listener only gets created and can be used for the first page of the list, if I switch to page 2,3,...they event listener doesn't get created for the button. I see that the elements for the other pages are actually dynamically created so that's why the addEventListener doesn't work.
My current solution has been to use onclick="myfunction(event)"
on all the buttons, so that when Listjs generates the list items it has the function attached inline, but though this works fine I find it a bit hacky.
I see List.js has a method called .on()
but I can't seem to get it to work either.
My code:
var menuList = new List('menu-items', {
valueNames: ['menu-item'],
page: 3,
pagination: true
});
function log_console(){
return console.log('list updated!');
} //tried this, doesn't work
//menuList.on('updated', log_console);
menuList.on('updated', function(menuList){
return console.log('list updated');
}); //this doesn't work either
From what I can get from the docs, this should be fired every whenever lists are updated, which Seems to be what happens when I switch from page 1 to page 2 of the list (it replaces the HTML).
I also tried a different event which I assume should work when I use the search box but nothing happens:
menuList.on('searchStart', function(menuList){
return console.log('list updated');
}); //doesn't log anything enither
How do I go about using this ListJs .on()
method? I'd use it to create the event listener everytime a user switches the page and the list gets generated, something like this:
menuList.on('updated', function(menuList){
const btns = document.querySelectorAll('.add-btns');
btns.forEach(button => button.addEventListener('click', myfunction));
});
My code was totally correct...I was just including the wrong JS file...since I'd made a copy that had the new changes while the one being loaded didn't.