WhilseySoon
WhilseySoon

Reputation: 322

Holding a mouse on enter

So I've got this JS program: http://codepen.io/anon/pen/avgQVa

$('.divider').draggable({
  axis: 'x',
  drag: function(e, ui) {
    $('.right').width(100 - ui.position.left);
    $('.yellow').css('right', ui.position.left);
  }
});

I can reveal red rect by moving the grey divider to the right, but I need this divider to follow my mouse whenever I enter this block. How do I do this?

Upvotes: 5

Views: 81

Answers (1)

Lucas Pottersky
Lucas Pottersky

Reputation: 1919

// Handle the mouse move event on the parent div
$( "div:first" ).mousemove(function(e) {
  // calculate the mouse position relative to the div element position on the page
  var x = e.pageX - $(this).offset().left;  
  $('.divider').css('left', x);
  $('.left').css('width', x);
});

In order for it to work, I had to tweak the CSS too:

.left {
  left: 0px;
 /* This makes the left div render "above" the others, so when we change its width it shows up */
  z-index: 1; 
}

Demo: http://codepen.io/anon/pen/epwQLr

Upvotes: 4

Related Questions