Create common keydown function with ID/Class - javascript

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') ;
})

Related

Adding event on "Enter Key" for two filters

I just set up a couple of functions that are executed upon users pressing the "ENTER" keyword. I was wondering if anyone has a more elegant solution or if this would be the only option?
I was looking at others' solutions and I couldn't find anything else. The reason is that both inputs belong to the same functions thus I'm curious to see a different approach. Here is my code:
This is the code on "search btn" click:
const searchBtnHandler = () => {
let countryValue = countryFilterAccess.value.trim().toUpperCase();
let searchCategory = searchCategoryMenu.value.trim();
if (countryValue === '' && searchCategory === '') {
return;
}
console.log(countryValue, searchCategory);
const results = filteredItems(countryValue, searchCategory);
if (results.length === 0) {
alert(`Not Items Found :(, Please Try Again`);
} else {
for (let el of itemElements) {
el.style.display = 'none';
}
results.forEach((result) => {
document.getElementById(result.id).style.display = 'grid';
});
if (!document.getElementById('cancel-search-btn')) {
addCancelFilterBtn();
} else {
return;
}
}
};
Below the code I created for action on "ENTER"
countryFilterAccess.addEventListener('keyup', (event) => {
if (event.keyCode === 13) {
event.preventDefault();
searchBtnAccess.click();
}
});
searchCategoryMenu.addEventListener('keyup', (event) => {
if (event.keyCode === 13) {
event.preventDefault();
searchBtnAccess.click();
}
});
I just want to see if there is a way to merge the two event listeners in one function.
Thank you!
function callbackFn(event){
if (event.keyCode === 13) {
event.preventDefault();
searchBtnAccess.click();
}
}
countryFilterAccess.addEventListener('keyup', callbackFn);
searchCategoryMenu.addEventListener('keyup', callbackFn);
why can't you try this way,
const listner = (event) => {
if (event.keyCode === 13) {
event.preventDefault();
searchBtnAccess.click();
}
}
countryFilterAccess.addEventListener('keyup', listner);
searchCategoryMenu.addEventListener('keyup', listner);
You can have the elements in an array and loop through them:
[countryFilterAccess, searchCategoryMenu].forEach(function(el){
el.addEventListener('keyup', (event) => {
if (event.keyCode === 13) {
event.preventDefault();
searchBtnAccess.click();
}
});
});
I came out with this.
const filterInputs = [countryFilterAccess, searchCategoryMenu];
filterInputs.forEach((element) => {
element.addEventListener('keyup', (event) => {
if (event.keyCode === 13) {
event.preventDefault();
searchBtnAccess.click();
}
});
});

Onkeydown not working javascript

Here is my code
document.onkeydown = function (a) {
if (a.which == 13) {
alert("Not Anymore");
}
}
document.onkeydown = function (b) {
if (b.which == 65) {
auto();
}
}
document.onkeydown = function (c) {
if (c.which == 83) {
auto2();
}
}
Only the last snippet works can someone explain why this is happening
check my website and you can see it isnt working when you press a but when you press b it is
Thanks, I appreciate the help and feedback
You're binding the same event on the document multiple times. So, the later event handlers override the previous event handlers just like the functions with same name does. You need to bind only one event handler and use if... else in it.
You can use this
document.onkeydown = function (e) {
if (e.which == 13) {
alert("Not Anymore");
} else if (e.which == 65) {
auto();
} else if (e.which == 83) {
auto2();
}
};
Also, use addEventListener instead of onkeydown.
document.addEventListener('keydown', function (a) {
if (a.which == 13) {}
...
}, false);

Toggling a function that depends on a button state?

I'm trying to turn a button-click into a toggle that enables or disables a function, depending on its state. The function allows the enter key to be used for a form submission.
var enterToggle = true;
function enterToggleListener(elem) {
enterKeyPress();
elem.click(function() {
enterToggle = !enterToggle;
console.log('enter-toggle clicked')
if (enterToggle === false) {
console.log('enter toggle false')
// What do I need to add here to stop 'enterKeyPress()'?
} else {
console.log('enter toggle true')
enterKeyPress();
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(e.which == 13){
$('#noteButton').click();
}
});
}
enterToggleListener($('#toggle-button'));
What I don't understand is how to stop the enterKeyPress() function when enterToggle is false. Any suggestions?
EDIT: Cleaned-up code, with #James Montagne's answer added
var enterToggle = true;
function enterToggleListener(elem) {
elem.click(function() {
enterToggle = !enterToggle;
if (enterToggle === false) {
$('#enter-toggle').text('Enter key saves note (OFF)')
} else {
$('#enter-toggle').text('Enter key saves note (ON)')
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
enterKeyPress();
enterToggleListener($('#enter-toggle'));
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
You can simply check the value of the variable within your handler. This way you don't need to keep adding and removing the handler as seems to be your current approach.
However, if you must add and remove for some reason, you would use off.

Detecting keystrokes without textboxes?

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
}
});​

keydown Event to override return key does not work in Firefox

I have the following simple javascript code, which handles the Return Key, I don't want to submit the form when the return key is pressed in the textbox.
All this works fine, but in Firefox, if i show an alert message, then it stops working and the form starts getting submitted, whereas the exact code without alert message works fine and stops the form from being submitted. I dont understand why alert is spoiling the party..
$("document").ready(function () {
$("#input1").keydown(OnKeyDown);
});
function OnKeyDown(e) {
if (e.keyCode == 13) {
// alert('this will fail'); // Adding alert makes the form submit
stopBubble(e);
return false;
}
}
function stopBubble (e) {
// If an event object is provided, then this is a non-IE browser
if (e && e.stopPropagation)
// and therefore it supports the W3C stopPropagation() method
e.stopPropagation();
else
// Otherwise, we need to use the Internet Explorer
// way of cancelling event bubbling
window.event.cancelBubble = true;
}
<input type="text" id="input1" value="">
I don't really know if the event is normalized or not. But this is how I have to do it for it to work in all browsers:
$(whatever).keypress(function (e) {
var k = e.keyCode || e.which;
if (k == 13) {
return false; // !!!
}
});
jQuery normalizes this already, you can just do:
$(document).ready(function () {
$("#input1").keydown(OnKeyDown);
});
function OnKeyDown(e) {
if (e.which == 13) { //e.which is also normalized
alert('this will fail');
return false;
}
}
When you do return false from a handler, jQuery calls event.preventDefault() and event.stopPropgation() internally already. You can also do the anonymous function version:
$(function () {
$("#input1").keydown(function() {
if (e.which == 13) return false;
});
});
textBox.onkeydown = function (e) {
e = e || window.event;
if (e.keyCode == 13) {
if (typeof (e.preventDefault) == 'function') e.preventDefault();
if (typeof (e.stopPropagation) == 'function') e.stopPropagation();
if (typeof (e.stopImmediatePropagation) == 'function') e.stopImmediatePropagation();
e.cancelBubble = true;
return false;
}
}

Categories

Resources