Key combination to add H2 tag to selected text in ContentEditable DIV using JavaScript/jQuery

Here is an example of a JavaScript/jQuery event handler for the key combination of CTRL + SHIFT + H for a contenteditable div. When you select text within the contenteditable div and press the combination of the three keys (CTRL + SHIFT + H), the selected text will be enclosed in an <h2> tag.

$(document).on('keydown', function (e) {
  if (e.ctrlKey && e.shiftKey && e.keyCode === 72) { // KeyCode for 'H' is 72
    // Get the selected text
    var selection = window.getSelection().toString();

    // Check if the selected text is not empty
    if (selection.length > 0) {
      // Replace the selected text with the same text wrapped in <h2> tags
      document.execCommand("insertHTML", false, "<h2>" + selection + "</h2>");
    }
  }
});

This code listens for the keydown event and checks if the CTRL and SHIFT keys are pressed along with the H key. If that key combination is pressed, it uses the window.getSelection() method to get the selected text and replaces it with the same text wrapped in <h2> tags using the document.execCommand method.

To check if focus is on a specific contenteditable div, you can compare the activeElement property of the document object with the div element using jQuery. Here’s the updated example:

$(document).on('keydown', function (e) {
  if ($(document.activeElement).is('#myDiv')) {
    if (e.ctrlKey && e.shiftKey && e.keyCode === 72) {
      var selection = window.getSelection().toString();
      if (selection.length > 0) {
        document.execCommand("insertHTML", false, "<h2>" + selection + "</h2>");
      }
    }
  }
});

In this example, #myDiv is the id of the specific contenteditable div that you want to check the focus on. The $(document.activeElement).is('#myDiv') condition checks if the currently focused element is #myDiv. If the condition is true, the code inside the block will be executed, otherwise it will be ignored.

In conclusion, the key combination event handler code provides a convenient way to format selected text within a contenteditable div by enclosing it in an <h2> tag. By using the combination of the three keys (CTRL + SHIFT + H), users can quickly and easily apply the desired formatting to their selected text. The code checks to ensure that the selected text is within the contenteditable div and on a single element, making sure that the formatting is applied correctly. This script demonstrates how to use JavaScript and jQuery to implement a custom event handler for a key combination, making text formatting faster and more efficient for users.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *