6

I'm using the ngx-owl-carousel-o library in Angular. Each carousel item is created as a div with a (click) event. The problem I had is that when dragging the carousel it would always trigger the click event undesirably i.e click should only trigger when not dragging.

<owl-carousel-o [options]="customOptions" (dragging)="on_carouselDrag($event.dragging)">
    <ng-container *ngFor="let item of items">
        <ng-template carouselSlide>
            <div (click)="on_itemSelected(item)">
                <!-- ... -->
            </div>
        </ng-template>
    </ng-container>
</owl-carousel-o>

I've made a solution that seems to work but I'm unsure if its an appropriate application for using setTimeout. I'm basically just using it to delay the end of the on_carouselDrag to make sure the on_vendorSelected triggers first.

on_itemSelected(item: string): void {
  if(!this.isDragging){
    // ...
  }
}

on_carouselDrag(dragging: boolean){
  setTimeout(() => {
    this.isDragging = dragging;
  }, 10 )
}

Any comments if this approach could be improved would be appreciated.

Jnr
  • 1,504
  • 2
  • 21
  • 36

1 Answers1

0

I used a similar timer solution to prevent click on drag - but I had a simple 'onclick' on the individual carousel elements. I used the plugins triggers to determine when the dragging had begun and ended:

<div onclick="if(owl_is_dragging){ return; } do_something_otherwise();">

<script>
    let owl_is_dragging = false;
    
     $(document).ready(function(){
    
            // Owl-carousels
            let owl = $('.owl-carousel');
    
            owl.on('drag.owl.carousel', function(event) {// bound to 'this.trigger("drag")'
                owl_is_dragging = true;
            });
    
            owl.on('dragged.owl.carousel', function(event) {// bound to 'this.trigger("dragged")'
                setTimeout(function() {
                    owl_is_dragging = false;
                }, 100);
    
            });
    });

</script>

I think there are many other custom solutions to this. Like a timer on the mousedown/touchstart/ mouseup/touchend that could simply determine if the event is indeed a click or a drag. Other dragging detection could be used. But for sure built in owl globals like 'isdragging' 'isdonedragging' OR 'preventClickOnDrag', could be helpful.

TV-C-1-5
  • 680
  • 2
  • 13
  • 19