天道酬勤,学无止境

Prevent text selection after double click

Question

I'm handling the dblclick event on a span in my web app. A side-effect is that the double click selects text on the page. How can I prevent this selection from happening?

Answer1
function clearSelection() {
    if(document.selection && document.selection.empty) {
        document.selection.empty();
    } else if(window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
    }
}

You can also apply these styles to the span for all non-IE browsers and IE10:

span.no_selection {
    user-select: none; /* standard syntax */
    -webkit-user-select: none; /* webkit (safari, chrome) browsers */
    -moz-user-select: none; /* mozilla browsers */
    -khtml-user-select: none; /* webkit (konqueror) browsers */
    -ms-user-select: none; /* IE10+ */
}
Answer2

In plain javascript:

element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false);

Or with jQuery:

jQuery(element).mousedown(function(e){ e.preventDefault(); });
Answer3

To prevent text selection ONLY after a double click:

You could use MouseEvent#detail property. For mousedown or mouseup events, it is 1 plus the current click count.

document.addEventListener('mousedown', function (event) {
  if (event.detail > 1) {
    event.preventDefault();
    // of course, you still do not know what you prevent here...
    // You could also check event.ctrlKey/event.shiftKey/event.altKey
    // to not prevent something useful.
  }
}, false);

See https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

Answer4

FWIW, I set user-select: none to the parent element of those child elements that I don't want somehow selected when double clicking anywhere on the parent element. And it works! Cool thing is contenteditable="true", text selection and etc. still works on the child elements!

So like:

<div style="user-select: none">
  <p>haha</p>
  <p>haha</p>
  <p>haha</p>
  <p>haha</p>
</div>
Answer5

A simple Javascript function that makes the content inside a page-element unselectable:

function makeUnselectable(elem) {
  if (typeof(elem) == 'string')
    elem = document.getElementById(elem);
  if (elem) {
    elem.onselectstart = function() { return false; };
    elem.style.MozUserSelect = "none";
    elem.style.KhtmlUserSelect = "none";
    elem.unselectable = "on";
  }
}
Answer6

For those looking for a solution for Angular 2+.

You can use the mousedown output of the table cell.

<td *ngFor="..."
    (mousedown)="onMouseDown($event)"
    (dblclick) ="onDblClick($event)">
  ...
</td>

And prevent if the detail > 1.

public onMouseDown(mouseEvent: MouseEvent) {
  // prevent text selection for dbl clicks.
  if (mouseEvent.detail > 1) mouseEvent.preventDefault();
}

public onDblClick(mouseEvent: MouseEvent) {
 // todo: do what you really want to do ...
}

The dblclick output continues to work as expected.

Answer7

or, on mozilla:

document.body.onselectstart = function() { return false; } // Or any html object

On IE,

document.body.onmousedown = function() { return false; } // valid for any html object as well
Answer8

Old thread, but I came up with a solution that I believe is cleaner since it does not disable every even bound to the object, and only prevent random and unwanted text selections on the page. It is straightforward, and works well for me. Here is an example; I want to prevent text-selection when I click several time on the object with the class "arrow-right":

$(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});});

HTH !

Answer9

If you are trying to completely prevent selecting text by any method as well as on a double click only, you can use the user-select: none css attribute. I have tested in Chrome 68, but according to https://caniuse.com/#search=user-select it should work in the other current normal user browsers.

Behaviorally, in Chrome 68 it is inherited by child elements, and did not allow selecting an element's contained text even if when text surrounding and including the element was selected.

Answer10

To prevent IE 8 CTRL and SHIFT click text selection on individual element

var obj = document.createElement("DIV");
obj.onselectstart = function(){
  return false;
}

To prevent text selection on document

window.onload = function(){
  document.onselectstart = function(){
    return false;
  }
}
Answer11

If you are using Vue JS, just append @mousedown.prevent="" to your element and it is magically going to disappear !

Answer12

