window.open with _blank opens two tabs in Firefox - javascript

When this element is middle clicked:
// Allow middle button click to open client in another tab.
$(document).on('mousedown', '.clientlist-edit', function (event) {
if (event.which === 2) {
event.preventDefault();
var url = $(this).attr('href');
url = url.toLowerCase().replace('/addedit', '/clientindex');
window.open(url, '_blank');
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="clientlist-edit" href="/Clients/Management/AddEdit/4ffac190-72d2-476a-b0be-a9d90097272a">
<i class="glyphicon glyphicon-pencil"></i> <strong class="title">Client Name</strong>
</a>
This handler is called and when it gets to window.open, two tabs are opened. The first is the URL (variable URL) which is desired. The second is the original href set on the anchor element which is undesired. I'm calling preventDefault. What am I missing?
It is reproducible. See the link below. Sometimes it is two middle clicks. It is a middle click. It only happens in Firefox.
https://jsfiddle.net/jsmunroe/eap1b6k7/3/
I'm using Firefox 68.0.2.

I guess your goal here is to intercept the user trying to open a link in a new tab and instead open a different link in a new tab. If I'm correct, then you're going to need to adjust your strategy in a few key ways:
Don't use mousedown
Click events are triggered by a mouse-down followed by a mouse-up event. That means that normally you have to press and release the button before any click-type thing happens, whether that's navigation (left-click), context menu (right-click) or open in new tab (middle-click). If you try to simulate this using mousedown, it's gonna feel weird - the action will happen too soon!
Also, as you've now observed, it won't work correctly: the corresponding click event will still happen after your handler runs, because you're not cancelling the right event. What does your preventDefault() / return false accomplish? Well, try holding the middle button down and dragging: most browser will probably pan around the view as you move your mouse, but if you try this on your "Middle Click Me" element... Nothing happens. Yep, you've only succeeded in making your page slightly more annoying to scroll around on.
DO use the auxclick event.
I'm guessing you went with mousedown in the first place because you observed that nothing fired for a middle click when you captured the click event. A few years ago, click would've worked fine - but now, click only fires for the primary mouse button. This is a good thing! Way too many people inadvertently blocked right- and middle-clicks by capturing click, when they only intended to capture left-clicks. Presumably if you're capturing auxclick, you know what you're doing and can be trusted to handle it properly. (so, y'know... Do be careful)
The w3c actually has rather good documentation on all of this, so I'd be remiss if I didn't link to it and quote the relevant bits here:
The click event should only be fired for the primary pointer button (i.e., when button value is 0, buttons value is 1). Secondary buttons (like the middle or right button on a standard mouse) MUST NOT fire click events. See auxclick for a corresponding event that is associated with the non-primary buttons.
The click event MAY be preceded by the mousedown and mouseup events on the same element, disregarding changes between other node types (e.g., text nodes). Depending upon the environment configuration, the click event MAY be dispatched if one or more of the event types mouseover, mousemove, and mouseout occur between the press and release of the pointing device button. The click event MAY also be followed by the dblclick event.
Finally, here's your snippet with the changes above, for your review (you can't actually test it here, since window.open is blocked in Snippets - but you'll get an error indicating this and not see any tabs open; paste it into your fiddle for a real test):
// Allow middle button click to open client in another tab.
$(document).on('auxclick', '.clientlist-edit', function (event) {
if (event.which === 2) {
event.preventDefault();
var url = $(this).attr('href');
url = url.toLowerCase().replace('/addedit', '/clientindex');
window.open(url, '_blank');
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="clientlist-edit" href="/Clients/Management/AddEdit/4ffac190-72d2-476a-b0be-a9d90097272a">
<i class="glyphicon glyphicon-pencil"></i> <strong class="title">Client Name</strong>
</a>
Yep - the only change is mousedown -> auxclick! Enjoy...
Further reading
Middle button click event
UI Events - event type click - W3C Editor's Draft
Element: auxclick event on MDN

Related

JavaScript Click event fires via the Enter Key but not via the Mouse

Some code that looks like the following is firing the click event via the Enter key, but is not responding to the mouse click.
//a is an anchor element
a.addEventListener('click', function (e)
{
//Do Stuff...
});
This page demonstrates the problem. The relevant bit of code is at line 176. This is in the middle of development and currently only (sort of) works in Chrome.
Also, I just verified that it works if I use mousedown, so it's not just the case of an invisible element sitting in front of the anchor.
Any ideas?
Edit: Now that you've shown us the actual code you're using, the problem is related to the fact that the autoSuggest() function has it's own click handler and in that click handler, it is clearing the container which removes all <a> elements in the container so your link object gets destroyed (probably before your click event gets to process). So, you can get events that happen before the click (like mousedown), but after a click, the element is removed from the DOM.
If you tell us what you're trying to actually do when an auto-suggest item is clicked that is different than the default behavior of the autoSuggest() function and you point to any documentation for that function, then perhaps we could offer a better way to solve your issue.
The link may be firing and taking you off to a new page (or reloading the current page), thus preventing you from seeing the click code run. Usually when you process a click event on a link element, you need to prevent the default behavior:
//a is an anchor element
a.addEventListener('click', function (e) {
e.preventDefault();
//Do Stuff...
});
Another possibility is that you are trying to install the event handler too soon either before the DOM has been loaded or before this particular link has been created and thus no actual click event handler is attached to the DOM object. You can verify whether the event handler is even getting called by temporarily putting an alert("Click handler called"); in the event handler and see if that pops up or not.

Backbone.js - Both click and double click event getting fired on an element

In my Backbone View, I have defined events like this:
events : {
'click .elm' : 'select',
'dblclick .elm' : 'toggle'
},
select: function(e){
e.preventDefault();
console.log('single clicked');
}
toggle : function(e){
e.preventDefault();
console.log('double clicked');
}
I have bound single and double click event listeners to same element .elm. When I double click on this element, I get this output:
single clicked
single clicked
double clicked
Tried preventDefault() and stopImmediatePropagation() and that didn't solve the issue.
So, how can I prevent the single click event getting fired when I double click?
The jQuery documentation specifically recommends against what you're doing:
It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
What you're seeing is exactly what is expected (depending on the browser of course). The only way around your problem is to set a timer and manually differentiate between a single- and double-click yourself; then you'll have to adjust the timer value and check various browsers and operating systems until you get something that sort of pretends to work in most place.
I'd strongly recommend that you use separate controls with single-click actions instead. Double-click is pretty unfriendly period and we only put up with it because we're used to it.
This isn't an issue with Backbone itself.
It's about how to handle both single click and double click events on the same button.
See
Need to cancel click/mouseup events when double-click event detected
Javascript with jQuery: Click and double click on same element, different effect, one disables the other
Update: But it would be better if you didn't have to deal with it. See mu is too short's answer below!
Try adding return false; at the end of select & toggle.

Ctrl+click on links with click handlers

I have a link (anchor) that has an href attached to it to navigate to a specific URL say 'www.bla.com'.
<a href='http://www.bla.com' />
I also have an click handler attached to the link that performs some actions and then opens an html view in the same window. Everything works perfectly well.
However, when the user uses 'ctrl+click' to open the link in a new tab/window, the click handler seems to be taking precedence and opens the html view in the same window. But I want to retain the 'ctrl+click' behavior and allow the user open the link in a new tab/window (just as a normal link). How could I do that?
Thanks in advance!
function process(e){
var evt = e ? e:window.event;
if(evt.ctrlKey)
alert("ctrlClicked");
}​
evt.ctrlKey will return true if control key is pressed, you can write your conditions within "if" block, I tested this for chrome and ff only.
Perhaps something like this?
function onclick(e){
var event = e ? e:window.event;
this.target = event.ctrlKey?"_blank":"_self";
}​
The associated click event object will have its ctrlKey property set to true if the control key (or equivalent) was pressed when the click occurred. Check the event object and if the control key was pressed, don't do the "HTML view" thing.
Click me!
However, if the user activates the link some other way, you may or may not get a click event.
e.g.
right button -> "open in new tab/window" - no click event (Firefox, IE)
Tab to focus on link, press enter - dispatches click event (Firefox, IE)
<a target="_blank" href='http://www.bla.com' />
Add target="_blank" within to anchor tag.

Keypress and Keydown generate different behavior

I am trying to create to popup div when pressing enter key, while the div contains a button (that I script to focus when it fired up) that will close the div when you press enter again. I receive the enter key from binding keypress and keydown, end up having different results.
Binding 'keypress'
Things work properly, with first enter key fires up a popup box and another enter key to dismiss the popup box.
Refer this JSFiddle.
Binding 'keydown'
This doesn't work correctly, as it fires up and dismiss the popup box immediately (which you won't see) with only one enter key.
Refer this JSFiddle.
My question is why would keydown generate odd behavior, it is like firing enter key twice for me, but the truth it wasn't. If I remove the button focus(), it will works correctly. That's puzzled me.
Tested with firefox and chrome.
You're rebinding the click event every single time the popup opens, so each time you click the close button it'll fire it multiple times which will cause unexpected behaviour.
Eg:
var Popup = function(){
$('#ok-button').live('click',function(){
$('#popup').remove();
});
};
This code means every time you create a new Popup instance, every single $('#ok-button') that exists will have another click event bound to it.
As for the reason why it immediately closes when you use keydown vs keypress, that's due to the fact that the moment the popup is opened you've set the focus to the button.
The two key events work differently (firing at slightly different times during the key process). It appears that with keydown, you're changing the focus in the middle of the actual action (pressing the button on the keyboard) which then continues and triggers the focused click.
Removing the focus stops the weird double trigger behaviour because you're no longer binding another click event.
I'd suggest changing your click event:
$('#ok-button').live('click', function(){
$('#popup').remove();
});
var Popup = function(){
// Whatever
};
I'd also suggest looking at jQuery's on event instead of using live.

In the mousedown event, is it possible to cancel the resulting click event? or pass info to it?

for arcane reasons I need to be able to cancel the click event via the mousedown event.
Briefly; I am creating a context menu in the mousedown event, however, when the user clicks on the page the context menu should disappear.
I am not able to use the mousedown event over the click in that scenario as I want the user to be able to click links inside the menu ( a full click would never travel to the <a> based menu elements ).
If it is any help, jQuery can be applied.
I would like to either be able to prevent the click event from happening from within the initial mousedown, or be able to pass information to the click event (via originalEvent or otherwise).
TIA
Seems to be impossible, neither FF nor Opera didnt cancel upcoming click when prevented in mousedown and/or mouseup (as side note: click is dispatched after mouseup if certain conditions met). testcase: http://jsfiddle.net/ksaeU/
I have just had the exact same problem. I fixed my context menu by closing it on mousedown and eating the mousedown event on the menu so that I can still receive clicks on the menu, like so:
$(document).one('mousedown.ct', null, function() { cmenu.hide(); return false; });
cmenu.bind('mousedown', function(e) { e.stopImmediatePropagation(); });
And in the hide() function I unbind the mousedown.ct again, in case it was closed due to a click on an item.
Hey, I think this is what you are trying to do with your code. If not, I apologize, I may have misunderstood the question. I used jQuery to get it done: http://jsfiddle.net/jackrugile/KArRD/
$('a').bind({
mousedown: function(){
// Do stuff
},
click: function(e){
e.preventDefault();
}
});

Categories

Resources