How to call the same function in two different ways? - javascript

I am trying to combine a function which will display alert (ofcourse I have a lot of code In this function but for this case It will be alert) after:
Click on element with class .number
Change select[name=receive]
I have this code but it doesn't work:
$(document).on(("click",".number"),("change","select[name=receive]"),function(){
alert('test');
})

Try this
function doMyWork() {
console.lot( 'TEST' );
}
$('.number').on('click', doMyWork);
$('select[name=receive]').on('change', doMyWork);
Or, if your elements are inserted after DOM ready:
You do not have to use this form if the target elements exist at DOM ready
function doMyWork() {
console.lot( 'TEST' );
}
$(document).on('click', '.number', doMyWork)
.on('change', 'select[name=receive]', doMyWork);

Try this
$(document).on("click change","select[name=receive], .number", function(){
alert('test');
});
Or
var fn = function () {
alert('test');
}
$(document).on("click", ".number", fn);
$(document).on("change", "select[name=receive]", fn);

You cannot separate events and selectors in a single .on() call. You have two options here. You can use them together....
$(document).on("click change", ".number, select[name=receive]"),function(){
alert('test');
});
...however this means that .number will listen to both click and change, possible resulting in the function running 2 times.
You need to move the function outside and reuse it for every handler
var al = function(){
alert('test');
};
$('.number').on('click', al);
$('select[name=receive]').on('change', al);

$(document).on("click change",".number, select[name=receive]", function(){
alert('test');
})

I am not sure where you learned that syntax, but that is not how on() works.
Use a named function and share it.
(function(){
var shared = function(){
console.log(this);
}
$(document)
.on("click",".number", shared)
.on("change","select[name=receive]", shared);
}());

Related

jQuery - undefined function call on click

I want to call a function on the click event, my collegue defined the function as written below. Somehow I cannot access it, what is wrong?
function Start(data) {
this.move= function() {
....
};
$('.button').click(function(){
this.move();
});
}
this in a click function is the clicked element. Save a reference of the object in a variable outside the function and use it :
function Start(data) {
var self = this; //HERE
this.move= function() {
....
};
$('.button').click(function(){
self.move();
});
}
Here's an article that may give you more explanation about the above fix.
try this, you must remember reference to your main function.
function Start(data) {
var that = this;
this.move = function() {
....
};
$('.button').click(function(){
that.move();
});
}
Another way to keep the scope is to use jQuery's proxy()
$('.button').click($.proxy(this.move, this));
In an event handler bound with jQuery, this refers to the DOM element on which the handler was bound. See jQuery Event Basics.
You can override jQuery's this binding by using function#bind on the click handler:
function Start(data) {
this.move= function() {
....
};
$('.button').click(function(){
this.move();
}.bind(this));
}
Beware of browser support for function#bind -- if you target older browsers you'd need a polyfill or simply assign the value of this to another variable.

Multiple functions for mouse events jquery

I'm working on a jQuery plugin. To separate my logic I do something like this:
$element.on({
mouseenter: function(){
//do something special
}, mouseleave: function(){
//do something else special
}
});
//more stuffs
and then above this I do that again but with other function body
$element.on({
mouseenter: function(){
//do something not special
}, mouseleave: function(){
//do something else not special
}
});
How does jQuery deal with this ? Will 2nd declaration of mouse events function override the first one ? Sometimes I see both things works but sometimes not.
Will 2nd declaration of mouse events function override the first one ?
No.
How does jQuery deal with this ?
It executes your event handlers in the order in which they were attached. From the documentation (about 40% down the page):
Event handlers bound to an element are called in the same order that they were bound.
So for instance, if you have:
var div = $("#someDiv");
div.on("click", function() { console.log("one"); });
div.on("click", function() { console.log("two"); });
div.on("click", function() { console.log("three"); });
...then clicking the div will give you
one
two
three
...in the console.
Note that it doesn't matter how you found the element to attach the handlers. Let's say you have only one div on the page, it has the id "someDiv", and it's the first child of body (just to make the selectors easy). If you have:
$("#someDiv").on("click", function() { console.log("one"); });
$(document.body).children().first().on("click", function() { console.log("two"); });
$("div").on("click", function() { console.log("three"); });
and you click the div, you'll get
one
two
three
...in the console.

jQuery onClick multiple callbacks

