I’m using Swiper to show some slides, and I have some events that run on mouseup
, but they are not working with Swiper. When I click the swiper container nothing happens.
You can see it in this example, the alert doesn’t work:
document.body.addEventListener('mouseup', () => { alert('mouseup'); });
const swiper = new Swiper('.swiper-container', {
direction: 'horizontal',
pagination: {
el: '.swiper-pagination',
},
});
.swiper-container {
width: 80vw;
height: 80vh;
}
html, body {
width: 100%;
height: 100%;
}
#m {
height: 400px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.2/css/swiper.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.2/js/swiper.min.js"></script>
<div id="m">
<div class="swiper-container">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
...
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>
<!-- If we need navigation buttons -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
<!-- If we need scrollbar -->
<div class="swiper-scrollbar"></div>
</div>
</div>
I think it does it to avoid events interfering with the Swipe, but if the user doesn’t swipe, just clicks, I would like to trigger my events.
How can I do that?
Swiper does that on purpose to avoid events from messing up the swipe. One way to change this behavior is to trick it to think that your elements are form elements. Internally it does a check and if the target is a form element it allows the click.
You can change
Swiper
sinit
function to set the form elements data:With that it will no longer lock
mouseup
events.The following example shows an event with
alert
, it works but causes ux problems with the swiping.For me, just adding this
touchStartPreventDefault: false
on Swiper options solved my issues with "mousedown" and "mouseup".Update Swiper and add
touchStartPreventDefault: true
in swiper options