Devid Farinelli Devid Farinelli - 7 months ago 54
Javascript Question

CSS/JS: Change opacity on swipe

I want to change the opacity of an element while swiping on it.

I would like to achieve an animation similar to the one in the snippet, that is applied gradually depending on how much my finger/cursor has dragged the element while swiping.

EDIT: The animation is the same as clearing a notification in Android

  • My first idea has been to handle the drag event and change the opacity depending on the position of the element and the width of the screen. Is this a good solution? Is there a better one, maybe CSS only?

I'm using ionic (my element is a ion-item), so anything related to ionic/angular1 could be good too.

div.animated {
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 31px;
animation: right 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: linear;

.back {
width: 100px;
height: 100px;
border: 1px solid blue;
position: fixed;
top: 30px;
left: 50px;

@keyframes right {
0% {
left: 0px;
opacity: 0.1;
50% { opacity: 1;}
100% {left: 100px;opacity:0.1}

The blue frame is the screen and the red square is the dragged element
<div class="animated"></div>
<div class="back"></div>


Ansrew's is very useful. In Ionic it is easier to use onDrag and onRelease directives.

<ion-item on-drag="onDrag($event)" on-release="onRelease($event)" /> 

And use these methods to style the ion-item:

function onDrag (e) {
    var element = e.currentTarget.childNodes[0];
    var screenW = element.offsetWidth;
    var threshold = screenW * 0.16;

    var delta = Math.abs(e.gesture.deltaX);

    if(delta >= threshold) {
        var normalizedDragDistance = (Math.abs(delta) / screenW);
        var opacity = 1 - Math.pow(normalizedDragDistance, 0.7); = opacity;
    } else {
        e.currentTarget.childNodes[0].style.opacity = 1;

function onRelease (e) {
    e.currentTarget.childNodes[0].style.opacity = 1;