Brendon
Brendon

Reputation: 59

Dragging elements

Im just wondering whether its possible to drag images/elements (whether inside a div or not) where the image/element is dragged to the far left and comes in from the right side of the screen - therefore dragging the image/element left to get the same result, or vice versa.

Similar to the google maps (on zoom level 1) the user can continuously drag the image left or right, and those images are on a continuous loop.

If so, what languages would you recommend using? javascript?

I hope this makes sense.

Many thanks

Upvotes: 1

Views: 146

Answers (2)

Plato
Plato

Reputation: 11052

You can add event handlers to any element, including your images, that execute code while dragging. I apologize for not providing a complete working solution, I am pressed for time, I hope this helps as a starting point

var myGlobals = {
  state: {
    dragging: false;
  }
};

$('.carouselImg').on('mousedown', function(e){
  myGlobals.state.dragging = true;
});

$(window).on('mouseup', function(e){
  // stop movement even if mouseup happens somewhere outside the carousel
  myGlobals.state.dragging = false; 
});

$(window).on('mousemove', function(e){
  // allow user to drag beyond confines of the carousel
  if(myGlobals.state.dragging == true){
    recalculateCarouselPosition(e);
  }
});

function recalculateCarouselPosition(e){
  // These fun bits are left as an exercise for the reader
  // the event variable `e` gives you the pixel coordinates where the mouse is
  // You will have to do some math to determine what you need to do after this drag.
  // You may want to store the coordinates of the initial click in 
  // `myGlobals.dragStart.x, .y` or similar so you can easily compare them
  // You will probably set a negative CSS margin-left property on some element
  // of your carousel.
  // The carousel will probably have overflow:hidden.
  // You will also have to manipulate the DOM, by adding a duplicate image to the
  // opposite end and deleting the duplicates once they have scrolled out of view

};

Upvotes: 0

Flight Odyssey
Flight Odyssey

Reputation: 2287

This is certainly possible using Javascript. Just have two copies of the image, and as you slide the images left, move the second copy to the right side. (Or vice versa if sliding right).

Upvotes: 1

Related Questions