0

I am trying to figure out how to setup an event listener that will work after ajax content is loaded using fetch. I'm trying to do this all with plain javascript and no jQuery.

I know with jQuery I can do something like this that will work on content that is loaded by ajax.

$('body').on('click', '#myLink', function () {
    // do stuff...
});

So my question is, how can I do something similar with just plain javascript?

In my application, I've got a login screen that shows when no session or cookie is set. Once the user logs in, javascript fetch loads a main screen and there are clickable links on that screen. So far I've had to create functions for these links with event listeners that I fire on page load and also after the fetch command.

Here is some code from my application, you can see I've got a loadScreen function which gets called elsewhere, then after it does it's work it calls the logoutFunction, this is because that link to logout is not displayed until the ajax content is loaded. However, if someone is already logged in, then the login screen will not show and the main page will load. Thus, I have the same logout function firing on page load.

function loadScreen(page){
    fetch(page)
    .then(function(res){return res.text()})
    .then(function(data){
        document.getElementById('mainWrap').innerHTML = data;
        logoutFunction();
    })  
}

function logoutFunction(){
    var logout = document.getElementById('logout');
    if(logout){
        logout.addEventListener('click',function(event){
            event.preventDefault();
            // do stuff..
        });
    }
}
logoutFunction();

All in all I'm trying to move away from jQuery and do everything with plain javascript & fetch. This is one hurdle I've been researching the past several days. I've seen some mention of mutation observer but not sure how that would work in my situation. I'm thinking that the answer is somehow with a body event listener that then fires off these other event listeners. How is jQuery doing it? I really like the elegance and simplicity of jQuery so I was hoping there is a similar method to do this.

drooh
  • 762
  • 2
  • 15
  • 36

0 Answers0