1

I am experiencing an issue when trying to simply detect a link button click through javascript.

My nav html is spawned through javascript in this way:

INDEX.HTML:

<div id="nav">
</div>

NAV.HTML:

<div class="nav-wrapper">
    <div class="left-side">
        <div class="nav-link-wrapper">
            <a id="home-button">Home</a>
        </div>
    </div>  
</div>

INDEX.JS:

$.get('/shared/nav.html', function(data) {
    $("#nav").replaceWith(data);
});
window.onload = function() {  

    const button = document.getElementById('home-button');

    button.addEventListener('click', function() {
        console.log("clicked");
    })
}

THe javascript should execute after the html has been replaced and find the a element with "home-button" id, but button is always null for some reason... Any idea?

Thanks.

EDIT:

Tried event delegation with no luck.

INDEX.JS:

$.get('/shared/nav.html', function(data) {
    $("#nav").replaceWith(data);
});
$("#nav").on('click', 'a', function(event) {
    console.log('click.');
});

The rest of the code is identical.

EDIT 2:

Solution: replaceWith(data) in the javascript was removing the "nav" div, making it impossible to use event delegation. I changed from replaceWith to use innerHTML=... and the event delegation worked.

jackyroo
  • 99
  • 2
  • 12

0 Answers0