Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery text selection event

Tags:

jquery

events

I have the following event handling code:

$('#main').delegate('.slide', 'click', function () {
  slideshow.next();
});
$('#main').delegate('a', 'click', function (e) {
  e.stopPropagation();
});

.slide is a large div with content. slideshow.next() is called when .slide is clicked, except when a link is clicked, in which case stopPropagation(), and .slide never receives the click event.

I'd like to make it possible to select text on the slide. At the moment, if I click and drag, when I release the mouse the selection works but .slide registers the click and fires the slideshow.next() function. Is there an event I can intercept?

The page is available here.


Edit: Interestingly, if the selection spans more than one HTML element, click isn't fired, but it the selection is within an element, it is fired.


Edit2: Ok, here's my solution:

function setupHandlers() {
  var prevX = 0;
  var prevY = 0;

  $('#main').delegate('.slide', 'click', function (e) {
    var clickTolerance = 2;
    var dx = Math.abs(e.pageX - prevX);
    var dy = Math.abs(e.pageY - prevY);
    //if mouse has moved less than two pixels in any direction this is a click
    if (dx < clickTolerance && dy < clickTolerance) {
      slideshow.next();
    }
  });
  $('#main').delegate('.slide', 'mousedown', function (e) {
    prevX = e.pageX;
    prevY = e.pageY;
  });
  $('#main').delegate('a', 'click', function (e) {
    //Clicks on links shouldn't fire '.slide'.click() above
    e.stopPropagation();
  });
}
like image 708
Skilldrick Avatar asked Jan 26 '11 23:01

Skilldrick


1 Answers

What is the difference between a single click and a click that selects text ?

I would say it could either relate to the time passed between the down click and the upclick of the mouse. Alternatively and perhaps more importantly it could be diagnosed by difference in the screen position of the mouse at the time of the down click and at the time of the mouse up event.

When the mouseDown event is fired record the event.pageX and event.pageY values. When the mouseUp event is fired compare the stored x,y coords with the current. If they are different it was a text select... do nothing. If they are the same, swap your page.

Not sure how to implement this in JScript unfortunately ;)

like image 151
Eric Coffin Avatar answered Oct 31 '22 20:10

Eric Coffin