How to route all mouse input to a specific HTML element? - javascript

For my webapp I'm working on a popup element, which is used for menus and similar things. I want to redirect all mouse input on the current page to this popup element when it's visible, however I can get it to work.
I have a tile element which, on mouse hover, shows an image (and highlights the tile). When the user clicks on that image the popup is shown (as a context menu). This works already. When the user moves the mouse outside the tile the hover state is gone, the highlight and also the image disappear, which is not what should happen. Instead I want the visual state unaffected as long as the menu is visible.
So I tried to capture the mouse using Element.setPointerCapture. However, this requires a pointer id, which I don't have. I tried to use onPointerDown on the trigger image, but that didn't do anything.
What's the right way to implement this mouse capture, so that no mouse event is scheduled to any other HTML element, but the popup?
This is what I came up with so far:
private handleTriggerClick = (e: React.MouseEvent): void => {
console.log("mouse");
this.props.trigger?.props.onClick?.(e);
if (this.state.open && this.props.closeOnTriggerClick) {
this.close();
} else if (!this.state.open && this.props.openOnTriggerClick) {
this.open();
e.currentTarget.setPointerCapture(this.pointerId);
}
e.stopPropagation();
};
private handleTriggerPointerDown = (e: React.PointerEvent): void => {
console.log("pointer");
this.pointerId = e.pointerId;
};
where trigger is the image used to show the popup.
I also tried using a mouse move handler on the document, but that didn't work either, probably because of event bubbling where first the deeper elements receive the event before it reaches the document, so it's too late then to prevent default handling or stop propagation.

The Element.setPointerCapture API will only work when the pointer is in its "active button" mode (that is between pointerdown and pointerup or pointercancel).
I guess it's not exactly what you want...
Maybe requestPointerLock would be closer to what you are asking, but it may also be a bit too much (a confirm message would pop-up asking your users if they wish to let your app control their mouse etc.)
So a third way, probably easier, is to append an overlay element with a fixed position that would cover the whole page, you could make it appear also only when your menu is hovered, but without seeing your actual situation, I can only give such a broad advice.

Related

Right click acts like a left click on the event

I have this code:
document.getElementById("1").oncontextmenu = function() {
return false
}
It disables the little window that shows after a right click (only on the button/image).
On my code (https://jsfiddle.net/nnuyguat/) everything is working fine, except for when I do a right click on the image as it triggers the left click event and changes the image untill I move the mouse.
Another related problem is if I press left click without releasing and then right click (releasing the right button), it will also change the image.
I need to prevent the image changing with right clicks. It should work as the closing button of the browser (except it's another images and it doesn't close anything).
You could use event.button to check which button is pressed because event.button returns a number which indicates which mouse button was pressed.
Source
Edit:
if (event.button === 2){
// run your function
}
That should be correct, as I have never used this before.
The right click event is not triggering a left click. It is just activating your object. Your image says "click" but it is inaccurate. It should say "Active".
Second, a number is NOT a valid ID. So rename your div from id="1" to id="one" or similar.
Finally, try with this code, instead of yours:
document.getElementById("one").addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('hello from right click');
return false;
}, false);
See https://jsfiddle.net/nnuyguat/3/
The issue with your image changing on right click is not related to your javascript, but to your css. The :active CSS pseudo-class matches when an element is being activated by the user. According to the specs this should only be when the element is activated with the primary mouse button, but it seems like most browsers do not implement the spec correctly. See this question for info.
A work around maybe to abandon the :active pseudo-class, and set up a function to change the content explicitly on left click.
Its because of the oncontextmenu event. Remove it and it will work

Javascript override user mouse event

I have a bit of javascript that will allow the user to move stuff around using the mouse, so the user can click and drag things around, which is working all fine, but what I am struggling with is being able to override the users click event.
So what I am trying to do is, if the user moves the item to a certain position I want to stop the click and hold event, this would mean the user would have to the go an reselect the item again and click and drag again.
Can you override the users mouse action from javascript? It seems simple but I am unable to find a way in my javascript to stop the mousehold event
You can try to override onmousedown to store the mouse coordinates and fire the "real click" event on onmouseup if the mouse position did not changed (or if the change is less than say 5 pixels).
document.getElementById('myElement').addEventListener('click', function(e) {
e.preventDefault(); // here is your override
doSomethingElse(); // or not
});
Same thing for IE but use attachEvent instead of addEventListener
Perhaps instead of blocking events, you can put some logic inside your onclick handler to check for this condition?
For example, maybe a couple of properties to maintain state. You could call one itemSelected, which must be true in order for the the item to move. Then if you set itemSelected to false, another click will be necessary to toggle it again.

