1

I have an element that is draggable via jQuery UI's .draggable(). How can I make the opacity of that element less as the element is being dragged?

So it looks like it is fading out while being dragged?

I also have revert set to true, and I want it to return to full opacity as and if the revert starts and is happening.

Here is my jQuery code:

$('#draggable').draggable({
    axis: 'x',
    revert: true,
    drag:function(event, ui){
        if(ui.position.left>0){
            console.log("moving right");
            // fade out / make opacity less as drag moves right or ui.position.left becomes higher.
        }
    }
});

Here is a JS Fiddle with the code: http://jsfiddle.net/EybmN/1/

I am wondering and hoping someone can help me figure out how to gradually fade out / make the opacity less of object being dragged as it is being dragged. But if revert occurs and the item start sliding back to its original place then return the opacity back to full.

I would greatly appreciate any and all help!

Thanks in Advance!

Django Johnson
  • 1,383
  • 3
  • 21
  • 40

2 Answers2

5

Something like :

$('#draggable').draggable({
    axis: 'x',
    revert: true,
    drag:function(event, ui){
        ui.helper.css('opacity', 1-ui.position.left/ $(window).width());
    }
});

FIDDLE

EDIT:

to make the draggable element change opacity on revert as well, we have to hook into that event:

$('#draggable').draggable({
    axis: 'x',
    revert: function(valid) {
        if (!valid) {
            $(this).animate({opacity:1}, 'fast').animate(this.originalPosition);
            return true;
        }
        return false;
    },
    drag:function(event, ui){
        ui.helper.css('opacity', 1-ui.position.left/ $(window).width());
    }
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • One problem, when the revert happens, the opacity isn't returned to a 100%. I need it to fade out when being dragged left or right. But while the revert happens, the opacity needs to climb back to 100%. – Django Johnson Sep 15 '13 at 19:45
  • @DjangoJohnson - added a solution for that as well ! – adeneo Sep 15 '13 at 20:02
  • Awesome, thank you! One more question: how can I have the element fade out when it is being dragged left or being dragged right? And also return to full opacity on revert? – Django Johnson Sep 15 '13 at 20:05
  • You'll have to figure out what direction the element is dragged in, and then use position.left / .right based on that ? – adeneo Sep 15 '13 at 20:31
0

Something like this?

http://jsfiddle.net/EybmN/2/

$('#draggable').draggable({
    axis: 'x',
    revert: true,
    drag:function(event, ui){
        if(ui.position.left>0){
        console.log("moving right");
        $(this).css("opacity", (100-ui.position.left)/100);
        }
    }
});
Alexander Scholz
  • 2,100
  • 1
  • 20
  • 35