I'm pasting this sample code, which listens for mouseenter event and on mouseenter checks if Ctrl key is pressed. If yes, it applies some classes to the current target, which works fine, BUT only if the Ctrl key is pressed prior to the mouseenter event. What do I have to change for the same thing to happen also in the case where the mouseenter is first and then the Ctrl key is pressed?
html:
<div ng-mouseenter="hoverIn($event)" ng-mouseleave="hoverOut($event)"> Some content </div>
controller.js:
function hoverIn(event){
if((event.ctrlKey || event.metaKey)){
angular.element(event.currentTarget).addClass('current-element');
}
}
I know this is very old but I wanted to resolve it in case someone else came by it.
Changing your code to use ng-mousemove will get you what you want. Then in code handle both the true and false possibilities.
HTML:
<div ng-mousemove="mouseHover($event)"> Some content </div>
JavaScript:
scope.mouseHover = function ($event) {
if ($event && $event.ctrlKey) {
angular.element($event.currentTarget).addClass('actionCursor');
}
else {
angular.element($event.currentTarget).removeClass('actionCursor');
}
}
Related
I'm new to JQuery, so I don't know much of the logic. I'm using it to find out which index of textarea I clicked while holding the CtrlKey.
However how do I assign a function on a combination of onclick and a keyboard event.
//What I have tried:
//textarea is the object where I want to detect both ctrlKey and mouse click
$(textarea).keydown(function(event){
if(event.ctrlKey){
$(textarea).click(function(event){
console.log("catched")
})
}
})
The above method does work, however It does so thrice, i.e.the console.log occurs thrice, so is there a way to make this catch it once.
also it somehow also occurs when not pressing the ctrl key.
You can simply check the ctrlKey property of the mouse event:
$(function() {
$('textarea').on('click', function (e) {
if (e.ctrlKey) {
console.log('clicked with ctrl');
} else {
console.log('clicked without ctrl');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea>click me</textarea>
A couple of small mistakes here, but you had the right idea :)
First off, it doesn't really make sense to stack the event handlers the way you have done - I get what you're thinking logically but in reality JS doesn't work that way. What you've actually said is this:
"If the user presses a key down in this textarea, and if their control key is down, add an event listener to this textarea that detects for clicks, and logs catched to the console".
What you really want is this:
$("#txtarea").click((e)=>{
if (e.ctrlKey) {
console.log("Control + Click!");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="txtarea"></textarea>
The ctrlKey property is exposed to all events, not just the keypresses.
If it were not though, (say you wanted A + Click), you would have a keydown event which sets global variable aDown to true, a keyup event which sets the aDown variable to false, and a click event which has an if statement in it which only works if aDown is true. This is shown below:
let aDown = false;
$("#txtarea").keydown((e)=>{
aDown = e.originalEvent.code == "KeyA";
});
$("#txtarea").keyup((e)=>{
aDown = false;
});
$("#txtarea").click((e)=>{
if (aDown) {
console.log("A + Click!");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Focus the textbox, hold down "A", and then click.<br>
<textarea id="txtarea"></textarea>
Note: On macOS, control + click is a shortcut for right-clicking, so your code won't fire. Consider listening to the oncontextmenu event and dealing with it if you care about macOS support - or perhaps changing your shortcut scheme.
I'd recommend setting up a global variable which holds the status of your ctrl key.
var ctrlDown=false;
Instead of simply listening for a keydown event, listen for a keyup event as well and update ctrldown accordingly.
$(textarea).keydown(function(event) {
if (event.ctrlKey) {
ctrlDown = true;
}
});
$(textarea).keyup(function(event) {
if (event.ctrlKey) {
ctrlDown = false;
}
});
Now that you know that the ctrl key is actually pressed you can do a simple check like:
$(textarea).click(function(event) {
if (ctrlDown) {
console.log("catched")
}
});
I have a jQuery change event for when a user changes a given SELECT element. However the event may also be triggered by a third party script. What I want to do is detect whether the event was triggered programmatically or by the user.
I have tried the accepted solution in this question Check if event is triggered by a human
But note the JSFiddle in this answer is for a click event rather than a change event.
To demonstrate I amended the fiddle and created this one: http://jsfiddle.net/Uf8Wv/231/
If you try this in latest Firefox or Chrome, you will see that the alert human is being shown even when the event was triggered programmatically.
I have tried event.originalEvent.isTrusted but that doesn't work in all browsers. Can anyone help?
I have added mouseenter and mouseleave events. The idea is that it's a human if the click coincided with a mousepointer being over the element. See:
http://jsfiddle.net/Uf8Wv/232/
$("#try").mouseenter(function(event) {
mouseover = true;
});
// ... etc.
I can't think of any other way.
You can find some vague difference between click and emulated click using this code:
$(document).on('change', "#try", function (event) {
//some difference appear in the next line
console.log(event.delegateTarget.activeElement);
//no difference
if (event.originalEvent === undefined) {
alert('not human')
} else {
alert(' human');
}
event.delegateTarget = null;//doesn't help
});
$('#click').click(function (event) {
$("#try").click();
});
Click on the checkbox logs <input id="try" type="checkbox">.
Click on the button logs <button id="click">.
But...
Run $("#try").click(); from console before any clicks logs <body> and after the click result of the last click.
Generally JS can always fake any client event. So isTrusted is never trusted.
You can listen to the click event as well, and modify a variable. The change event seems indeed to be quite similar wheter it's a real click or a script triggered click, but the click on #try event won't be the same. And since click is triggered before change, you have time to set a switch.
Like this for example:
var realClick;
$("#try").change(function(event) {
console.log('change')
if (!realClick) {
alert('not human')
} else {
alert(' human');
}
});
$("#try").click(function(event) {
console.log('click')
// originalEvent is one way, but there will be many differences
if (event.originalEvent) {
realClick = true;
} else {
realClick = false;
}
});
// Since this is called from outside, better not put
// any controls here.
$('#click').click(function(event) {
$("#try").click();
});
http://jsfiddle.net/2xjjmo09/3/
What really worked for me is:
if ((event.originalEvent.isTrusted === true && event.originalEvent.isPrimary === undefined) || event.originalEvent.isPrimary === true) {
//Hey hooman it is you
//Real CLick
}
Tested with jQuery version 3.5
You can easily detect whether the click event on the button is actually triggered by mouse click or not. By doing,
$('#click').click(function(ev) {
if (ev.which !== undefined && ev.button !== undefined) {
$("#try").click();
}
});
Here's the Fiddle
Note: Beware of either ev.which or ev.button could result in 0 on some browser for left-click.
You can check for if event.srcElement (which is source element on which event is triggered) is equal to event.currentTarget something like:
$("#try").change(function(event) {console.log(event,event.target,event.currentTarget,event.srcElement)
if (event.currentTarget=== event.srcElement) {
alert(' human')
} else {
alert(' not human');
}
});
Fiddle: http://jsfiddle.net/Uf8Wv/234/
I am new to JS and trying to learn on my own - thanks for any help!
I am trying to have a simple program respond to a click differently depending on what other key is pressed at the time of the mouse click.
I have searched far and wide and have not been able to find an answer that works for non-modifier keys alt and shift (which I have had no trouble implementing). However, I can't for the life of me figure out how to achieve the same result with a regular character key.
The example below (which I found in other comments on this site) works if the alt key is employed.
<div id="targetDiv">I want to put a ding in the universe.</div>
$(function() {
$("#targetDiv").click(function(event) {
if (event.altKey) {
//do something, alt was down when clicked
}
});
});
However, the intuitive modification does not work.
For example, the otherwise identical code (now using event.keyCode===114) does not work (?!) when the 'r' key is pressed (nor does event.charCode===114 do the trick):
<div id="targetDiv">I want to put a ding in the universe.</div>
$(function() {
$("#targetDiv").click(function(event) {
if (event.keyCode===114) {
//do something, alt was down when clicked
}
});
});
What went wrong?
I am able to get functionality out of a keyPress if I listen to it alone:
addEventListener("keypress", rIsPressed, false);
function rIsPressed(event){
if(event.keyCode===114){
console.log("the 'r' key is pressed");
}
}
however nothing seems to work when I try to pair a character keypress with a mouse click or even a character keypress with a modifier keypress:
addEventListener("keypress", rIsPressed, false);
function rIsPressed(event){
if((event.keyCode===114) && (event.altKey)){
console.log("the 'alt' and 'r' keys are pressed");
}
}
Note: I have tried keydown instead of keypress in all of these examples with no success.
Suggestions please on what I am missing or overlooking - what is problematic about pairing a character key down/press with a modifier key or a mouse click !?
Thank you!!
As I commented above, the click event does not have a property called keyCode so doing event.keyCode will not work. The only reason that control and alt work is because they are properties of the click event, event.ctrlKey and event.altKey. You can be a little more creative and use something like this maybe though I don't really know what you need:
var currKey = null;
$("#targetDiv").click(function (event) {
if (currKey != null) {
$("#targetDiv").text(currKey);
}
});
$(window).keydown(function (event) {
currKey = event.which;
});
$(window).keyup(function (event) {
currKey = null;
});
This stores the key code when keydown is fired, when keyup is fired it clears the var. The stuff in the click event is only allowed to run if the var shows something other than null.
I'm trying to disable the mouse right click option. So i used contextmenu bind function to prevent it. This works fine but when shift is pressed along with the mosue right click the contextmenu bind function is not triggering but it shows the contextmenu. Means am not getting the alert but it shows the menu.
Here is the code i tried.
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
alert('Context Menu event has fired!');
return false;
});
});
In order to capture the shift button press and mouse right click am doing the below code but this doesn't help. May be i am doing something wrong.
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
alert('Context Menu event has fired!');
return false;
});
var shift = false;
jQuery(document).on("keydown", function(event) {
//check for shift key is pressed
if (event.which === 16) {
shift = true;
}
});
jQuery(document).mousedown(function(e) {
// e.which === 3 is for mouse right click
if (e.which === 3 && shift === true) {
console.log("both action are triggered");
return false; // how to stop the contextmenu action here
}
});
});
I tried giving the e.preventDefault instead of return false. I think the context menu event itself is not triggering in firefox when shift is clicked.
How to disable the mouse right click in this situation for firefox? Any help or clue will be much helpful
JSFIDDLE
NOTE
This is not happening in chrome. This is happening in firefox only. Is this a bug?
It's not a bug, it's a feature!
http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus
User agents may provide means for bypassing the context menu
processing model, ensuring that the user can always access the UA's
default context menus. For example, the user agent could handle
right-clicks that have the Shift key depressed in such a way that it
does not fire the contextmenu event and instead always shows the
default context menu.
You will not be able to do this in Firefox, by design. It's annoying, especially for complex web apps and games, but it's hard-coded into the browser and there's not way to disable it in javascript (that I know of).
Blame the standards, not Mozilla.
Javascript code to disable mouse right click
<script language="javascript">
document.onmousedown=disableRightclick;
status="Disabled";
function disableRightclick(event)
{
if(event.button==2)
{
alert(status);
return false;
}
}
</script>
On the HTML Body tag set the oncontextmenu property to false.
<body oncontextmenu="return false">
...
</body>
Disclaimer: The link provided is the blog which i have written. Hope
this solves the problem.
How can I find out a HTML-Element (lets say a select-tag) got focus by mouse-click, keyboard or JavaScript function?
<select onfocus="foo(event)"></select>
<script>
function foo(e) {
if (e.??? == 'mouse') {
//do something
}
else if (e.??? == 'keyboard') {
//do something different
}
}
</script>
I also tried to add an onclick event to the element but the onfocus event fires first.
I don't believe there is any native way to see how the element received its focus (correct my if I'm wrong!).
However, you may be able to do something like store when the mouse is clicked, store when the keyboard is used and then react based on the last active state.
var inputState = null;
document.addEventListener("click", handleClick);
document.addEventListener("keyup", handleKey);
function handleClick () {
inputState = "mouse";
}
function handleKey () {
inputState = "keyboard";
}
function foo() {
if ( inputState === "mouse" ) {
// mouse code
} else if ( inputState === "keyboard" ) {
// keyboard code
} else {
// Function was called directly
}
// Reset input State after processing
inputState = null
}
This will likely need some adjustments but I hope you can use this to find the correct answer.
Edit:
My answer is a vanilla JS solution, if you have access to jQuery you may want to investigate the click and keyup event handlers.
Use document.activeElement, it is supported in all major browsers. It can give you the current active element.
EDIT
Oops I think I misunderstood your question. you want to identify the mouse or keyboard or programmatic
For programmatic
if(e.hasOwnProperty('originalEvent')) {
// Focus event was manually triggered.
}
To differentiate between keyboard and mouse based focus events
You have to hack it by adding an extra keydown event and understand. You can not differentiate it like you want.
If you want to check wheather < select > is clicked by keyboard or mouse,
you can use mousedown() and keypress() event
$('select').mousedown(function(e){
//your code on mouse select
});
and
$('select').keypress(function(e){
//your code on key select
});