Prevent firing the blur event if any one of its children receives focus

I have a div on a page that shows some info about a particular category (Image, Name etc).
When I click on the edit image it puts the category into edit mode which allows me to update the name. As you can see from the image below it shows that "Soup" is currently in edit mode, the others are in normal view mode. This all works as expected with the cancel / save buttons doing everything right. (I tried adding an image but wouldn't let me, need more love)
However once in edit mode if I click anywhere else on the page (Outside of the div) the expected result would be that the soup category would go back to view mode. Upon an event firing of some sort, this should also allow me to ask if they wanted to save changes.
So what I then decided to do is create an blur event on the "soups" parent div. This works as expected if I click anywhere on the page, however if I click on the inner element of the div it also causes the parents blur event to be fired, thus causing the category to go back to view mode.
So, is there a way to prevent the parent div from firing the blur event if any one of its children receive focus?
<div tabindex="-1" onblur="alert('outer')">
<input type="text" value="Soup" />
</div>
I just wrote the code without a compiler so not sure if that even works but with that hopefully you get the idea.
I'm using Knockout.js to update the GUI on the fly but that shouldn't effect this answer I wouldn't have thought.
I faced the same issue. This what worked for me.
handleBlur(event) {
// if the blur was because of outside focus
// currentTarget is the parent element, relatedTarget is the clicked element
if (!event.currentTarget.contains(event.relatedTarget)) {
.....
}
}
Enjoy :)
I've had to tackle this problem before. I am not sure if it is the best solution, but it is what I ended up using.
Since the click event fires after the blur, there is no (cross-browser, reliable) way to tell what element is gaining focus.
Mousedown, however, fires before blur. This means that you can set some flag in the mousedown of your children elements, and interrogate that flag in the blur of your parent.
Working example: http://jsfiddle.net/L5Cts/
Note that you will also have to handle keydown (and check for tab/shift-tab) if you want to also catch blurs caused by the keyboard.
I don't think there is any guarantee mousedown will happen before the focus events in all browsers, so a better way to handle this might be to use evt.relatedTarget. For the focusin event, the eventTarget property is a reference to the element that is currently losing focus. You can check if that element is a descendant of the parent, and if its not, you know focus is entering the parent from the outside. For the focusout event, relatedTarget is a reference to the element that is currently receiving focus. Use the same logic to determine if focus is fully leaving the parent:
const parent = document.getElementById('parent');
parent.addEventListener('focusin', e => {
const enteringParent = !parent.contains(e.relatedTarget);
if (enteringParent) {
// do things in response to focus on any child of the parent or the parent itself
}
});
parent.addEventListener('focusout', e => {
const leavingParent = !parent.contains(e.relatedTarget);
if (leavingParent) {
// do things in response to fully leaving the parent element and all of its children
}
});

Detect if mouse is over an element when page loads with Javascript

