event.stopPropagation() is not working, not able to stop a ul div from getting closed automatically

47 Views Asked by At

i have the following Code where, when the user types in the search box suggestion list opens. in this list there are a list of characters and each character has it's own favorite icon on click of which the it can be added or removed from the favorite list.

my issues are

when a user clicks on any <li> item or heart icon the suggestionsList gets closed automatically. It should not happen like this. what should actually happen is that if the user clicks on character name it should open another page and if the user clicks on the heart icon against a particular character, it should get added to favorite list by calling "clickFav" function and through whatever process is running the suggestionlist box should remain open. Only if the user clicks outside it, it should get closed

I tried using event.stopPropagation(); but it is not working. i want to use vanilla js ony to solve the issue

html code

<div class="search-container">
    <input class="input" type="text" id="searchInput" placeholder="Type to search">
    <ul class="suggestions" id="suggestionsList">
        
    </ul>
</div>

Js code

searchInput.addEventListener('input', () => {
    let userInput = searchInput.value.toLowerCase();
    let filterSuggestion = heroList.filter((char) => char.name.toLowerCase().startsWith(userInput));
    displaySuggestionList(filterSuggestion);
});

function displaySuggestionList(suggestion) {
    suggestionsList.innerHTML = '';
    if (suggestion.length > 0) {
        suggestion.forEach((char) => {
            let searchDiv = `
                <li data-index=${char.id} >
                    <a href="#"> ${char.name} </a>
                    <i class="fa-heart 
                        ${
                            favList ? 
                            favList.includes(char.id) ? 'fa-solid' : 'fa-regular' 
                            : 'fa-regular'
                        }
                    "></i>
                </li>`;
            suggestionsList.insertAdjacentHTML('beforeEnd', searchDiv);
        });

        // Add event listener to suggestionsList to prevent automatic closure
        suggestionsList.addEventListener('click', (event) => {
            event.stopPropagation();
        });

        // Add event listeners to <li> elements
        suggestionsList.querySelectorAll('li').forEach((li) => {
            li.addEventListener('click', () => {
                // Call the clickFav function with the corresponding data-index
                clickFav();
            });
        });

    } else {
        suggestionsList.innerHTML = '<li>No suggestions found</li>';
    }
}

function clickFav(event) {
    if (event.target.classList.contains('fa-heart')) {
        const id = event.target.parentElement.dataset.index;
        createFavAndLocal(id,event);
    }
}
0

There are 0 best solutions below