How to Find the Nearest Instance of an Image Above Current Cursor Point

I want to hook up a keyboard shortcut for a rich text editor. There are several of these editors on the page, so I cannot use a found image as well as I might - it may select the wrong image.

So, what I would like to do is say "Find me this image on the page, but it must be the one nearest to AND above the currently highlighted text"

I don't want it to be based on where the mouse cursor is.

So I guess that's two questions:

Can I specify to look above a given area?
Can I set that starting point to be where a text editor has focus, not where the mouse pointer is?

Any ideas? I look forward to hearing any suggestions :slight_smile:

Hey Lloyd,

It sounds like you're working in a web browser. Yes?

In any case – you should specify what you're working in and provide a screenshot if possible.

-Chris

Ah, I'm not sure I can as it's an internal company tool and I think that might be frowned upon.

It is running in Chrome as an extension, and there are two rich text editors (cKEdit), hence I only want it to click on one of the editor's toolbar buttons, the one above the textarea that I am working in at the time. I did try using the found image area near to the cursor but that didn't work very well.

Ah, okay. Please say so at the outset, so people on the forum don't have to wonder and ask questions that can't be answered.

Finding text selections according to the selection color is difficult but not always impossible. There a so many possible problems that I rarely try, unless there is some clearly definable boundary I can anchor to.

Without seeing what you're dealing with and being able to test I can't really say much more...

-Chris

OK, so I can make a generic example that gives nothing away that the company might have an issue with. Here's what I am after.

.

However, the highlighted text could, of course, be anywhere in that text area and the text selection color might differ depending on OS settings. But hopefully this shows what I'm after.

Perhaps another approach that does not scan the screen might work? For example, when the keyboard shortcut is invoked, run a script to:

  • Find element that has focus (the textarea)
  • Walk the DOM to find the code button
  • element.click() it

A script did it. Far easier solution :slight_smile:

var focussedEl = document.activeElement;
var codeButton = focussedEl.parentNode.previousElementSibling.querySelector("button:nth-of-type(3)"); 
codeButton.click();
2 Likes

Well done!