I have an image that I want to have trigger certain behaviors when the mouse is over, I have a mouseover and mouseout method, but if you happen to have your mouse over the image when the page loads, the mouseover method never fires until you leave the image and come back over it.
Is there a way to detect if the mouse is over an element on the fly without the mouse having to be off of the element and then come over the element to trigger the JS mouseover event? Like is there a document.getElementById("blah").mouseIsOver() type function in Javascript?
I believe this is possible without any action from the user. When your page loads, bind the mouseover event to your image and hide your image (i.e. using CSS display:none). Use setTimeout() to show it again in a few milliseconds (10 should be enough). The even should be fired.
If you don't want to cause the 'flick' effect on your image, you may try using some temporary element instead, attaching event to it, and delegating the event onto your image.
I have no idea if this is cross-browser solution, but it worked from my Firefox 3.0 console ;)
You could use the mousemove event. That would trigger anytime the user moves a mouse; so the only instance of the trigger not firing would be if the user does not move the mouse at all, which should be rare.
The only problem with this is that the event would fire anytime the mouse would move over your image, so you would get a LOT of those events while over the component. What you would probably need to do is implement some sort of flag within your method when the event fires. You turn on the flag when the event first fires, and you turn it off when you leave the component.
This is less than ideal, but I think this will probably satisfy your problem scenario. The following is some quick pseudo code on what that solution might look like, I think it should work.
<img src="blah.png" onmousemove="JavaScript:triggerOn(event)" onmouseout="JavaScript:triggerOff(event)"/>
...
<script type='text/javascript'>
var TriggerActive = false;
function triggerOn(e){
e = e||window.e;
if( !TriggerActive){
TriggerActive = true;
// Do something
} else {
// Trigger already fired, ignore this event.
}
}
function triggerOff(e){
e = e||window.e;
if(TriggerActive)
TriggerActive = false;
}
</script>
You can find some great mouse event information including browser compatibility notes here.
Use document.querySelectpor and onload/onready events.
var a = document.querySelector('#a:hover');
if (a) {
// Mouse cursor is above a
}
else {
// Mouse cursor is outside a
}
There is no way to get the mouse coordinates aside from listening for mouse events, namely mousemove, mouseover etc. However, these events are very sensitive in the sense that moving the cursor by just one pixel is enough to trigger them, so having the cursor hover over your image while perfectly still should be somewhat unusual.

Prototype best practice for "click anywhere to close"?

I find myself very often in the situation that I open an element in a web page - e.g. a drop-down menu - that I want to close if the user clicks anywhere on the page except the element itself.
To keep things simple, I have mostly written the code myself instead of employing some drop-down menu class.
However, I have never managed to build an implementation of this that was completely satisfying: Event handling and bubbling would work differently in different browsers, there would be the need for nasty workarounds, in some situations clicking the drop-down button would start closing it in the same moment, and so on.
Is there a Prototype based, authoritative, best practice to do this? Something that works across browsers - IE6 being a plus but not a requirement?
Just this:
click on a button - an element opens
(e.g. an absolutely positioned drop-down menu).
click within the element - the element stays open.
click on the button that opened the element - the element stays open.
click anywhere else on the page - the element closes.
I need help with the event handling part only, the displaying of the menu is totally secondary.
Event.observe(document, 'click', function (event) {
switch (event.element().id) {
case 'example_id':
// do different stuff depending on element clicked
// ofc u don't need to pass id, u can simply throw an element itself
break;
default:
// do close action
break;
}
// also check Event.findElement();
});
You can also add specific classes to the items you don't want to trigger close action and check it inside
if (!event.element().hasClassName('dont_close'))
Element.remove(selectDOMElement);
I guess the open button is within the menu.
$('openbutton').observe('click' function(event) {
var menu = $('openbutton').up();
if (menu.hasClassName('collapsed')) {
menu.removeClassName('collapsed');
menu.addClassName('expanded');
document.observe('click', function (event) {
if(!event.target.descendantOf(menu)) {
menu.addClassName('collapsed');
menu.removeClassName('expanded');
}
});
} else {
menu.addClassName('collapsed');
menu.removeClassName('expanded');
}
});
AFAIK, you need to make an invisible div the size of window, put it behind the current element, and add a click event to that.
Just thinking out loud but you might be able to use the blur event on the dropdown to hide it (blur gets fired when an element loses focus) or another idea might be when the dropdown opens attach a click event to the document object that hides the dropdown. Events get propagated through their containers so it should end up at the document object eventually. You might need to call preventPropegation on the event when your dropdown gets clicked so that it doesn't make it to the handler attached to the document.
maybe you could calculate the Position (X,Y) for the clickevent and compare that to the cumulativeOffset (cumulativeScrollOffset) + [el.width|el.height] of the desired container.
Event.observe(window, 'click', function(e) {
var el = $('el')
if( el.cumulativeOffset[0] < e.Event.pointerX(e) ... )
});
<div id="el" style="position:absolute;width:100px;height:100px;background-color:#00F;top:100px;left:300px;">
</div>

Categories

Resources