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.
Related
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/
We've been busy with upgrading TinyMCE from 3.x to 4.2.5 and can not prevent the default ENTER action from happening.
Our goal is to submit the form when CTRL + enter is pressed, and important is that the submit should happen before the newline is added to TinyMCE. The 3.x branch allowed us to add the event to the top of the queue:
// Important: inject new eventHandler via addToTop to prevent other events
tinymce.get('tinymce_instance').onKeyDown.addToTop(function(editor, event) {
if (event.ctrlKey && event.keyCode == 13) {
$("form").submit();
return false;
}
});
Unfortunately we can not figure out how to add it to the top of the events again.
event.preventDefault() and event.stopPropagation() do not have the expected effect because the enter is already there. The weird thing is that it does work on other keys, the alphanumeric keys can be prevented. http://jsfiddle.net/zgdcg0cj/
The event can be added using the following snippet:
tinymce.get('tinymce_instance').on('keydown', function(event) {
if (event.ctrlKey && event.keyCode == 13) {
$("form").submit();
return false;
}
});
Problem: the newline is added to the TinyMCE content earlier as our event handler is called, so an unwanted enter is stored. How can I add the event to the top in the 4.x branch, or prevent the newline from happening?
event.preventDefault() works when you attach the keydown event via the setup on the init function.
tinymce.init({
selector:'textarea',
setup: function (ed) {
ed.on('keydown',function(e) {
if(e.ctrlKey && e.keyCode == 13){
alert("CTRL + ENTER PRESSED");
e.preventDefault();
}
});
}
});
This does block the carriage return from happening. JsFiddle
Edit:
Above is one way of doing it, I have found another way of achieving the result which doesn't require the init at all. Instead we create a new Editor instance and bind to our textarea given it has an id.
HTML
<form>
<!--Select by ID this time -->
<textarea id='editor_instance_1'>A different way</textarea>
</form>
JS
var ed = new tinymce.Editor('editor_instance_1', {
settings: "blah blah"
}, tinymce.EditorManager);
//attach keydown event to the editor
ed.on('keydown', function(e){
if(e.ctrlKey && e.keyCode == 13){
alert("CTRL + ENTER");
e.preventDefault();
}
});
//render the editor on screen
ed.render();
var init {
...,
setup: function (ed) {
ed.on('keydown', function (e) {
if (e.ctrlKey && 13 === e.keyCode) {
e.preventDefault();
$("form").submit();
}
});
};
tinymce.init(init);
Works for tinyMCE 4.x
Maybe I'm late, but this answer is for those who cannot(or don't want to) change init setup for tinymce. I found following method:
var frame = document.getElementById('id_of_editor_iframe');
var iframeDocument = fr.contentWindow.document;
iframeDocument.addEventListener('keydown', function(e) {
if (
[38, 40, 13].indexOf(e.keyCode) > -1 //Enter and up/down arrows or whatever you want
) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
// your code here
return false;
}
}, true);
It helped me to prevent new line in editor
I want to prevent the default event on key #93 (select, between alt gr and ctrl right on AZERTY keyboard).
This key open context menu like right click.
I tried :
$(document).off('keydown');
$(document).off('keyup');
$(document).off('keypress');
$(document).on('keypress', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
$(document).on('keyup', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
$(document).on('keydown', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
Nothing works... I have always the contextmenu.
After checking for a while, I've been headed to another question similar to this one, but with a very different matter.
In any case, since the problem is the context menu, you don't even need jQuery for such, and the solution (despite it WON'T always work in firefox because the user may set it to disable such) is this one:
document.oncontextmenu = function (e) {
e.preventDefault();
return false;
}
fiddle:
http://jsfiddle.net/0kkm1vq0/3/
Works on chrome as well, and you won't need to use the keyboard listeners.
Reference: How to disable right-click context-menu in javascript
(which is really the same as key #93).
** note that this will disable the right click too **.
EDIT:
Not sure if this is cross-browser (the UPDATED code below seems to be working for both chrome and firefox, didn't try IE and others though), but the event fired by key #97 seems to be identified as 1, while the click seems to be identified as key 3, so you can just:
(function($){
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
$(document).on('keyup', function(e) {
e.which == 93 && e.preventDefault();
});
}
else {
document.oncontextmenu = function (e) {
e.which == 1 && e.preventDefault();
}
}
})(jQuery);
http://jsfiddle.net/0kkm1vq0/10/
To disable JUST the key and not the right click.
I am trying to close bootstrap popover using ESC key press.
But it does not seem to be working when using:
$(document).keyup(function (event) {
if (event.which === 27) {
$('#example').popover('hide');
}
});
Here is the fiddle with bootstrap popover:
http://jsfiddle.net/mashinista/b2NKt/
The fiddle you included has the popover code, but not the escape code.
Add it and, as koala_dev pointed out, you should be fine:
Demo in fiddle
$('#example').popover();
$(document).keyup(function (event) {
if (event.which === 27) {
$('#example').popover('hide');
}
});
Also, this is very similar to how the modal escape function works
The problem with that arises when a tooltip is inside of a modal, because then the Esc key is expected to close the modal. It's a not good user experience if a user only wants to dismiss the tooltip but then the entire modal closes. So I would propose, if there are currently tooltips to dismiss, then a user will need to press Esc twice to close the modal (first time to dismiss tooltips), but otherwise once, as usually. Note: This is not ideal, especially for screen reader users, so take that as a food for the further thinking.
/**
* Accessibility: Close tooltips and popovers on ESC key (WCAG 1.4.13)
* Note: Using event capture:true to cancel the propagation preventing the modal to close at first (hence no `.on()` here)
* Tested with Bootstrap v3.4.1; Does not support IE 11
*/
$.fn.listenEscKeyToCloseOverlays = function () {
return this.each(function () {
if (("undefined" !== typeof $.fn.tooltip) || ("undefined" !== typeof $.fn.popover)) {
document.addEventListener('keydown', function(e) {
if ('Escape' === e.key) {
const $openTooltips = $('.tooltip');
const $openPopovers = $('.popover');
if ($openPopovers.length || $openTooltips.length) {
e.stopPropagation();
$openTooltips.tooltip('hide');
$openPopovers.popover('hide');
}
}
}, true);
}
});
};
$(document).listenEscKeyToCloseOverlays();
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;
}
}
}