Search code examples
javascriptcssdraggable

Dynamically change element background (gradient)


Consider situation http://codepen.io/anon/pen/JdGYBN

I need to change background color of card "draggable" dynamically while dragging element.

But card's background should change in accordance with line gradient color.

background: linear-gradient(to bottom,  rgba(255,2,2,1) 0%,rgba(242,255,0,1) 34%,rgba(16,255,0,1) 66%,rgba(255,255,255,1) 100%);

Not like card "badone" that consist all gradients.

Therefore, in top of the container card background should be mostly red. At bottom mostly white.

Any suggestions how to implement this? Hope you understand me.


Solution

  • The trick is to set background-size of the dragged element to size of container and background-attachment to fixed like so:

    #draggable {
      background: /* linear gradient */;
      background-size: 900px 500px;
      background-attachment: fixed;
    }
    

    The draggability plugin uses translate while dragging and only updates element position after drop. This causes the background to stick while dragging. The jQuery UI Draggable changes positions while dragging giving the desired effect.

    I've adjusted your demo accordingly.