Using window.onkeyup in two different JavaScript files - javascript

I have a web app that uses multiple JavaScript files. I have two event handlers like this in two files:
window.onkeyup = function (e) { SomeFunction1(e) }
window.onkeyup = function (e) { SomeFunction2(e) }
SomeFunction1 is in a file that's used in every part of the site but SomeFunction2 is in a file that's only used in one part of the site.
The problem is that when I include the JavaScript file that contains the handler for SomeFunction2, it replaces the handler for SomeFunction1, which means the event doesn't trigger any more.
Instead of replacing the window.onkeyup handler, I want to add another handler in the javascript file that contains SomeFunction2 so that both functions are called. How can I do that? jQuery available.

You can use on event function for this:
$(window).on('onkeyup', SomeFunction1);
$(window).on('onkeyup', SomeFunction2);
Or using vanilla JS
window.addEventListener('onkeyup', SomeFunction1);
window.addEventListener('onkeyup', SomeFunction2);

If jQuery available, you could easily add as many listener as you want
$(window).on("keyup", function(){alert(1);});
$(window).on("keyup", function(){alert(2);});
Try it on https://jsfiddle.net/45zf9vkd/

That's because you're using the DOM attribute to attach the handler, and there can only be one.
You're better off using the addEventHandler API:
document.querySelector('foo').addEventListener('click', function(){
// Your code goes here
})
OR
document.querySelector('foo').addEventListener('click', someFunction);
function someFunction(){
// Your code goes here
}
You can add as many as you want.

Try this ;)
Add this in a common file:
window.onkeyup = function(e){
try{
SomeFunction1(e);
}catch(e){}
try{
SomeFunction2(e);
}catch(e){}
}
And include your files where SomeFunction1(e) and SomeFunction2(e) where you need them?

