Click or key press - javascript

I'm trying to trigger something to happen either when I press the escape key or when I click on an element. I've tried using..
if( $( '#some_id' ).click() || e.keyCode == 27 )
{
alert( 'Click or esc' );
}
But that doesn't seem to be working, is there something else I can use? If I do each individually like..
$( '#some_id' ).click(...);
or..
if( e.keyCode == 27 )
it works without a problem, but I'd prefer to have it working together to avoid code duplication. Sorry if it's something stupid I missed but would really like to get this sorted.
Thanks :)

Use .bind() .on() (as of jQuery 1.7) passing in multiple events:
$("#some_id").on("click keyup", function (e) {
if (e.type == "click" || e.keyCode == 27) {
alert("click or esc");
}
});

You mentioned code duplication. Why not do them separately, but put the code you want to execute for both of them into a function:
$('#some_id').click(function () {
doStuff();
});
$('#some_id').keypress(function (e) {
if (e.keyCode == 27) doStuff();
});
function doStuff() {
alert('Click or esc');
}

Related

window.location.reload(); fails unless coupled with an alert

In my MVC javascript, I have the following code:
addEvent(document.getElementById("mta"), 'keydown', function() {
var keycode = event.which || event.keyCode;
if (keycode == 27) {
//alert(x);
window.location.reload(true);
return
}
etc...
The idea is to clear all input when the user presses the escape key. This doesn't work unless the alert is un-commented. Browser is Firefox. WTH ?
I had early today a similar problem. One of the mistakes I can see is event.keyCode, which is depreciated right now, you can replace it with event.key.
I leave you the code that worked for me.
addEventListener("keyup", function(event) {
if (event.key === "Escape") {
event.preventDefault();
window.location.reload(true);
}
});

An elegant way of handling click and keypress in the same function

I have a bunch of places where I have to code the same functionality for a click and an ENTER key press (keyup). I'm ending up writing event handlers like this:
$('#SomeElement').on('click keyup', function (e) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
// do what needs to be done
}
});
Is there an elegant way of handling this without the if statement? I hate the fact that it's an event handler specific to click and keyup, yet I have to check the event type inside the handler.
EDIT: I'm OK with abstracting out the if statement into a separate function. As long as I don't have to copy/paste the same line of code over and over again.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(function( $ ) {
$.fn.clickOrKeyPress = function( callback ) {
this.on('click keyup', function (e) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
callback(e);
}
});
return this;
};
}( jQuery ));
You will need an if condition to confirm if the key pressed is enter. So you cannot completely get rid of if condition there.
But you can get rid of redundant conditions, like you don't need to check if the event type is keyup as we know if the event is not click, it will definitely be a keyup event.
So you can reduce your condition to
e.type === 'click' || e.keyCode === 13
My final solution - jQuery Event Extensions.
Create jQuery event extension specific for ENTER key.
$.event.special.enterkey = {
delegateType: 'keyup',
bindType: 'keyup',
handle: function (event) {
if (event.keyCode === 13)
return event.handleObj.handler.apply(this, arguments);
}
};
Now all I have to do is the following. Neat and elegant.
$('#SomeElement').on('click enterkey', function (e) {
// do what needs to be done
});
P.S. To all the incognito downvoters - you should be ashamed of yourselves.
I have not tested this yet, but maybe you can do named function and pass it with another callback to the event handler?...
Example (not tested!):
// Define the callback function somewhere
function clickKeyupCallback(e, callback) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
return callback;
}
}
$('#SomeElement').on('click keyup', clickKeyUpCallback(e, function() {
// your normal code here
}));
// EDIT
I realized the named function has to sit on a different place here if you want to do it this way and abstract the "if" part.
another example:
// Define the callback function somewhere
function clickKeyupCallback(e, callback) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
callback();
}
}
$('#SomeElement').on('click keyup', function(e) {
clickKeyupCallback(e, function() {
// do what ever needs to be done
});
});
I didn't understand clearly what you mean by "I have a bunch of places where I have to code the same functionality". But according to my understanding you want to attach some handlers to some elements that involve this check.
function doSomething(e) {
//do what needs to be done
}
function handleEvent(attachedHandler) {
return function(e) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
attachedHandler(e);
}
};
}
$('#SomeElement').on('click keyup', handleEvent(doSomething));
lemme know if it helps you...

Add keypress or eventlistener to input, "TypeError: ...addEventListener is not a function"

