Detecting keystrokes without textboxes? - javascript

I have to use javascript to make links instead of for several unimportant reasons, and I want for it to behave like even though im not using it. Not the affects thats easy, but I want to be able to hold down shift while clicking to open a new window and to open it in a new tab if they are holding down ctrl. How would I do this? Also, it has to be compatible with IE9.
[edit] Also, this is going to be in an iframe

I guess you want something like this:
JSFiddle
http://jsfiddle.net/MXuVY/3/
JavaScript
var ctrlPressed = false;
$('#link').click(function () {
var link = 'http://stackoverflow.com/';
if (ctrlPressed) {
window.open(link,'_blank');
} else {
window.location = link;
}
return false;
});
$(document).keydown(function (e) {
if (e.keyCode === 17) {
ctrlPressed = true;
}
});
$(document).keyup(function (e) {
if (e.keyCode === 17) {
ctrlPressed = false;
}
});
​
HTML
<span id="link">Link to stackoverflow</span>​
​Version without jQuery
JSFiddle
http://jsfiddle.net/MXuVY/6/
JavaScript
function addEvent(el, eType, fn, uC) {
if (el.addEventListener) {
el.addEventListener(eType, fn, uC);
return true;
} else if (el.attachEvent) {
return el.attachEvent('on' + eType, fn);
} else {
el['on' + eType] = fn;
}
}
var ctrlPressed = false,
a = document.getElementById('link'),
link = 'http://stackoverflow.com/';
addEvent(a, 'click', function () {
if (ctrlPressed) {
window.open(link,'_blank');
} else {
window.location = link;
}
return false;
});
addEvent(document, 'keydown', function (e) {
if (e.keyCode === 17) {
ctrlPressed = true;
}
});
addEvent(document, 'keyup', function (e) {
if (e.keyCode === 17) {
ctrlPressed = false;
}
});
​

Bind a keystroke event listener to window or document and use it's callback function to do whatever you need.
If you use jquery, its a bit easier to make a more reliable keystroke listener, imho. http://blog.cnizz.com/2008/10/27/javascript-key-listener/

So, this is what you want: http://jsfiddle.net/DerekL/V8yzF/show
$("a").click(function(ev) {
if (ev.ctrlKey) { //If ctrl
window.open(this.attr("href"));
retrun false;
} else if (ev.shiftKey) { //If shift
window.open(this.attr("href"),"_blank", "width=400,height=300");
retrun false;
} else { //If nothing
//do nothing
}
});​

Related

Create common keydown function with ID/Class

