Search code examples
javascriptcarouselowl-carousel

Click event on owl-item not triggered in owl carousel 1.3.3 when navigation is true


Anyone help me on owl-carousel. Click event on item not triggered in owl carousel v1.3.3 while navigation is on. My code is:

$(document).ready(function () {
        $('.owl-carousel').owlCarousel({
          items: 3,
          mouseDraggable: false,
          navigation: true,
          scrollPerPage: true,
          rewindNav: false,
          pagination: false,
          navigationText: ['<span>&#60;</span>', '<span>&#62;</span>'],
        })
        $('.owl-carousel').on('click', '.owl-item>div', function () {
          alert('click');
        })
      })

Solution

  • $(document).ready(function() {
      var owl = $('.owl-carousel');
      owl.owlCarousel({
        margin: 10,
        navigation: true,
        loop: true,
      })
      $('.owl-carousel').on('click', '.owl-item>div', function () {
              alert('click');
      })
    })
    .owl-carousel .item {
        height: 10rem;
        background: #4DC7A0;
        padding: 1rem;
        margin: 1rem;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.theme.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js"></script>
    
    
    
    <div class="owl-carousel owl-theme">
      <div class="item">
        <h4>1</h4>
      </div>
      <div class="item">
        <h4>2</h4>
      </div>
      <div class="item">
        <h4>3</h4>
      </div>
      <div class="item">
        <h4>4</h4>
      </div>
      <div class="item">
        <h4>5</h4>
      </div>
      <div class="item">
        <h4>6</h4>
      </div>
      <div class="item">
        <h4>7</h4>
      </div>
      <div class="item">
        <h4>8</h4>
      </div>
      <div class="item">
        <h4>9</h4>
      </div>
      <div class="item">
        <h4>10</h4>
      </div>
      <div class="item">
        <h4>11</h4>
      </div>
      <div class="item">
        <h4>12</h4>
      </div>
    </div>

    There is a good chance that owl carousel stops the propagation of events from the parent element ('.owl-carousel').

    So rather than adding the click event on '.owl-carousel' and reaching its child, add it on the child '.owl-item>div' directly.

    Update: Try this, make sure to set your event listener after the document is loaded. This gives a good enough time for your HTML to render.