Languages
[Edit]
EN

JavaScript - limit element text selection on Ctrl+a or cmd+a (on select all text)

7 points
Created by:
Jacob
532

In this short article, we would like to show some simpel trick, that lets you create some element, that selection is limited to specific area. That approach is useful when we want to get specific area selectuion on Ctrl+a keys pressed on Windows, Linux or Unix or cmd+a keys pressed on MacOS.

Preview:

Element text selection limit on Ctrl+a or cmd+a keys.
Element text selection limit on Ctrl+a or cmd+a keys.

Practical example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    [tabindex] {
        outline: none;  /* only to disable outline on ficusable elements */
    }

</style>
<script>
  
  	function isApple() {
    	var expression = /(Mac|iPhone|iPod|iPad)/i;
        return expression.test(navigator.platform);
    }

    // Returns true if Ctrl or cmd keys were pressed.
    //
    function isControl(event) {
        if (isApple()) {
            return event.metaKey;
        }
      	return event.ctrlKey; // Windows, Linux, UNIX
    }
  
    // Returns true if Ctrl+a or cmd+a were pressed (all text selection).
    //
  	function isSelecting(event) {
    	if (isControl(event)) {
        	return event.key === 'a';
        }
      	return false;
    }
  
  	var selection = window.getSelection();

    // Selects all content for indicated node.
    //
  	function selectContent(node) {
    	var range = document.createRange();
        range.selectNode(node);
      	selection.empty();  
      	selection.addRange(range);
    }

    // Creates scope that limits all text selection on Ctrl+a or cmd+a keys pressed.
    //
    function createScope(node) {
      	var callback = function(event) {
          	if (isSelecting(event)) {
                event.preventDefault();
                selectContent(node);
            }
        };
      	if (node.hasAttribute('tabindex')) {
      		node.addEventListener('keydown', callback);
            return {
                remove: function() {
                    node.removeEventListener('keydown', callback);
                }
            };
        } else {
        	node.setAttribute('tabindex', 0);
            node.addEventListener('keydown', callback);
            return {
                remove: function(navigation) {
                  	if (navigation !== true) {
                    	node.removeAttribute('tabindex');
                    }
                    node.removeEventListener('keydown', callback);
                }
            };
        }
    }

</script>
</head>
<body>
  <p>Some text here...</p>
  <div id="my-text">Get focus on this text and press Ctrl+a or cmd+a keys.</div>
  <p>Some text here...</p>
  <script>
    
    var text = document.querySelector('#my-text');
    
    var scope = createScope(text); // creates scope that will limit all text selection on Ctrl+a or cmd+a keys pressed.
    
    // scope.remove(); // revemoves selection limit on Ctrl+a keys
    
  </script>
</body>
</html>

 

Alternative approaches

Warning: below aproaches can have some problems on some mobile devicas,
e.g. Android with Google Chrome Web Browser that do not block content editing.

return false; based example

In this section, you will find example that returns false value to block changes in editable content.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    [contenteditable="true"] {
        outline: none;
    }

</style>
<script>
  
  	function isApple() {
    	var expression = /(Mac|iPhone|iPod|iPad)/i;
        return expression.test(navigator.platform);
    }

    function isControl(event) {
        if (isApple()) {
            return event.metaKey;
        }
      	return event.ctrlKey; // Windows, Linux, UNIX
    }

</script>
</head>
<body>
  <p>Some text here...</p>
  <div 
      contenteditable="true"
      spellcheck="false"
      onkeydown="return isControl(event) && event.key === 'a'"
      onpaste="return false"
      ondrop="return false"
  >
    Get focus on this text and press Ctrl+a or cmd+a keys.
  </div>
  <p>Some text here...</p>
</body>
</html>

Where:

  • spellcheck="false" prevents agains markers on the text by web browser spell checing mechanism,
  • onkeydown="return isControl(event) && event.key === 'a'" prevents agains editable content changing by pressed keys (only Ctrl+a or cmd+a are allowed),
  • onpaste="return false" prevents against text pasting into editable content (blocked context menu paste option),
  • ondrop="return false" prevents against text dragging into editable content.

 

preventDefault() based example

In this section, you will find example that uses prevent default operation to block changes in editable content.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    [contenteditable="true"] {
        outline: none;
    }

</style>
<script>

  	function isApple() {
    	const expression = /(Mac|iPhone|iPod|iPad)/i;
        return expression.test(navigator.platform);
    }

    function isControl(event) {
        if (isApple()) {
            return event.metaKey;
        }
      	return event.ctrlKey; // Windows, Linux, UNIX
    }

</script>
</head>
<body>
  <p>Some text here...</p>
  <div 
      contenteditable="true"
      spellcheck="false"
      onkeydown="isControl(event) && event.key === 'a' || event.preventDefault()"
      onpaste="event.preventDefault()"
      ondrop="event.preventDefault()"
  >
    Get focus on this text and press Ctrl+a or cmd+a keys.
  </div>
  <p>Some text here...</p>
</body>
</html>

Snippets

  1. html element text selection area limit on Ctrl+a or cmd+a keys - example 1

  2. html element text selection area limit on Ctrl+a or cmd+a keys - example 2

See also

  1. JavaScript - detect apple device (MacOS, iPhone, iPad, iPod) 
  2. JavaScript - event on Ctrl+a or cmd+a keys pressed

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join