While working on Compliance for the buttons clicks, I happen to add several keydown events but with different classes and ID's triggering the onclick inside the condition if pressed Enter Key. I want to put all of the several methods under one function and re-use that
$(".classOne").keydown(function (e) {
if (e.keyCode === 13) {
hideShow('classOne');
return false;
}
});
$("#iDOne").keydown(function (e) {
if (e.keyCode === 13) {
navigateTo('somepage');
return false;
}
});
$(".classTwo").keydown(function (e) {
if (e.keyCode === 13) {
$(".classTwo").trigger("click");
return false;
}
});
$(".classThree").keydown(function (e) {
if (e.keyCode === 13) {
navigateTo('anotherpage');
return false;
}
});
$(".classFour").keydown(function (e) {
if (e.keyCode === 13) {
$(".classFour").trigger("click");
return false;
}
});
$("#idTwo").keydown(function (e) {
if (e.keyCode === 13) {
$("#idTwo").trigger("click");
return false;
}
});
I'm learning to write functions etc, so pardon my novice-ness here
$(".targetClass").keydown(function (e) {
if (e.keyCode === 13) {
// do the click/navigate/showhide...
}
});
targetClass being changed to the clicked element/ID
How can I do something like above, re-using the same method while passing the ID/Class(whichever is on the html element) and trigger the onclick and avoid writing same functions numerous times?
Thank you in advance for the suggestions.
Your click operations seem to fall into a number of categories. If you add the operation to the element, then your code can determine what to do without knowing what that actual element is, eg:
<button type="button" data-operation="click">click</button>
<button type="button" data-operation="navigate" data-navigate="anotherpage">another page</button>
You could then handle these in a single function:
$(".targetClass").keydown(function (e) {
if (e.keyCode === 13) {
switch ($(this).data("operation")) {
case "click":
$(this).trigger("click")
return false;
case "navigate":
navigateTo($(this).data("navigate"));
return false;
or (preferred) you could then add handlers per operation:
$(".targetClass[data-operation=click]").keydown(function(e) {
if (e.keyCode === 13) {
$(this).trigger("click");
return false;
}
});
$(".targetClass[data-operation=navigate]").keydown(function(e) {
if (e.keyCode === 13) {
navigateTo($(this).data("navigate"));
return false;
}
});
Depending on the operations, and your preference, you can use classes for these (which may be more efficient for the selector, not tested, possibly micro-optimisation), eg:
<button type="button" class="targetClass trigger-click">click</button>
<button type="button" class="targetClass trigger-navigate" data-navigate="anotherpage">another page</button>
then similar split event handlers:
$(".targetClass.trigger-click").keydown(function(e) {
if (e.keyCode === 13) {
$(this).trigger("click");
return false;
}
});
$(".targetClass.trigger-navigate").keydown(function(e) {
if (e.keyCode === 13) {
navigateTo($(this).data("navigate"));
return false;
}
});
Using separate handlers means extending to new functionality will less likely affect existing code (ie improved maintainability). If you want to add a new operation:
$(".targetClass.trigger-show").click(function() {
$($(this).data("trigger")).toggle();
}
You can probably make use of an array of the attributes to loop through them:
var elList = [".classOne","#iDOne",".classTwo",".classThree",".classFour","#idTwo"];
elList.forEach(function(el){
$(el).keydown(function(e){
if (e.keyCode === 13) {
if($(this).hasClass('classOne')){
//do your staff
console.log('classOne');
}
else if($(this).attr('id') == 'iDOne'){
//do your staff
console.log($(this).attr('id'));
}
//do it for all
//
//
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="classOne" >classOne
<input id="iDOne">iDOne
Use some thing like this
function KeyDown(ele, type) {
var $selector = null;
if (type == 'cssClass') {
$selector = $("." + ele);
else if (type == "id")
$selector = $("#" + ele);
}
$selctor.on("keydown", function(e) {
if (e.keyCode === 13) {
switch (ele)
case "classOne":
hideShow('classOne');
return false;
break;
case "iDOne":
navigateTo('somepage');
break;
case "classTwo":
$(".classTwo").trigger("click");
break;
case "classThree":
navigateTo('anotherpage');
break;
case "classFour":
$(".classFour").trigger("click");
break;
case "idTwo":
$("#idTwo").trigger("click");
break;
return false;
}
})
$(function(){
KeyDown('classOne', 'cssClass');
KeyDown('iDOne', 'id') ;
KeyDown('classTwo', 'cssClass');
KeyDown('classThree', 'cssClass');
KeyDown('classFour', 'cssClass');
KeyDown('idTwo', 'id') ;
})

How can I fire the unload method when closing the browser?

Observed scenarios:
When closing the browser, the beforeunload event is fired but the unload event isn't fired.
When closing the tab, both the beforeunload event and the unload event are fired.
Question:
How can I fire the unload method when closing the browser?
Code:
var inFormOrLink = false;
var flag = false;
$(document).ready(function () {
$(window).bind("beforeunload", function () {
return "You are about to close the window";
});
$(window).on("unload", function () {
if (!inFormOrLink)
window.open('../Account/Login?admin=admin', "_blank");
});
});
$(function () {
$("a").click(function () {
if (!flag) {
inFormOrLink = true;
$(window).unbind('beforeunload');
$(window).unbind('unload');
}
else {
// inFormOrLink = false;
$(window).bind('beforeunload');
$(window).bind('unload');
}
});
$(".btn").click(function () {
if (!flag) {
inFormOrLink = true;
$(window).unbind('beforeunload');
$(window).unbind('unload');
}
else {
inFormOrLink = false;
flag = false;
$(window).bind('beforeunload');
$(window).bind('unload');
}
});
$("body").keydown(function (e) {
if (e.which == 116 || e.which == 117) {
inFormOrLink = true;
}
else if (e.ctrlKey && e.keyCode == 82) {
inFormOrLink = true;
}
else if (e.which == 8) {
var tag = e.target.tagName.toLowerCase();
inFormOrLink = true;
if (tag != "input") {
e.preventDefault();
}
}
else {
inFormOrLink = false;
$(window).bind('unload');
}
});
});
'
The onunload event theoretically should run in the case you mentioned, however, there are many browsers and each is implemented by a different team. Since you observed a bug in a few browsers, I suggest that you should attach the event handlers to beforeunload instead of unload. In that case you work around the problem. Another possiblity is to run the unload event, like this:
$(window).unload();

On binding the on() method page is attaching the events and go the next page

My problem is that when I try to bind the click event using JQuery on(). It doesn't go the next page.
What is your favorite color?This input is required.
$('#continue-bank-login-security-question-submit').off('click');
$('#continue-bank-login-security-question-submit').on('click',function(e){
e.preventDefault();
e.stopPropagation();
if ($('.tranfer--bank-security-question-inputs').val().length===0){
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
return true;
}
});
Because you call
e.preventDefault();
e.stopPropagation();
of course it does not do anything after returning.
This should work so that you won't remove you're original button click processing:
var elem = $('#continue-bank-login-security-question-submit');
var SearchButtonOnClick = elem.get(0).onclick;
elem.get(0).onclick = function() {
var isValid = false;
var sessionKey = '';
if ($('.tranfer--bank-security-question-inputs').val().length===0){
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
SearchButtonOnClick();
}
};
You could try this:
<button id="continue-bank-login-security-question-submit" onclick="return Validate();">Next</button>
function Validate() {
if ($('.tranfer--bank-security-question-inputs').val().length === 0) {
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
nextPage();
}
}

jQuery wait for keyup after keydown

I'd like to trigger an event once after key down and a different event only after the down arrow key has been released, like so:
$('body').keydown(function (e)
{
if(e.keyCode==40)
{
//do something
}
$('body').keyup(function (d)
{
if(d.keyCode==40)
{
//do something else
}
}
}
This code only functions partially. The keydown is triggered continuously as the down arrow key is held.
I have a setInterval whose refresh rate I'm altering when I hold the arrow key. Unforunately setTimeOut isn't an option in this situation.
So my code looks something like this:
clearInterval(interval);
refresh = 100;
interval();
$('body').keydown(function (e) {
if(e.keyCode==40) {
//do something
}
return false;
})
.keyup(function(e) {
if(e.keyCode==40) {
//do something else
}
return false;
});
$('body').on('keyup', function (e) {
if(e.keyCode==40) {
//do something
}
// after first keyup set to handle next keydown only once:
$(this).one('keydown', function(e) {
if(e.keyCode==40) {
//do something else
}
});
});
If you need exactly trigger the event and not handle as it's in your example, then you need to use $.trigger() method.
If you want to do some action only once while the key remains pressed, simply keep track of that:
var arrowKeyDown = false;
$('body').keydown(function(e) {
if (e.which == 40 && !arrowKeyDown) {
arrowKeyDown = true;
// ...
}
});
$('body').keyup(function(e) {
if (e.which == 40) {
arrowKeyDown = false;
}
});
Demo: http://jsfiddle.net/utfwQ/
$('body').keydown(function (e)
{
console.log('down');
}​).keyup(function(e){console.log('up')});​​​​
If you really need to remove the keyup listener when you're done,
http://jsfiddle.net/CgmCT/
document.body.addEventListener('keydown', function (e) {
if(e.keyCode === 40){
console.log('key 40 down');
// key down code
document.body.addEventListener('keyup', function listener(d){
if(d.keyCode === 40){
document.body.removeEventListener('keyup', listener, true);
console.log('key 40 up');
// key up code
}
}, true);
}
}, true);​

Disabling page zoom in IE7 (jQuery/JS)

I know this is not the best thing to do in view of accessibility, but I have a genuine need to disable the user from zooming onto the page using CTRL+ in IE7.
I got it working for the other browsers the following way, but IE7 seems to ignore the "return false":
$(window).keydown(function (e) {
alert('key is down'); // this fires
return false; // but this has no effect in IE7!
});
This is better and correct way:
$(document).ready(function() {
var ctrl = false;
$(document).keydown(function(e){
// disable ctrl + +/-
if(ctrl && (e.keyCode == 107 || e.keyCode == 109)) {
alert('Zoom is disabled!');
return false;
}
if(e.keyCode == 17) {
ctrl = true;
// disable ctrl + scroll
$(document).bind('scroll', function() {
if(ctrl) {
alert('Zoom is disabled!');
return false;
}
});
}
})
$(document).keyup(function(e) {
if(e.keyCode == 17) {
ctrl = false;
$(document).unbind('scroll');
}
});
});
Try attaching keydown to document instead:
$(document).keydown(function (e) {
alert('key is down');
return false;
});
This is pointless if the end user's browser already has the zoom set before visiting your page.
simple answer. for IE, you need Event.stop(e); instead of return false;
I don't have IE7 to test on ATM but this should do it
$(window).keydown(function (e) {
alert('key is down'); // this fires
e.preventDefault(); // This is a standard jQuery way of
// preventing the default action
return false; // Therefore you shouldn't need this.
});

Categories

Resources