I'm working on a form where I do not want enter/return to submit the form so I used a function like this.
$('[name="form"]').keypress(function(e) {
var charCode = e.charcode || e.keyCode || e.which;
if (charCode === 13) {
e.preventDefault();
return false;
}
});
That works, but now I want to assign the enter/return to perform functions on two inputs on the form. I'm totally stuck.
To get the inputs I've tried vanilla js calling by id, jQ calling by id and then a mixer of the two with variables. I've also tried .keypress, .keydown, .keyup instead of the attachEventListener method. No matter what I do, I get this error in console.
"TypeError: ...addEventListener is not a function" (or keypress, keydown etc.)
I've also researched a good deal but can't find any solution. I appreciate any suggestions.
Here is this block of code in it's current form that's giving the trouble.
var yelpInput = $('#inputURL');
var googleInput = $('#googleURL');
yelpInput.addEventListener("keydown", function(e) {
if (e.keyCode === 13 ) {
alert('do stuff!');
}
});
// Google
googleInput.addEventListener("keydown", function(e) {
if (e.keyCode === 13 ) {
alert('do stuff!');
}
});
Thanks
var yelpInput = $('#inputURL');
var googleInput = $('#googleURL');
yelpInput.keydown(function(e) {
if (e.keyCode === 13 ) {
alert('do stuff!');
}
});
// Google
googleInput.keydown(function(e) {
if (e.keyCode === 13 ) {
alert('do stuff!');
}
});
yelpInput is jQuery wrapped object which does not have addEventListener method.
Use .on to attach event-handler on jQuery wrapped object or yelpInput[0].addEventListener/yelpInput.get(0).addEventListener to attach event using JavaScript as yelpInput[0] will be an DOMElement not jQuery-wrapped object.
var yelpInput = $('#inputURL');
var googleInput = $('#googleURL');
yelpInput.on("keydown", function(e) {
//-----^^^
if (e.keyCode === 13) {
alert('do stuff!');
}
});
googleInput.on("keydown", function(e) {
//-------^^^
if (e.keyCode === 13) {
alert('do stuff!');
}
});

How to handle multiple buttons enter key functionality?

In my page there are two buttons. For enter key functionality I have written the following jQuery code.
$(function () {
$("#first-button-id").keyup(function (e) {
if (e.keyCode == '13') {
e.preventDefault();
}
}).focus();
$("#second-button-id").keyup(function (e) {
if (e.keyCode == '13') {
e.preventDefault();
}
}).focus();
});
But always when click on enter key first one is firing. Please tell me how to handle the multiple button enter key functionality.
Try something like this
HTML :
<label>TextBox : </label>
<input id="textbox" type="text" size="50" />
<label>TextBox 2: </label>
<input id="textbox2" type="text" size="50" />
JQuery
$('#textbox , #textbox2').keyup(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed a "enter" key in textbox');
}
event.preventDefault();
}).focus();
DEMO
Some browser prefer keycode and other use which ... I suggest you to use both..
You do not need to focus on two buttons at the same time. Try doing something like this:
$("#button1").keypress(function(event){
if ( event.which == 13 ){
//Do something}
$("#button2").keypress(function(event){
if( event.which == 13 ){
//Do something else}
The problem i think is with your event.preventDefault() function which stops the propogation of the event once a function is executed. In your case, your first function might be getting completed before the second one and hence the second one gets aborted in the middle.
$("#first-button-id , #second-button-id ").keyup(function(event){
if ( event.which == 13 ) {
alert("you pressed enter.");
event.preventDefault();
}
}
The reason the first submit button is always firing is because that's the default behavior of a web page which you haven't actually altered with your code.
Try this:
$(function () {
$("#first-button-id, #second-button-id").keyup(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
if (e.keyCode == '13') {
$(this).trigger("click");
}
});
});
What you seem to be asking about strikes me as rather odd. It looks like you want second-button to be 'clicked' if the focus is on second-button and enter is pressed. Tabbing until the focus is on the correct button is really the only practical way this could happen.
Try this.
$('#first-button-id').on("keydown", function (e)
{
if (e.keyCode == 13)
{
e.preventDefault();
$("first-button-id").click();
}
});

jquery code is not workign after postback

I wrote the following jquery code to allow only numbers in a textbox.
$("[id$='txtPriority']").keydown(function (event) {
if (event.keyCode == 48) {
var value = $("[id$='txtPriority']").val();
if (value == "") {
event.preventDefault();
return;
}
}
else if (event.keyCode == 86 || event.keyCode == 118) {
event.preventDefault();
return;
}
else {
$("[id$='txtPriority']").numeric();
}
});
});
This works fine ,when the page is loaded for first time.But after post back the code is not working.What might be the reason.
I you are changing something with ajax then the event will not work.
Try using the live function ( http://api.jquery.com/live/ )
$("[id$='txtPriority']").live('keydown', function (event) {
I had this problem once and it was because I was replacing the html for the form in the postback. You need to reset your event handlers after replacing the controls or use the .live() handler which will work even for elements you add later:
$("[id$='txtPriority']").live('keydown', function (event ) {

Categories

Resources