ireply ireply - 3 months ago 5
jQuery Question

Binding event listeners function, do I need to call the function later?

I'm using an api which includes these event listeners for changing the display of a div from hidden to visible.

function bindEventListeners() {
/* cart close button listener */
$('.cart .btn--close').on('click', closeCart);

/* click away listener to close cart */
$(document).on('click', function(evt) {
if((!$('.cart').length) && (!$('.js-prevent-cart-listener').length)) {

These listeners aren't working, the click away listener doesn't work and neither does the close button one. In the support docs they're just given like this but does the function bindEventListeners need to be called somewhere for them to be working or how should they listen?


You will need to call bindEventListeners() after .cart .btn--close exists. If that element exists statically on the page you should call it in the $(document).ready() handler like


Or if .cart .btn--close is created dynamically say through an ajax call then the bindEventListeners() should be done after it is loaded into the DOM.