You will need to use addEventListener to have multiple handlers for a DOM element e.g.:
document.querySelector('#elementID').addEventListener('keyup', function(){...
If you already have jQuery set up (it is not worth adding jQuery to your site just for this), you can use
$(window).on('keyup', function(){...
This will only add additional handlers and won't overwrite any existing ones

Related

Call a function saved to a variable that has an event handler attached to it

Hi I am currently trying to call a function that is saved to a variable, but also has an event handler on it.
col.onclick = function(e){
}
I have not been able to find how to call this kind of set up, and was wondering if it's possible at all, and if it can be done without using jquery.
Help would be nice, thanks in advance.
http://pastebin.com/JJYQeZDG //Code that is the root of the problem.
This code is for a game of checkers, for context.
Simply use () like any other function.
Based on your comments, it looks like you may also have a scoping issue.
I would recommend refactoring your code so your onclick function can be accessed without needed the col object:
var onclick = function(e) {
// note: you will only have "e" if this is invoked as an event callback
};
// later when defining col
col.onclick = onclick;
// ...and later when you want to directly invoke onclick
onclick();

Having multiple window.onload functions in multiple script files

I'm building a site and I have loads of scripts going on there, theyre all contained in different files and some of them are onload functions. I know about using a function to run all of them. However this doesn't work so well with multiple files. I've tried using an onload.js file:
window.onload = function() {
// Site wide funcs
searchShow();
// Page specific
if(getProducts && loadMore){
getProducts();
loadMore();
}
if(checkBox){
checkBox();
}
if(styleProduct) {
styleProduct();
}
}
where it should check if the function exists on the page before running it. (Some files are referenced in each file some are site wide and are referenced in the header file)
Could anyone suggest a better option for having all these onload files?
In your script files stick to addEventListener or attachEvent, as both allow multiple handlers for single event.
EDIT
As these two functions are browser specific, it is a good idea to start with some kind of wrapper:
function createEvent(objectTarget, eventName, eventHandler)
{
if (objectTarget.addEventListener)
objectTarget.addEventListener(eventName,eventHandler,false);
else if (objectTarget.attachEvent)
objectTarget.attachEvent('on'+eventName,genericHandler);
}
Now use createEvent to attach new handler to specific event.
createEvent(window, 'load', handler1);
createEvent(window, 'load', handler2);
...
Please take into account, that there are more severe differences in event model between browser (such as where is event object or target vs. srcElement).

jQuery.off not working with a variable function name

I'm using a modular pattern for writing my Javascript code, and it is totally fun! But I'm stuck very badly at one situation.
My Namespace is as follows:
var settings, handlers, objects,
Namespace = {
handlers: {
//All event handlers go here
},
objects: {
//All jquery button references go here
},
init: function(){
//Initial stuff
}
};
//Call init with the Namespace
I have a button which toggles between two different handlers for a mousedown event on a single object (a div), and handlers are properties of the handlers object. On init, one handler is automatically on to the div and works fine. Now when I click the toggle button, I'm trying to turn off the first handler so I can turn on the other, but it isn't working!
I turn on my first mousedown event handler (or all handlers for that matter!) like this:
Namespace.objects.someObject.on('mousedown', Namespace.handlers.mouseDownHandlerOne);
This works fine. When I try to turn it off like this:
Namespace.objects.someObject.off('mousedown', Namespace.handlers.mouseDownHandlerOne);
It doesn't work! No errors or warnings. If I just use off with mousedown without passing the handlers name, it works. But I need to separate between 2 different handlers!
How should it be done in a modular js environment?
Jquery .off method can take up to 3 arguments, use the following code:
Namespace.objects.someObject.off('mousedown', '**', Namespace.handlers.mouseDownHandlerOne);

Get value of current event handler using jQuery

I can set the onclick handler using jQuery by calling
$('#id').click(function(){
console.log('click!');
});
Also using jQuery, how can I get a reference to the function which is currently handling the click() event?
The reason is that I have another object and want to set its click handler to the same one as #id.
Update
Thank you for all the suggestions. The problem is that I do not know which function is currently handling the clicks. Keeping track of it would add state to an already complicated template-editing system.
jQuery's .click(function) method adds the function to a queue that is executed on the click event~
So actually pulling out a reference to the given function would probably be hairy-er than you expect.
As noted by others, it would be better to pass in a reference to the function; and then you already have the reference you need.
var clicky = function () { /* do stuff */ };
$('#id').click(clicky);
// Do other stuff with clicky
Update
If you really really need to get it out, try this:
jQuery._data(document.getElementById('id')).events.click[0].handler
Depending on your version of jQuery that may or may not work~ Try playing around with
jQuery._data(document.getElementById('id'))
and see what you get.
Got the idea from this section of the source:
https://github.com/jquery/jquery/blob/master/src/event.js#LC36
if you dont know the name of the function you can use
args.callee
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee
function clickHandle(e){
if($(e.target) == $('#id')) {
$(newTarget).bind('click', clickHandle);
}
}
$('#id').bind('click',clickHandle);
I think this would be the most symantic way of going about it

Can you bind to jQuery events with plain JavaScript?

I'm working on a project where a number of different companies are working on the same site.
The main developer have set up an event - let's call it init - which indicates the page is ready for our code to execute.
They're basically calling it like this:
$(window).trigger('init');
For a number of reasons I won't go into here, we prefer to avoid using jQuery in our own code wherever possible. I tried to bind to it like this:
window.addEventListener('init', function (event) {
alert('hehehehe');
});
But that doesn't seem to work. This works perfectly, though:
$(window).bind('init', function (event) {
alert('hehehehe');
});
Does jQuery use special event objects by default that you can't bind to with plain JS? Am I just doing something stupid?
The docs for bind seem to contain the answer:
Any string is legal for eventType; if the string is not the name of a native DOM event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler().
There's no native DOM event called 'init':
http://en.wikipedia.org/wiki/DOM_events
Hence "These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler()"

Categories