Home > Enterprise >  Trigger event when user highlights text
Trigger event when user highlights text

Time:12-06

I'm trying to figure out a problem that I recently saw on an e-shop website.

When a user highlights the name of a product, it pops up a little window asking about customer satisfaction and s on, like this:

enter image description here

Is there a way to use a pseudo class line :active or :focus to enable this?

Or is there perhaps a custom solution using javascript event listener?

CodePudding user response:

Yes, it is possible to use a pseudo-class like :active or :focus to trigger an event when the user highlights text on a webpage. However, these pseudo-classes are typically used to apply styles to an element when it is active or focused, rather than to trigger events.

If you want to trigger an event when the user highlights text, it is better to use a JavaScript event listener, as I mentioned in my previous response. You can attach an event listener to the selectionchange event, which is fired whenever the user selects or deselects text on the page.

Here is an example of how you could use a JavaScript event listener to trigger an event when the user highlights text on the page:

document.addEventListener("selectionchange", function() {
  var selectedText = window.getSelection().toString();
  if (selectedText) {
    // Trigger your event here
  }
});

This will attach an event listener to the selectionchange event, and whenever that event is fired, the event listener will check if any text is currently selected. If there is, it will trigger your event.

  • Related