mrbay
mrbay

Reputation: 101

Making pushstate work with both href and javascript

I'm using javascript pushstate to change the URL of the current page, when a link i clicked:

<a href="/some-page/" onclick="url_go('/some-page/'); return false;">

I want to allow right-clicking on the link and opening in new window - as well as CTRL+click should open in new tap. But it doesn't.

How can I make both normal clicking work (pushstate) and CTRL+click (new tap) work?

(Facebook does it, but I cannot see how).

Upvotes: 1

Views: 1279

Answers (1)

vortexwolf
vortexwolf

Reputation: 14037

I assume that you want your own event handler for Click, but leave the default behavior for Ctrl+Click or Scroll Button Click. I haven't found where exactly facebook does it (it always handles clicks and ctrl+clicks in the same way), but it can be achieved by code.

You should remove the onclick attribute from the HTML element and move it to javascript. Then check the event parameter for the ctrlKey property. You can do this by using the code like if (e.which > 1 || e.ctrlKey) or use a more complex function from a website similar to facebook:

function shouldUseDefault(e) {
    return ((e = (e || window.event)) && (e.type == 'click' || e.type == 'mousedown' || e.type == 'mouseup') && (e.which > 1 || e.button > 1 || e.ctrlKey || e.shiftKey || browser.mac && e.metaKey)) || false;
} 

Then use it so in plain javascript:

<a id="some-link-id" href="http://google.com">Test link</a>

<script type="text/javascript">
window.addEventListener("load", function() {
    var link = document.getElementById("some-link-id");
    link.addEventListener("click", function(clickEvent) {
        if (shouldUseDefault(clickEvent) === false) {
            url_go(link.href);
            clickEvent.preventDefault();
        }
    });
});
</script>

Or in jQuery if you want to support older browsers like Internet Explorer 8:

$(function() {
    $("#some-link-id").on("click", function(clickEvent) {
        if (shouldUseDefault(clickEvent) === false) {
            url_go(clickEvent.currentTarget.href);
            clickEvent.preventDefault();
        }
    });
});

Upvotes: 1

Related Questions