0

im strugling with this problem that when I add a dropdown-submenu via innerHTML, the event onclick that I made isn't firing. But when I add that dropdwon-submenu directly in the HTML, the event works fine. There's my code if you wanna try it.

var bookmarkMenu = document.getElementById("btnBookmarkMenu");

bookmarkMenu.innerHTML = '<li class="dropdown-item dropdown-submenu"><a href="#" data-toggle="dropdown">Submenu-1</a><ul class="dropdown-menu"><li class="dropdown-item"><a href="#">Item-1</a></li><li class="dropdown-item"><a href="#">Item-2</a></li><li class="dropdown-item"><a href="#">Item-3</a></li></ul></li>' + bookmarkMenu.innerHTML;

$('.dropdown-submenu > a').on("click", function(e) {
    var submenu = $(this);
    $('.dropdown-submenu .dropdown-menu').removeClass('show');
    submenu.next('.dropdown-menu').addClass('show');
    e.stopPropagation();
});
    
$('.dropdown').on("hidden.bs.dropdown", function() {
    // hide any open menus when parent closes
    $('.dropdown-menu.show').removeClass('show');
});
.dropdown-submenu {
    position: relative;
}
  
.dropdown-submenu .dropdown-menu {
    top: 0;
    left: 100%;
    margin-top: -1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex align-items-center"> 
    <div class="dropdown">
        <a href="#" id="menu" data-toggle="dropdown" class="droptown-toggle btn btn-light-primary btn-sm">
            <i class="fas fa-bookmark"></i><span id="button-bookmark">Bookmarks</span>
        </a>
        <ul class="dropdown-menu" id="btnBookmarkMenu">
                                            
        </ul>
    </div>      
</div>

I'm using Bootstrap 4 and I tried to do a simple dropdown with items that are dropdowns too, but I cant make this event fire when I insert the items with innerHTML, I need to do it with innerHTML because I'm getting the data of the items dinamicaly

David
  • 208,112
  • 36
  • 198
  • 279
sush
  • 1
  • 1
  • You are trying to perform your click function with something like jQuery. Is jQuery correctly loaded ? – Elias Nov 28 '22 at 13:33

1 Answers1

0

Problem: When the events are registered - meaning your javascript code run, the element still not exist in the DOM.

Solution: you can bind the listener string to the element like onclick="someFunc(), or re-run your javascript block of the listener

Yosi Leibman
  • 386
  • 3
  • 16