How to make a draggable handler that can change a div's css

115 Views Asked by At

I'm making a handler function
here is the demo:
http://codepen.io/iamkaikai/pen/myVzvY?editors=011

Here's my question,
The blue div's width is 0, and I use jQuery to give it a width by reading pageX when on click
However, I would like the blue div's width follows the changing of pageX instead of change only once.

My goal is to make a draggable handler that can switch red div to blue div



Here is the code:

$( "#line" ).draggable({
   containment: "#red";
});

$( document ).on( "mousemove", function( event ) {

   $( "#line" ).text( "pageX: " + event.pageX );
   $("#line").mousedown(function(){
      $("#blue").css("width", event.pageX);
   });

});

I know javascript only read the first pageX once when you click the div,
how do I make it read all the mouse position in one mouse down event?

2

There are 2 best solutions below

1
On BEST ANSWER
  1. Document denotes the whole document width :

  2. (#)line denotes the width of the #line div :

     $( document ).on( "mousemove", function( event ) {
      $( "#line" ).text( "pageX: " + event.pageX );
    });
    
    $("#line").on( "mousemove", function( event ) {
      $("#blue").css("width", event.pageX);
    });
    
0
On

Property pageX will return the result on your event, as the event mousedown is triggering for one time only.

Event mousemove will capture mouse movement on your div and trigger the event with its movement.

Check this out:

$( document ).on( "mousemove", function( event ) {
  $( "#line" ).text( "pageX: " + event.pageX );
});

$("#line").on( "mousemove", function( event ) {
  $("#blue").css("width", event.pageX);
});