I had the same problem. I solved it by switching to <a> and add onclick="return false;" (so that clicking on it won't add a new entry to browser history).

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐
  • How to prevent a double-click using jQuery?
    Question I have a button as such: <input type="submit" id="submit" value="Save" /> Within jQuery I am using the following, but it still allows for double-clicks: <script type="text/javascript"> $(document).ready(function () { $("#submit").one('click', function (event) { Any idea on how I can prevent double-click? Answer1 jQuery's one() will fire the attached event handler once for each element bound, and then remove the event handler. If for some reason that doesn't fulfill the requirements, one could also disable the button entirely after it has been clicked. $(document).ready(function () { $
  • Prevent double submission of forms in jQuery
    Question I have a form that takes a little while for the server to process. I need to ensure that the user waits and does not attempt to resubmit the form by clicking the button again. I tried using the following jQuery code: <script type="text/javascript"> $(document).ready(function() { $("form#my_form").submit(function() { $('input').attr('disabled', 'disabled'); $('a').attr('disabled', 'disabled'); return true; }); }); </script> When I try this in Firefox everything gets disabled but the form is not submitted with any of the POST data it is supposed to include. I can't use jQuery to submit
  • Disable double-tap “zoom” option in browser on touch devices
    Question I want to disable the double-tap zoom functionality on specified elements in the browser (on touch devices), without disabling all the zoom functionality. For example: One element can be tapped multiple times for something to happen. This works fine on desktop browsers (as expected), but on touch device browsers, it will zoom in. Answer1 Note (as of 2020-08-04): this solution does not appear to work in iOS Safari v12+. I will update this answer and delete this note once I find a clear solution that covers iOS Safari. CSS-only solution Add touch-action: manipulation to any element on
  • How to disable copy/paste from/to EditText
    Question In my application, there is a registration screen, where i do not want the user to be able to copy/paste text into the EditText field. I have set an onLongClickListener on each EditText so that the context menu showing copy/paste/inputmethod and other options does not show up. So the user won't be able to copy/ paste into the Edit fields. OnLongClickListener mOnLongClickListener = new OnLongClickListener() { @Override public boolean onLongClick(View v) { // prevent context menu from being popped up, so that user // cannot copy/paste from/into any EditText fields. return true; } }; But
  • Does ASP.NET Web Forms prevent a double click submission?
    Question I'm working on an ASP.NET 4.0 Web Forms project, after a break of about 5 years, and I'm confused about the submit behaviour. In the click event of a button, I sleep the thread so that I can click the submit button multiple times. From what I can tell, ASP.NET is preventing the click event being called more than once. Is this true? BTW: I've turned off javascript for this test. Answer1 "ASP.NET is preventing the click event being called more than once. Is this true?" No, actually what is happening to you is that your events are blocked by the lock of the session. (What session is on
  • Android Preventing Double Click On A Button
    Question What is the best way to prevent double clicks on a button in Android? Answer1 Disable the button with setEnabled(false) until it is safe for the user to click it again. Answer2 saving a last click time when clicking will prevent this problem. i.e. private long mLastClickTime = 0; ... // inside onCreate or so: findViewById(R.id.button).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // mis-clicking prevention, using threshold of 1000 ms if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){ return; } mLastClickTime = SystemClock.elapsedRealtime()
  • How to do double-click prevention in JSF
    Question We have a few search pages that run against a lot of data and take a while to complete. When a user clicks on the search button, we'd like to not allow them to submit the search result a second time. Is there a best practice for doing "double-click" detection/prevention in JSF? The PrimeFaces component seems like it can do what we want as it will disable the UI for a period of time between when the search button is clicked and when the search completes, but is there a more generic strategy we can use (perhaps something that isnt reliant on PrimeFaces)? Ideally, any click of the button
  • Disable button on form submission
    Question I have a button that I would like to disable when the form submits to prevent the user submitting multiple times. I have tried naively disabling the button with javascript onclick but then if a client side validation that fails the button remains disabled. How do I disable the button when the form successfully submits not just when the user clicks? This is an ASP.NET form so I would like to hook in nicely with the asp.net ajax page lifecycle if possible. Answer1 Give this a whirl: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI
  • How to automatically select all text on focus in WPF TextBox?
    Question If I call SelectAll from a GotFocus event handler, it doesn't work with the mouse - the selection disappears as soon as mouse is released. EDIT: People are liking Donnelle's answer, I'll try to explain why I did not like it as much as the accepted answer. It is more complex, while the accepted answer does the same thing in a simpler way. The usability of accepted answer is better. When you click in the middle of the text, text gets unselected when you release the mouse allowing you to start editing instantly, and if you still want to select all, just press the button again and this
  • Mobile Safari Autofocus text field
    Question In Mobile Safari I am unable to focus onto a text field after setting a delay period. I'm attaching some example code showcasing the issue. If, onclick of the button, you trigger .focus(), everything works as expected. If you hang the focus on a callback, like the setTimeout function, then it fails ONLY in mobile safari. In all other browsers, there is a delay, then the focus occurs. Confusingly, the "focusin" event is triggered, even in mobile safari. This (and ~similar~ comments in SO) make me think that it's a mobile safari bug. Any guidance will be accepted. I've tested in the
  • What's the difference between disabled=“disabled” and readonly=“readonly” for HTML form input fields?
    Question I have read a bit on this, but I can't seem to find anything solid about how different browsers treat things. Answer1 A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn't editable and isn't sent on submit. Another difference is that readonly elements can be focused (and getting focused when "tabbing" through a form) while disabled elements can't. Read more about this in this great article or the definition by w3c. To quote the important part: Key Differences The Disabled attribute Values for disabled form elements are not
  • Stop form from submitting , Using Jquery
    Question I'm trying to stop my form from submitting if a validation fails. I tried following this previous post but I doesn't work for me. What am I missing? <input id="saveButton" type="submit" value="Save" /> <input id="cancelButton" type="button" value="Cancel" /> <script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $("form").submit(function (e) { $.ajax({ url: '@Url.Action("HasJobInProgress", "ClientChoices")/', data: { id: '@Model.ClientId' }, success: function (data) { showMsg(data, e); }, cache
  • How to prevent user to enter text in textarea after reaching max character limit
    Question I want to prevent user to enter text in textarea once it reaches a max character limit. What was happening that when i reached to max limit then my text-area scroll-bar moved to top I somehow prevent this with this code. jQuery(document).ready(function($) { $('textarea.max').keyup(function() { var $textarea = $(this); var max = 400; if ($textarea.val().length > max) { var top = $textarea.scrollTop(); $textarea.val($textarea.val().substr(0, max)); $textarea.scrollTop(top); } }); }); //end if ready(fn) But i also want that after reaching max limit user unable to type anything in the
  • Prevent a webpage from navigating away using JavaScript
    Question How to prevent a webpage from navigating away using JavaScript? Answer1 Using onunload allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload will interrupt navigation: window.onbeforeunload = function() { return ""; } Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden. In older browsers you could specify the message to display in the prompt: window.onbeforeunload = function() { return "Are you sure you want to navigate
  • Performing a copy and paste with Selenium 2
    Question Is there any way to perform a copy and paste using Selenium 2 and the Python bindings? I've highlighted the element I want to copy and then I perform the following actions copyActionChain.key_down(Keys.COMMAND).send_keys('C').key_up(Keys.COMMAND) However, the highlighted text isn't copied. Answer1 To do this on a Mac and on PC, you can use these alternate keyboard shortcuts for cut, copy and paste. Note that some of them aren't available on a physical Mac keyboard, but work because of legacy keyboard shortcuts. Alternate keyboard shortcuts for cut, copy and paste on a Mac Cut =>
  • How to increase font size in the Xcode editor?
    Question To increase font-size in Xcode is a pain. Answer1 For Xcode 4.1 Still a huge pain. Poor UI design (But my mindset does not seem to match the mindset of software engineers that make 100+ character variable and method names. Enough of my complaining) I'll modify a previous post for the current version. Close any projects you have open in Xcode (Otherwise the Font window will be inaccessible while a project is open.) Go to XCode > Preferences > Fonts & Color From the 'Theme' box select the theme you want to modify (or select the theme you want to modify and click the "+" button at the
  • Jquery bind double click and single click separately
    Question Is there something in jquery that would allow me to differentiate between behavior on double click and single click? When I bind both to same element only the single click gets executed. Is there a way that wait for some time before execution of the single click to see if the user clicks again or not? Thanks :) Answer1 I found that John Strickler's answer did not quite do what I was expecting. Once the alert is triggered by a second click within the two-second window, every subsequent click triggers another alert until you wait two seconds before clicking again. So with John's code, a
  • Detect which word has been clicked on within a text
    Question I am building a JS script which at some point is able to, on a given page, allow the user to click on any word and store this word in a variable. I have one solution which is pretty ugly and involves class-parsing using jQuery: I first parse the entire html, split everything on each space " ", and re-append everything wrapped in a <span class="word">word</span>, and then I add an event with jQ to detect clicks on such a class, and using $(this).innerHTML I get the clicked word. This is slow and ugly in so many ways and I was hoping that someone knows of another way to achieve this. PS
  • Selecting text on focus using jQuery not working in Safari and Chrome
    Question I have the following jQuery code (similar to this question) that works in Firefox and IE, but fails (no errors, just doesn't work) in Chrome and Safari. Any ideas for a workaround? $("#souper_fancy").focus(function() { $(this).select() }); Answer1 It's the onmouseup event that is causing the selection to get unselected, so you just need to add: $("#souper_fancy").mouseup(function(e){ e.preventDefault(); }); Answer2 $('#randomfield').focus(function(event) { setTimeout(function() {$('#randomfield').select();}, 0); }); Answer3 This works fine for input type="text" elements. What kind of
  • How to run .jar file by double click on Windows 7 64-bit?
    Question Running a .jar file in a command line works fine, but i am not able to run any .jar file by double clicking on my Windows 7 (64). It seems nothing happens after the double click. I tried the ftype hint, no success: ftype jarfile="C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %* I reinstalled the JDK 7 64-bit, no success. Any idea? Answer1 What is listed in right-click-> Open With ? Is some other program listed as the default program ? Is a Java Runtime listed ? If a Java Runtime is listed, you can open with it, and make it the default program to run with. ie, Right Click ->