I'm trying to handle touch/mouse events. So, I created this code:
myObject.addEventListener("touchstart", function(e){
e.stopPropagation();
e.preventDefault();
console.log("Touched");
mouseTouchDown(e);
});
myObject.addEventListener("mousedown", function(e){
console.log("Clicked");
mouseTouchDown(e);
});
function mouseTouchDown(e){
console.log("Some function.");};
I want to stop bubbling of touch event, so click won't be fired afterwards. It works on Chrome, but on Firefox I get in console:
Touched
Clicked
How can I stop mouse click firing after touch event?
I tried returning false, but it doesn't work.
This looks like a bug in the browser, your code looks fine.
See: https://bugzilla.mozilla.org/show_bug.cgi?id=977226.
What OS/version of Firefox are you testing this with?
Have u attached both events with same element?
If that is the case the error is not because of bubbling happening.while mouse click several events will happen like mousedown, touchstart ..etc.so if you want to avoid mouse click event occuring add preventDefault() in the mouse down.This will disable default mouse click event happening on that element.
Related
I am working on an application using javascript and I want to get mouse events. To stop the options that appear when right clicking I use the preventDefault() function and it works in Firefox and Chrome but it doesn't work in Safari. This is my code:
document.querySelector("#GL-Surface").addEventListener("mousedown", function(e) {
e.preventDefault();
/* Handle mouse events */
});
From an other question I got that you should return false; but this still doesn't work. preventDefault() however works in Safari when it is used in keyboard inputs. So how can I prevent the default actions for mouse events in Safari?
To target right click events, use contextmenu rather than mousedown.
document.querySelector("#GL-Surface").addEventListener("contextmenu", function(e) {
e.preventDefault();
});
Note that the options that appear on right click do appear only when the right click button is released, so I don't think mousedown is at all suitable here.
I am trying to attach a drop event to an HTML div:
document.getElementById('sub-main').addEventListener("drop",
() => {console.log('DROP')});
but it does not fire. Adding a click event for test purposes worked - this click event fires:
document.getElementById('sub-main').addEventListener("click",
() => {console.log('Click')});
I have read that returning false from ondragover will help:
document.getElementById('sub-main').addEventListener("ondragover",
() => {return false});
document.getElementById('sub-main').addEventListener("drop",
() => {console.log('Drop')});
But this does not work either. I tried setting draggable to true:
document.body.setAttribute('draggable', true);
But also no luck!
Logging the event listeners to the console with getEventListeners() shows all the events, even any random event name I chose:
getEventListeners(document.getElementById('sub-main'));
But the drop event still does not fire. Any ideas?
To enable dragging you should first of all disable the default behavior of the browser using the dragover event.
add this piece of code and it will work.
document.addEventListener("dragover", function(event) {
event.preventDefault();
});
I did some trial and error in plunker and came to the conclusion that you first need to set the eventListener on the document(dont use.getElementById('sub-main') gives error in plunker at least) and then specify in the eventlistener on which target to fire on. And for it to detect that it can be dropped you need to have other eventListeners like: drag, dragstart, dragover, dragleave and dragenter. Just follow what they did here on MDN.
My iPhone's screen is playing up. I had the idea, since I'm a web developer, to go to a page on my local machine's web server, or on jsfiddle, using my phone, and have some jquery running on that page which gives me some simple feedback about every touch event. (I have a feeling that I will see lots of spurious swipe events firing off even when i'm not touching the screen, for example).
So, something like this:
<div id="feedback">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function feedback(msg){
$("#feedback").append("<div class=\"line\">"+msg+"</div");
}
$(function() {
feedback("in $(function) block");
$(document).on("click", function(event){
feedback("clicked at "+event.pageX+","+event.pageY);
});
//can you replace the below with working code?
$(document).on("all events", function(event){
var msg = "Some basic info about this event: if it's a swipe, which direction. if it's a keypress, which character? etc"
feedback(msg);
});
});
</script>
I've set this up in a jsfiddle here: https://jsfiddle.net/sxqjp9xe/
Do I need to write a handler for every event i'm interested in, like I've done with the click handler? Or is there some more generic solution? Thanks, Max
EDIT: changed my "feedback" function to use prepend() instead of append() as it's easier to see once you get a lot of lines on there.
You can include more than one event in the handler:
function feedback(msg){
$("#feedback").append("<div class=\"line\">"+msg+"</div");
}
$(document).on("blur touchstart touchmove touchend touchcancel focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error", function(event) {
var msg = event.type
feedback(msg);
}
https://jsfiddle.net/e9e0ehyc/
jsfiddle
<div class='wrapper'>
<button class='child'>Click me</button>
</div>
function h(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
alert(e.type);
return false;
}
document.querySelector('.wrapper').addEventListener('mouseup', h, false);
document.querySelector('.child').addEventListener('click', h, false);
I expect this to prevent the 'click' event from firing, but it doesn't. However, changing mouseup to mousedown does in fact prevent the click event.
I've also tried setting the useCapture argument to true, and that also doesn't produce the desired behavior with mouseup. I've tested this on Chrome and Firefox. Before I file bugs, I figured I'd ask here.
Is this a bug in current browsers, or is it documented behavior?
I've reviewed the W3C standard (DOM level 2), and I wasn't able to find anything that could explain this behavior, but I could have missed something.
In my particular case, I'm trying to decouple two pieces of code that listen to events on the same element, and I figured using capture events on the part that has priority would be the most elegant way to solve this, but then I ran into this problem. FWIW, I only have to support officially supported versions of FF and Chrome (includes ESR for FF).
Check out this quirksmode article
The click event:
Fires when a mousedown and mouseup event occur on the same element.
So when the mouse click is released, both the mouseup and click events are fired, click doesn't wait for the mouseup callback to finish. Almost always, mouseup and click can be used synonymously.
In order to cancel the click, like you demonstrated, you can return false in the mousedown event callback which prevents the click event from ever completing.
I just want to provide my work around for this issue:
let click_works = true
this.addEventListener('mousedown', e => {
click_works = // condition why the click may work or not
})
this.addEventListener('click', e => {
if (click_works) // Do your stuff
})
Hopefully, it will help someone.
Finally found a way to prevent click event from firing. Tested on latest Chromium and Firefox. It may be some bug or implementation details.
Solution
Handle onpointerdown or onpointerup event, remove the element and insert it in the same position.
<span>
<button onpointerdown="let parent = this.parentElement; this.remove(); parent.appendChild(this);" onclick="alert();">TEST</button>
</span>
Result
onpointerdown
onmousedown
onpointerup
onmouseup
<-- no click event occures
It appears that the Blur event stops the click event handler from working? I have a combo box where the options only appear when the text field has focus. Choosing an option link should cause an event to occur.
I have a fiddle example here: http://jsfiddle.net/uXq5p/6/
To reproduce:
Select the text box
Links appear
Click a link
The blur even occurs and the links disappear
Nothing else happens.
Expected behavior:
On step 5, after blur occurs, the click even should also then fire. How do I make that happen?
UPDATE:
After playing with this for a while, it seems that someone has gone to great lengths to prevent an already-occurred click event from being handled if a blur event makes the clicked element Un-clickable.
For example:
$('#ShippingGroupListWrapper').css('left','-20px');
works just fine, but
$('#ShippingGroupListWrapper').css('left','-2000px');
prevents the click event.
This appears to be a bug in Firefox, since making an element un-clickable should prevent future clicks, but not cancel ones that have already occurred when it could be clicked.
Other things that prevent the click event from processing:
$('#ShippingGroupListWrapper').css('z-index','-20');
$('#ShippingGroupListWrapper').css('display','none');
$('#ShippingGroupListWrapper').css('visibility','hidden');
$('#ShippingGroupListWrapper').css('opacity','.5');
I've found a few other questions on this site that are having similar problems. There seem to be two solutions floating around:
Use a delay. This is bad because it creates a race condition between the hiding and the click event handler. Its also sloppy.
Use the mousedown event. But this isn't a great solution either since click is the correct event for a link. The behavior of mousedown is counter-intuitive from a UX perspective, particularly since you can't cancel the click by moving the mouse off the element before releasing the button.
I can think of a few more.
3.Use mouseover and mouseout on the link to enable/disable the blur event for the field. This doesn't work with keyboard tabing since the mouse is not involved.
4.The best solution would be something like:
$('#ShippingGroup').blur(function()
{
if($(document.activeElement) == $('.ShippingGroupLinkList'))
return; // The element that now has focus is a link, do nothing
$('#ShippingGroupListWrapper').css('display','none'); // hide it.
}
Unfortunately, $(document.activeElement) seems to always return the body element, not the one that was clicked. But maybe if there was a reliable way to know either 1. which element now has focus or two, which element caused the blur (not which element is blurring) from within the blur handler. Also, is there any other event (besides mousedown) that fires before blur?
click event triggers after the blur so the link gets hidden. Instead of click use mousedown it will work.
$('.ShippingGroupLinkList').live("mousedown", function(e) {
alert('You wont see me if your cursor was in the text box');
});
Other alternative is to have some delay before you hide the links on blur event. Its upto you which approach to go for.
Demo
You could try the mousedown event instead of click.
$('.ShippingGroupLinkList').live("mousedown", function(e) {
alert('You wont see me if your cursor was in the text box');
});
This is clearly not the best solution as a mousedown event is not achieved the same way for the user than a click event. Unfortunately, the blur event will cancel out mouseup events as well.
Performing an action that should happen on a click on a mousedown is bad UX. Instead, what's a click effectively made up of? A mousedown and a mouseup.
Therefore, stop the propagation of the mousedown event in the mousedown handler, and perform the action in the mouseup handler.
An example in ReactJS:
<a onMouseDown={e => e.preventDefault()}
onMouseUp={() => alert("CLICK")}>
Click me!
</a>
4.The best solution would be something like:
$('#ShippingGroup').blur(function()
{
if($(document.activeElement) == $('.ShippingGroupLinkList'))
return; // The element that now has focus is a link, do nothing
$('#ShippingGroupListWrapper').css('display','none'); // hide it.
}
Unfortunately, $(document.activeElement) seems to always return the
body element, not the one that was clicked. But maybe if there was a
reliable way to know either 1. which element now has focus or two,
which element caused the blur (not which element is blurring) from
within the blur handler.
What you may be looking for is e.relatedTarget. So when clicking the link, e.relatedTarget should get populated with the link element, so in your blur handler, you can choose not to hide the container if the element clicked is within the container (or compare it directly with the link):
$('#ShippingGroup').blur(function(e)
{
if(!e.relatedTarget || !e.currentTarget.contains(e.relatedTarget)) {
// Alt: (!e.relatedTarget || $(e.relatedTarget) == $('.ShippingGroupLinkList'))
$('#ShippingGroupListWrapper').css('display','none'); // hide it.
}
}
(relatedTarget may not be supported in older browsers for blur events, but it appears to work in latest Chrome, Firefox, and Safari)
If this.menuTarget.classList.add("hidden") is the blur behavior that hides the clickable menu, then I succeeded by waiting 100ms before invoking it.
setTimeout(() => {
this.menuTarget.classList.add()
}, 100)
This allowed the click event to be processed upon the menuTarget DOM before it was hidden.
I know this is a later reply, but I had this same issue, and a lot of these solutions didn't really work in my scenario. mousedown is not functional with forms, it can cause the enter key functionality to change on the submit button. Instead, you can set a variable _mouseclick true in the mousedown, check it in the blur, and preventDefault() if it's true. Then, in the mouseup set the variable false. I did not see issues with this, unless someone can think of any.
I have faced a similar issue while using jQuery blur, click handlers where I had an input name field and a Save button. Used blur event to populate name into a title placeholder. But when we click save immediately after typing the name, only the blur event gets fired and the save btn click event is disregarded.
The hack I used was to tap into the event object we get from blur event and check for event.relatedTarget.
PFB the code that worked for me:
$("#inputName").blur(function (event) {
title = event.target.value;
//since blur stops an immediate click event from firing - Firing click event here
if (event.relatedTarget ? event.relatedTarget.id == "btnSave" : false) {
saveBtn();
}
});
$("#btnSave").click(SaveBtn)
As already discussed in this thread - this is due to blur event blocking click event when fired simultaneously. So I have a click event registered for Save Btn calling a function which is also called when blur event's related Target is the Save button to compensate for the click event not firing.
Note: Didnt notice this issue while using native onclick and onblur handlers - tested in html.