I want to be able to open an alternate link when I click by holding down the alt button. I've tried some solutions but they seem to have weird problems. All I want is when clicking to detect if the alt key is held down
function selectlink(selection,alt) {
if (alt key is pressed) {
window.open(alt,'_blank');
} else {
window.open(selection,'_blank');
}
In the body:
Click
Preferably WITHOUT Jquery.
You have to reference the event as a parameter, this will make it possible to check if a key was pressed during the click.
function selectlink(selection, alt, e) {
if (e.altKey) {
alert(alt);
} else {
alert(selection);
}
}
Click
With a little bit of rewriting you can make the link a bit smarter and still have functioning links when javascript is disabled.
function selectLink(e) {
var el = e.target;
if (e.altKey) {
window.open(el.getAttribute("alternative"), '_blank');
e.preventDefault();
}
}
Click
Here's a solution using jQuery. I'll write a solution using pure JS in my lunch break.
https://jsfiddle.net/jotq0atz/2/
X
Here is the js:
$("#x").on('click', function(e){
link = $(e.currentTarget).attr('href');
alt_link = $(e.currentTarget).attr('data-alt-href');
if(e.altKey){
alert("alt was held while clicking");
window.open(alt_link, '_blank');
} else {
alert("alt wasn't held while clicking");
window.open(link, '_blank');
}
});
Here's a solution made by adapting the answer provided in javascript alt key
var altdown = false;
document.onkeydown = KeyCheck;
document.onkeyup = KeyCheck;
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
case 18:
document.Form1.KeyName.value = "Alt";
if(e.type == "keydown"){
altdown = true;
}
else if(e.type == "keyup"){
altdown = false;
}
break;
}
}
function selectlink(selection,alt) {
if (altdown) {
window.open(alt,'_blank');
} else {
window.open(selection,'_blank');
}
}
The link opened in dependent on the altdown variable which is true when the alt key is pressed down. A working fiddle can be seen here. https://jsfiddle.net/q5kr9h2o/7/
Related
So basically i am trying to connect clicking links to keys in Tampermonkey. First I tried e.which, but it didn't work with different layouts. Then I tried e.code, but for some reason it only detects pressing the B key (see code below). What did I do wrong?
$(document).on("keypress", function (e) {
if(e.сode == "KeyN") {
document.getElementById("nextimage").click();
} else if(e.code == "KeyB") {
document.getElementById("previmage").click();
}
});
You can try using the KEY itself instead of the code. The toUpperCase() function will detect lowercase or uppercase :
$(document).on("keypress", function (e) {
if(e.key.toUpperCase() == "N") {
alert("yay!")
} else if(e.key.toUpperCase() == "B") {
alert("nay");
}
});
Here's a reference with the different key codes: https://keycode.info/
Try this to read keys.
Make sure you have the JQuery reference.
$(document).keypress(function(event) {
alert('You pressed - ' + event.key.toUpperCase());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
and here is javascript in case:
const myText = document.getElementById('myText');
document.addEventListener('keypress', logKey);
function logKey(e) {
myText.textContent += e.key.toUpperCase();
if(e.key.toUpperCase() == 'N')
alert("You Pressed N key");
}
and
<p id="myText"></p>
I'm trying to show a font awesome '?' after every element that has the ".info" class when the user is holding down the "alt" key. It appears to be working but when i release "Alt" and try to press it again nothing happens. But when i click the document it works again. See code sample:
jQuery(document).ready(function ($) {
var keyDown = false;
$(document).on("keydown", function (e) {
console.log(keyDown);
if (e.key == "Alt") {
if (!keyDown) {
$('.info').each(function () {
$(this).after("<a style=\"color:black;postion:absolute;\"><i class=\"fas fa-info-circle\"></i></a>");
});
}
keyDown = true;
}
});
$(document).on("keyup", function (e) {
if (e.key == "Alt") {
console.log("alt released");
$('.info').each(function () {
$(".fa-info-circle").remove();
});
keyDown = false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="info">Test</p>
EDIT: When using another key (i tested "i") it seems to work fine so i think it might be a Chrome issue.
Chrome has a number of keyboard shortcuts that use alt - for instance alt + home takes you to your home page.
you can see all the shortcuts here:
https://support.google.com/chrome/answer/157179?hl=en-GB
if you want to override Chrome's behaviour (which I do not recommend), you could add e.preventDefault() to your keydown function.
I have made divs in my HTML that I use to draw bars with CSS.
Now I want the to values change when the user presses the down arrow key.
This is my JavaScript:
var changeIdValue = function(id, value) {
document.getElementById(id).style.height = value;
};
window.addEventlistener("onkeydown", function(e){
if(e.keyCode == 40){
changeIdValue("balklongwaarde", "60px");
});
}
I don't understand why this is not working.
I know this has been answered already, but if you want to follow your original idea, here's the correct code (because Mritunjay's answer only works for one usage per page).
var changeIdValue = function (id, value) {
document.getElementById(id).style.height = value;
};
window.addEventListener('keydown', function (e) {
if (e.keyCode === 40) {
changeIdValue('balklongwaarde', '60px');
}
});
addEventListener is written with a capital L in Listener
'onkeydown' should be 'keydown' when used with the addEventListener function
You closed your brackets in the wrong order (close if, close function, close function call)
You can say something like this
window.onkeydown = function(e){
if(e.keyCode == 40)
changeIdValue("balklongwaard", "60px");
};
This question already has answers here:
How can I check if a key is pressed during the click event with jQuery?
(5 answers)
Closed 5 years ago.
I need to know if the user is clicking or CONTROL CLICKING a div element.
I have seen examples on how to do it using event listeners.. but my code is already set in place, and is using an on-element onclick method..
HTML
<div id='1' onclick='selectMe()'>blah</div>
JS
function selectMe(){
//determine if this is a single click, or a cntrol click
}
...also would love to know if it was a left or right mouse button click.
In your handler, check the window.event object for the property ctrlKey as such:
function selectMe(){
if (window.event.ctrlKey) {
//ctrl was held down during the click
}
}
UPDATE:
the above solution depends on a proprietary property on the window object, which perhaps should not be counted on to exist in all browsers. Luckily, we now have a working draft that takes care of our needs, and according to MDN, it is widely supported. Example:
HTML
<span onclick="handler(event)">Click me</span>
JS
function handler(ev) {
console.log('CTRL pressed during click:', ev.ctrlKey);
}
The same applies for keyboard events
See also
KeyboardEvent.getModifierState()
2021 UPDATE: There are better ways to do this now. Please be sure to check out the other answers
I'd recommend using JQuery's keyup and keydown methods on the document, as it normalizes the event codes, to make one solution crossbrowser.
For the right click, you can use oncontextmenu, however beware it can be buggy in IE8. See a chart of compatibility here:
http://www.quirksmode.org/dom/events/contextmenu.html
<p onclick="selectMe(1)" oncontextmenu="selectMe(2)">Click me</p>
$(document).keydown(function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
$(document).keyup(function(){
cntrlIsPressed = false;
});
var cntrlIsPressed = false;
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}
Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.
Here's the code for a modern implementation using jQuery:
$( 'div#1' ).on( 'click', function( event ) {
if ( event.ctrlKey ) {
//is ctrl + click
} else {
//normal click
}
} );
As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.
$( 'div#1' ).on( 'contextmenu', function( event ) {
// right-click handler
} ) ;
When there is a mouse click ctrlKey is event attribute which can be accessed as e.ctrlKey.
Look down for example
$("xyz").click(function(e)){
if(e.ctrlKey){
//if ctrl key is pressed
}
else{
// if ctrl key is not pressed
}
}
note: https://www.w3schools.com/jsref/event_key_keycode.asp
Try this code,
$('#1').on('mousedown',function(e) {
if (e.button==0 && e.ctrlKey) {
alert('is Left Click');
} else if (e.button==2 && e.ctrlKey){
alert('is Right Click');
}
});
Sorry I added e.ctrlKey.
Try this:
var control = false;
$(document).on('keyup keydown', function(e) {
control = e.ctrlKey;
});
$('div#1').on('click', function() {
if (control) {
// control-click
} else {
// single-click
}
});
And the right-click triggers a contextmenu event, so:
$('div#1').on('contextmenu', function() {
// right-click handler
})
You cannot detect if a key is down after it's been pressed. You can only monitor key events in js. In your case I'd suggest changing onclick with a key press event and then detecting if it's the control key by event keycode, and then you can add your click event.
From above only , just edited so it works right away
<script>
var control = false;
$(document).on('keyup keydown', function (e) {
control = e.ctrlKey;
});
$(function () {
$('#1x').on('click', function () {
if (control) {
// control-click
alert("Control+Click");
} else {
// single-click
alert("Single Click");
}
});
});
</script>
<p id="1x">Click me</p>
pure javascript:
var ctrlKeyCode = 17;
var cntrlIsPressed = false;
document.addEventListener('keydown', function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
document.addEventListener('keyup', function(){
if(event.which=="17")
cntrlIsPressed = true;
});
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}
I'd like to add support for keyboard shortcuts to a couple of pages in my web application by intercepting the keypress event handler of the document object, not the accesskey attribute.
The problem is that every browser has its own keyboard combinations, so it's impossible to come up with a set of keyboard combinations that work on all web browsers and yet consistent.(e.g. It'd be silly if the shortcut for save was Ctrl + Shift + S while one for delete was Alt + D.)
So I figured it would be just simpler to override browser shortcuts altogether in a couple of pages with mine.
All downside aside, is it possible? If so, how do you do it?
onkeydown = function(e){
if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){
e.preventDefault();
//your saving code
}
}
There's an excellent coverage of this here: http://unixpapa.com/js/key.html
As for whether this is something that should be done, stackoverflow's question editor override's quite a few keys without disrupting too much (hover over the toolbar buttons).
Here is my solution to this problem:
Most (if not all) of the browser's shortcuts will be overriden. Only system ones, like Alt + Tab or the Windows key won't.
document.onkeydown = overrideKeyboardEvent;
document.onkeyup = overrideKeyboardEvent;
var keyIsDown = {};
function overrideKeyboardEvent(e){
switch(e.type){
case "keydown":
if(!keyIsDown[e.keyCode]){
keyIsDown[e.keyCode] = true;
// do key down stuff here
}
break;
case "keyup":
delete(keyIsDown[e.keyCode]);
// do key up stuff here
break;
}
disabledEventPropagation(e);
e.preventDefault();
return false;
}
function disabledEventPropagation(e){
if(e){
if(e.stopPropagation){
e.stopPropagation();
} else if(window.event){
window.event.cancelBubble = true;
}
}
}
Here is my Solution:
document.onkeydown = function () {
if ((window.event.keyCode == 121) && (window.event.ctrlKey))) {
window.event.returnValue = false;
window.event.cancelBubble = true;
window.event.keyCode = 0;
return false;
}
}