I know the current code is bad practice because is too generic, but how can I make it better?
Context: im targeting a set of links with JS, and need to clear/ remove user input in a search box upon click on any of those links.
function clearSearchInput(event) {
document.getElementById("searchbox").value = "";
};
var links = document.getElementsByClassName("mystyle");
for (var z = 0; z < links.length; z++) {
links[z].addEventListener('click', clearSearchInput );
}
Honestly, this code works just fine. The only thing it wouldn’t help with is if any of the elements with a mystyle class are dynamically put on the page (as in a data driven web app), which you’d have to do a bit more to not have to rebind a click event to every single element every time. But if those elements are loaded from page load and don’t change, this works perfectly!
Thank you for the input Question should this code cause problems if other click event listeners target those? What are the good code practices about it? I should had mentioned I started to wonder because in mobile this list of links actually don’t go to the link referenced anchor position when a filter is in place… so clicking once removes the search input/and the filtered links, but it doesn’t as well go to the anchor unless a do a second click once the search is removed.