简体   繁体   中英

Click event doesn’t fire after browser resize

I'm currently using slick , a carousel. When the browser is resized below a certain threshold, I have the carousel set to unslick (meaning it stops being a carousel and each carousel panel is displayed statically one on top of another). The setting is this:

responsive:[{
  breakpoint: 992,
  settings: "unslick"
}]

It works great. However, I also have a .click function that's called when an element in the carousel is clicked on. Something like:

$(document).ready(function(){
  $('#linkInCarousel').click(function(){
    console.log('success');
  });
}

The .click function works on initial loading of the page, but if the page is resized, it no longer does. Any ideas?

The plugin may be replacing the HTML which causes it to lose the event handlers assigned to those DOM elements. Instead, try delegating the events to the document, like this:

$(document).ready(function(){
  $(document).on('click', '#linkInCarousel', function(){
    console.log('success');
  });
};

What this does is lets the document (which never gets removed) handle the event and checks to see if the actual target of the event matches the selector, in this case '#linkInCarousel'. This way, even if the element is added after page load the handler will fire properly.

In general it can be beneficial to use delegation when dealing with a list of elements, so you're only adding one event handler as opposed to creating the handlers for every element. Read more about it here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM