0

I want to trigger a keyboard event to press "right arrow" key. The purpose is to cancel the highlight.

I used the code below to insert a hyper link into the editor content.

var range = document.getSelection().getRangeAt(0);
var nnode = document.createElement("a");
range.surroundContents(nnode);
nnode.innerHTML = url;
nnode.setAttribute(url);
nnode.focus();

html

It is highlight by default. I want to trigger an "right arrow" key in order to cancel the highlight and move the cursor to the right. I did many searchs, I tried the most of solutions, but I still get one works. My environment is IE 11.

Can I get some help?

Thanks!

EGC
  • 1,719
  • 1
  • 9
  • 20
kevin
  • 419
  • 1
  • 3
  • 11
  • 1
    X-Y problem. You don't want to *Trigger "right arrow"*, your second sentence is what you want: "The purpose is to cancel the highlight." and for this, you really don't need to *Trigger "right arrow"*. – Kaiido Oct 10 '19 at 00:51
  • Simulating such user input events has never been universally supported and has been eschewed in more recent years. There is no appropriate cross-browser solution to the “X” question. – user2864740 Oct 10 '19 at 01:02

1 Answers1

1

So.. here are the resources you're asking for, but I have a solution for your highlighting problem which is none of these.

Resources:

How to trigger click on page load?

Detecting arrow key presses in JavaScript

Trigger an UP or DOWN ARROW key event through javascript


The actual solution uses JQuery & this resource: JavaScript Set Window selection

$("document").ready(function() {
   window.getSelection().removeAllRanges();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv">
I am some text!
</div>

See the JSFiddle: JSFiddle

EGC
  • 1,719
  • 1
  • 9
  • 20
  • Thanks a lot! I will try tomorow since I don't have access to my computer right now. BTW, will this solution keep the cursor at the right end of the string? Or, is there a another way to just focus on the right end of the string? – kevin Oct 10 '19 at 03:20
  • The cursor will not appear when this code is run, is that what you were after? It will just be as though the text was never selected – EGC Oct 10 '19 at 03:22
  • 1
    Thanks so much! Your solution perfectly solved my problem. – kevin Oct 10 '19 at 14:12