How do I register multiple callbacks for a jQuery event? An example of what I am trying to achieve:
$(document).on("click", ".someclass", CallbackFunction1, CallbackFunction2);
function CallbackFunction1(event) {
//Do stuff
}
function CallbackFunction2(event) {
//Do some other stuff
}
How can I set up the event handler to execute both callback functions when the element is clicked?
You can just attach them as separate event handlers:
$(document).on("click", ".someclass", CallbackFunction1)
.on("click", ".someclass", CallbackFunction2);
Unless I misunderstand what you're asking, you can use a single event handler:
$(document).on('click', '.someclass', function(e){
CallbackFunction1(e);
CallbackFunction2(e);
});
You can use a third function and then recall the other ones:
$(document).on("click", ".someclass", CallbackFunction);
function CallbackFunction(event) {
CallbackFunction1(event);
CallbackFunction2(event);
}
function CallbackFunction1(event) {
//Do stuff
}
function CallbackFunction2(event) {
//Do some other stuff
}
If you will be reusing this to bind different list of handlers for different elements, i would create a factory.
function multiFunction(){
var methods = Array.prototype.slice.call(arguments, 0);
return function(e){
for (var f=0, l = methods.length; f<l; f++) {
methods[f].apply(this, arguments);
}
}
}
and call this like this
$(document)
.on('click', 'someclass', multiFunction( CallbackFunction1, CallbackFunction2));
.on('click', 'someotherclass', multiFunction( CallbackFunction8, CallbackFunction1, CallbackFunction5));
Demo at http://jsfiddle.net/gaby/D8K75/

call many functions on document change

I have few namespaces and I want to reinitialize function inside namespaces on document change in order to be reinitialized every time when the document is modified (*modified = adding/removing new sections on existing dom ).
I have tried this but not working so far:
;namespaceName= {
namespaceFunction1: function() {
$( selector ).on('click', function() {
//my first function run here
})
},
// ************second function in namespace***************/
namespaceFunction2: function() {
$(secondSelector).on('click', function() {
//my second function run here
})
}
}
$(document).on('change', namespaceName.namespaceFunction1() );
$(document).on('change', namespaceName.namespaceFunction2() );
Pls help, ty.
Try this...
$(document).on("DOMSubtreeModified", function () {
namespaceName.namespaceFunction1();
namespaceName.namespaceFunction2();
});
It fires your 2 functions on the DOMSubtreeModified event, which is basically what you were looking for - when the DOM changes.
sounds like you need to listen for the DOMSubtreeModified event like this:
$('body').bind('DOMSubtreeModified', function(){
//your code here
});

User-defined callback function is being fired multiple times in Javascript/jQuery

There are some similar questions, but they all seem like regarding native jQuery callback functions.
So I have this code which (live) creates a div containting some form elements.
Values of these elements should be retrieved inside a callback function when (before) the div is removed.
function popup(callback) {
// ...
// before removing the div
callback.call();
// remove div
}
Unexpectedly, the callback function is being fired multiple times (increasingly) after the first time popup is executed.
I have simplified the code, and here is the fiddle.
I hope this is what you need.
function popup(callback) {
$("body").append('<div><span id="test">test</span> close</div>');
$(document).on("click", "#close", function() {
callback.call();
//
//callback = function() {};
$(document).off("click", "#close");
$("div").remove();
});
};
$(document).on("click", "#open", function() {
popup(function() {
alert('$("#test").length = ' + $("#test").length);
});
});
Basically, you need to remove event handler by invoking off() method.
Try dynamically generating the elements instead of using a string. This will allow you to bind events easier.
function popup(callback)
{ var $elem = $("<div></div>");
$elem.append($("<span></span>").html("test"));
$elem.append(" ");
$elem.append($("<a></a>").html("close").attr("href", "#"));
$("body").append($elem);
$elem.find("a").click(function() {
callback.call();
$elem.remove();
});
};
$(document).on("click", "#open", function() {
popup(function() {
alert('$("#test").length = ' + $("#test").length);
});
});
Example: http://jsfiddle.net/4se7M/2/
I don't know the exact scenario, but why do you want to bind and unbind the event each time you show the popup?
You can bind only once, like this, can't you?
$(document).on("click", "#close", function() {
alert('$("#test").length = ' + $("#test").length);
$("div").remove();
});
function popup() {
$("body").append('<div><span id="test">test</span> close</div>');
};
$(document).on("click", "#open", function() {
popup();
});

Categories

Resources