Question

How can I create a UX popover link that responds to single and double clicks?

Answer and Explanation

Creating a UX popover link that distinguishes between single and double clicks involves handling JavaScript event listeners for both clicks. Here’s how you can achieve this, with explanations for clarity:

1. HTML Setup: Create the link that will trigger the popover and the popover element itself.

<a href="#" id="myPopoverLink">Click me</a> <div id="myPopover" class="popover" style="display:none;">    <p class="qa-text">This is a popover content</p> </div>

2. CSS Styling: Create some simple styling to make popover visible, use display:none for hidden state and add other styling

.popover {
  position: absolute;
  border: 1px solid #ccc;
   background-color: white;
   padding: 10px;
}

3. JavaScript Logic for Single and Double Clicks:

- In JavaScript, you will use an event listener attached to the link. We'll introduce a timer, that checks time passed between clicks. If the second click happens within certain amount of time then its a double click and specific event gets triggered.

const link = document.getElementById("myPopoverLink");
const popover = document.getElementById("myPopover");
let singleClickTimer;
let clickCount = 0;

link.addEventListener("click", (e) => {
  e.preventDefault();
  clickCount++;

if(clickCount === 1) {
  singleClickTimer = setTimeout(() => {
     clickCount = 0;
    // handle single click action (Show/Hide popover)
    if(popover.style.display === "none") {
      popover.style.display = "block"
    } else {
     popover.style.display ="none";
    }      }, 200);
}else if (clickCount === 2) {
   clearTimeout(singleClickTimer);
  clickCount = 0;
  //handle double click action here
   console.log("Double click action"); }
});

Explanation of JavaScript Code:

  • preventDefault: We add it to stop default event behavior on link element
  • clickCount: We increase value with each click to make logic work
  • Single click logic We add setTimeout , with a timeout set to, in our case, 200 ms, to trigger the click if no additional clicks happen before then, handling opening and closing the popover on single click
  • Double click logic: When another click happens, inside of 200 ms timer gets cancelled and "double click action is handled". In this case we just write a log to a console, however, there may be more specific logic.

By using a single listener, we are not running two instances of similar functions, also with using clickCount value, we reduce usage of complicated flags for event behavior.

4. Further Improvements:

You could also change css of the link when mouse is hover to suggest the behavior for a better ux

More questions