Run custom browser behavior for (medium) click on the link

Question

I want to trigger a (middle) mouse click on the link, in such a way as to trigger the behavior of my own browser for this event.

eg. in the browsers I work with, an average click will cause the linked page to open in a new tab in the background.

But if other browsers have different behavior, this should be called instead.

I know there is a method element.click();, but how can I tell which mouse button to click?

Background

The background is that I want the div to behave as much as possible, like a regular link. The idea was that I would create a hidden link tag and trigger the behavior of my own browser.

Requirements for div-as-link:

  • href may come from the data-href attribute.
  • Native browser behavior for left-clicking, middle-clicking, and possibly right-clicking.
  • Relation to the target attribute, which may come from the data-target attribute.
  • Tabindex
  • keyboard activation?
  • the ability to select fragments of text in a div. This means that we cannot just use the overlay.

Why not use a native link tag? Because the div contains internal tags <a>. Thus, when creating a div field, an a-tag will trigger nested a tags, which will cause some browsers to restructure the DOM tree.

Obviously, I could just set document.location.href on click. But this is only 20% of browser behavior.

I could also try to detect the mouse button and use js to open the tab in the background if that was the middle button.

, , . , , js.

, , <a> href click <div> <a>. . , .

js jQuery?

jQuery . , , , jQuery, .

.

, , .

0
2

left click middle click. tabindex html, div

$("#link").on('click', function(e) {
  const hasTargetBlank = $(this).data('target') === '_blank';
  const href = $(this).data('href');

  switch(e.which) {
    // left click
    case 1: {
      if (hasTargetBlank) {
        window.open(href);
      } else {
        window.location = href;
      }
      break;
    }
    // middle click
    case 2: {
      window.open(href);
      break;
    }
    // right click
    case 3: {
      // do what you want to do
    }
   }
});
+1

@JonUleis @MikeWillis fooobar.com/questions/1530547/...

  $('.linkbox', context).once('linkbox').each(function(e){

    var $linkbox = $(this);
    var href = $linkbox.data('href');
    if (!href) {
      return;
    }
    var $hiddenLink = $('<a>').attr('href', href).hide().appendTo('body');
    $linkbox.click(function(e){
      $hiddenLink[0].dispatchEvent(new MouseEvent('click', {button: e.button, which: e.which}));
      e.preventDefault();
    });
  });

, div, .

"URL- ", , .

UPDATE: , -, - . Chromium Linux .

+1

Source: https://habr.com/ru/post/1530548/


All Articles