Reputation:
I want users to be able to click on an element and also highlight the same element. If they click it should behave like a click but if they mousedown and select some text it should not behave like a click (since that is not a click). jQuery fires a click if you mousedown and then 1 million years later mouse up. I realize you can do:
$myElm.on("mousedown.tmp", function () {
$myElm.off("mouTsedown.tmp");
$myElm.on("mouseup", function () {
$myElm.off("mouseup.tmp")
}
}); //
correct for spelling and factor in other event handlers. i mean roughly speaking.
I don't want to use a plugin.
Upvotes: 6
Views: 1605
Reputation: 15828
Keep track of the mouse position on mousedown. Compare it with the mouse position on mouseup. If the mouse has moved a certain number of pixels, prevent the default event.
event.preventDefault();
Upvotes: 0
Reputation: 1903
var mydate = new Date()
var downtime;
$('#div').on('mousedown', function() {
downtime = mydate.getTime();
});
$('#div').on('mouseup', function() {
if((mydate.getTime() - downtime) < 500) {
//perform click function
}
else {
//highlight text
}
});
Upvotes: 1
Reputation: 335
Here's my fiddle solution, I hope it's what your looking for.
I'm using mouseup()
for the highlighting of the text. And in the click event I'm checking to see if text has been selected.
var selection = window.getSelection();
if(selection == 0)
// Click event code goes here
Below is the code.
$(function(){
$("div").click(function(){
var selection = window.getSelection();
if(selection == 0)
{
// click event code goes here.
}
});
$("div").mouseup(function(){
document.execCommand("BackColor", false, "yellow"); // highlight selected text
document.designMode = "off";
});
$("div").mousedown(function(){
document.designMode = "on"; // Turn on design mode
});
});
Upvotes: 4