jQuery calling a method on 2 different events - javascript

I have 2 events; one for when i click a button and the other for when i press my down arrow.
They are both reffering to the same method. My code for that looks like this:
$('.button').on('click', function() {
someMethod();
});
$(document).keydown(function(e) {
if (e.keyCode === 40) {
someMethod();
return false;
}
});
Is there a better or shorter way to do this? Also when i want to add another event to it?

Make your method as you required
pass "e" for KeyDown and not pass "e" for click and then check e in your function
if(typeof e != "undefined" && e.keyCode === 40)
I hope you get it

You can shorten the first one by passing the handler reference instead of calling it through anonymous function.
$('.button').on('click', someMethod);

Related

how to write a jasmine spec for triggering a on event in jquery

how to write a jasmine spec for triggering a on event in jquery ?
$('#myid').on('keyup', function (event)
{
if(event.which === 13)
{
event.preventDefault();
myfunc(id);
}
});
those lines are not covered by jasmine spec how to write jasmine specs for those lines.
only triggering event didnt cover those lines so help me here
I don't know how you wrote your spec but try the below code
var event = $.Event("keyup");
event.which = 13;
$("#myid").trigger("keyup");
// expectations follow
If it still doesn't work, try using a separate named function instead of anonymous function as follows:
$('#myid').on('keyup', keyupHandler.bind(this));
function keyupHandler() {
if(event.which === 13){
event.preventDefault();
myfunc(id);
}
}

key down listner event not working in firefox

I have a 'keydown' event on javascript for navigating table using arrow keys:
my code as follows:
document.onkeydown= function() { keyDown();};
The implementation code as follows:
function keyDown(e){
var evt=(e)?e:(window.event)?window.event:null;
var key = evt.keyCode || evt.which;
if(key==38 || key==40){
alert("working");
}
}
How can I make it works on all browsers? What I am doing wrong here?
You need to pass the event variable that the system passes in to your function or use the standardised addEventListener method:
// Passing the event
document.onkeydown = function(e) { keyDown(e); };
// Using event listeners
document.addEventListener('keydown', keyDown, false);
Then you should rely on the event passed - do not use window.event - if the event is not passed to your function you have bigger issues to worry about than finding the event.
function keyDown(e){
if(e.which == 38 || e.which == 40){
alert("working");
}
}
I would learn more about the addEventListener method as assigning functions to the documents own onEvent attributes is not advised. What if you want to change this later? What if you want to add some code some of the time? Event Listeners are great for that and they don't modify the default behaviour here. You can add and remove these on the fly, making it much more versatile. Have a read here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Combining 2 jQuery functions

My jQuery is starting to get unnecessarily long. Is there a way to easily combine these 2 functions. My first thought is to create a custom event out of the key down function. Any solutions or suggestions on what to read up on would be appreciated.
$('th:nth-child(3):first').click(function () {
$('#dtSelect').val(2).change();
});
$('th:nth-child(3):first').keydown(function(event){
if(event.keyCode==13){
$('#dtSelect').val(2).change();
}
});
Simply:
$('th:nth-child(3):first').on('change keydown', function(event) {
if(!event.keyCode || event.keyCode==13){
$('#dtSelect').val(2).change();
}
});
This will fire on both change and keydown events, and will only call change() if event.keyCode does not exist (change) or is equal to 13 (keydown).
function combined(event) {
if (typeof event === 'undefined' || event.keyCode==13)
$('#dtSelect').val(2).change();
}
$('th:nth-child(3):first').click(combined).keydown(combined);
although in this case I don't think it's worth combining them.

Keypress events in Dojo's on module

I have started using Dojo's new on module to add my events. It works fine, but now I've run into a problem. When using keypress event I can't seem to get the character value (for example "2" or "b") from the pressed key. Previously I've used the behaviormodule, and the connect module, and then I have been able to get it by using e.keyChar or e.charOrCode, but now they´re undefined.
I have an event set up like this:
on(element, 'keypress', function(e)
{
console.log(e.keyCode); //works, but not what I need
console.log(e.charOrCode); //undefined
console.log(e.keyChar); //undefined
});
How do I get the character of a pressed key when using this module?
In this case, I think what you want is to use e.keyCode in conjunction with the JS-native String.fromCharCode() in order to get the desired character value.
on(element, 'keypress', function(e) {
var character = String.fromCharCode(e.keyCode);
if (character === 'a') { // do a stuff } else { // do something else }
}

Two elements using the same event function

What is the best way to share one function between two different event handlers? I want the same outcome but some situation dependent variables will need to be defined within the function depending on which element was clicked.
I could hack a solution but want to know the best practice for such a scenario. Simple problem must have a simple answer.
EXAMPLE
var onMyEvent = function(e){
if(click triggered from 'a'){
//do that
}
if(click triggered from 'div'){
//do that
}
}
$('a').click(onMyEvent);
$('div').click(onMyEvent);
FIDDLE: http://jsfiddle.net/f6C92/
I guess there'd be several ways to achieve this, such as checking the e variable for target objects, etc, but for your scenario, the easiest and most readable would be using the is() function, to which you can pass any CSS selector to test if the object of interest matches it.
var onMyEvent = function(e){
if($(this).is('a')){
//do that
}
if($(this).is('div')){
//do that
}
}
$('a').click(onMyEvent);
$('div').click(onMyEvent);
There are those who would argue that the above takes an unnecessary round-trip to jQuery, when you could achieve the same by testing this.tagName == 'A', but I usually recommend to delegate these things to jQuery as well, for browser compatibility reasons.
Another neat way would be to pass the relevant information as event data:
var onMyEvent = function(e){
if(e.data.type == 'a'){
//do that
}
...
}
$('a').click({ type: 'a' }, onMyEvent);
$('div').click({ type: 'div' }, onMyEvent);
It depends how complicated the differences are, but I don't really like checking element type in the handler. I would probably do something like this:
function doSomething(...){
// do stuff
}
$('a').click(function(){
// set some variables and send them as parameters to doSomething
doSomething(...);
});
$('div').click(function(){
// set some variables and send them as parameters to doSomething
doSomething(...);
});
Where doSomething contains the common code.
The target property of the event will contain the element that was clicked. In this updated fiddle, I alert the id of the clicked element, using e.target.id.
This ought to do the trick:
var onMyEvent = function(e) {
if (this.tagName == "A") {
alert("a");
} else if (this.tagName == "DIV") {
alert("div");
}
}
var onMyEvent = function(e){
if(this.tagName == 'A'){
alert("a");
}
if(this.tagName == 'DIV'){
alert("div");
}
}
$('a').click(onMyEvent);
$('div').click(onMyEvent);
Even if this will work in my opinion it's better to set a different handler for each tag, and call the same function inside it, like kingjiv suggested

Categories

Resources