David 天宇 Wong
David 天宇 Wong

Reputation: 4197

can't use ctrl + click with preventDefault and return false

I'm loading every pages in AJAX so I'm using return false on my links to load them in ajax.

Problem: if the guys want to open it in a new window he can't, ctrl+click activates the ajax as well, I haven't tried middle button because I don't have a mouse.

I then tried e.preventDefault and it still prevents the dude to open it in another tab.

Any idea how I could circumvent this?

(if you want to try: www.p1x3L.com)

Upvotes: 1

Views: 425

Answers (1)

BenM
BenM

Reputation: 53238

e.preventDefault() will prevent the link from being followed by the browser at all.

What I'd be tempted to do is just check the status of the Ctrl (or cmd on a Mac) when the click occurs, and then handle the action.

You'll need to track the action of the keypresses. Consider the following example, which assigns a boolean value to ctrlPressed:

var ctrlPressed = false;

$(window).on('keydown', function(e) {  
    if (e.metaKey || e.ctrlKey)  ctrlPressed = true;
}).on('keyup', function(e) {
    if (e.metaKey || e.ctrlKey)  ctrlPressed = false;
});

Now inside your click handler, you can just check the status of ctrlPressed:

$('a').on('click', function(e) {  
    if(ctrlPressed)
    {
        return true;
    }

    // Handle your AJAX here. No need for an else{} block 
    // since return true will already have executed.
});

Upvotes: 4

Related Questions