Search code examples
javascriptjqueryonclickhrefintercept

JavaScript update <a> href and then follow it and keep intended target


I have a problem. I need to update href and then follow it. It may seem that it's quite easy task, because I just could return false, create new link element and then initialise click on it or maybe just change location.href...

So problem is: How to know if user held [CTRL] button or right-clicked and chose one of Open in New Tab, Open in Incognito Tab or Open in New Window... or of course simply clicked with left-button...

This href must be updated on click. Mouse hover may be an option but this will fail in mobile and tablets :)

P.S. if you give a negative evaluation it would be nice to know why :)


Solution

  • Okay, so here's a workaround for you:

    HTML

    <a href="default_location">Click</a>
    

    JQuery

    $('a').on('mouseenter focus', function() {
        // Re-write url
        $(this).attr('href', 'redirected_location');
    });
    
    $('a').on('click', function(e) {
        // Prevent default behaviour (i.e. opening link)
        e.preventDefault();
    
        // Re-write url
        $(this).attr('href', 'redirected_location');
    
        // Re-direct to link
        window.location = $(this).attr('href');
    });
    

    The idea here is that we rely on other user interaction, other than clicking, to re-write the HREF.

    I have chosen mouseenter and focus to cover both mouse and keyboard events.

    This means that the URL they will follow, even if they right-click and chose new window, will be correct.