I have this function:
$("#btn").click(function(e,someOtherArguments)
{ //some code
e.stopPropagation();});
It works, but If I have named function I can't use e because it is undefined.
var namedFunction= function(e,someOtherArguments)
{
//some code
e.stopPropagation();
}
$("#btn").click(namedFunction(e,someOtherArguments));
I would like to use this namedFunction because several buttons use it.
Either:
$("#btn").click(namedFunction);
Or:
$("#btn").click(function(e,someOtherArguments){
namedFunction(e, someOtherArguments);
});
You can call that function directly in the click event
$("#btn").click(function(e,someOtherArguments){
namedFunction(e, someOtherArguments);
});
You can use apply like so:
$("#btn").click(function(e,someOtherArguments){
namedFunction.apply(this, arguments);
});
Related
I feel like this is one of those problems you only run into after too little sleep or too many coffees...
I have an element
<a id="blah" href="#">somethinghere.com</a>
I define a function
function test(){
alert('hi');
};
I try to attach the function as a click-handler(https://jsfiddle.net/8r1rcfuw/30/):
$('#blah').on('click', test());
and load the page, and the handler executes immediately - without any clicks.
However when I just use an anonymous function as a handler(https://jsfiddle.net/8r1rcfuw/36/) :
$('#blah').on('click', function(){
alert('hi');
});
it works fine
Doing both (https://jsfiddle.net/8r1rcfuw/39/):
$('#blah').on('click', function(){
test();
});
function test(){
alert('hi');
}
seems to work fine - but seems a little redundant.
This feels like something I've done 1000 times before - what gives?
The event handler has to be a function, and you are passing the result of a function to it:
$('#blah').on('click', test());
is the same as:
$('#blah').on('click', undefined); //As your funcion doesn't return anything
Think of it as a function is a value, you can do:
var myFunction = function() {
alert("Hi");
}
or
function myFunction() {
alert("hi");
}
And then:
$('#blah').on('click', myFunction); //Without invocation!
or using an anonymous function:
$('#blah').on('click', function() {
alert("Hi");
});
You can also use object of function :
var temp=function test() {
alert('hi');
}
$('#blah').on('click', temp);
Try :
$('#blah').on('click', test); // your function name only
Updated Fiddle
I am trying to understand the difference between these two callback methods and how they handle the $(this) context.
Working Example
$("#container").on("click",".button", function() {
$(this).text("foo");
});
This process works just fine. However, if I want to do a different approach, I lose the context of the event.
Non-Working Example
bindAnEventToAnElement: function(theElement, theEvent, theFunctions) {
$("body").on(theEvent, theElement, function() {
theFunctions();
});
}
bindAnEventToAnElement(".button", "click", function() {
$(this).text("foo");
});
The latter produces an undefined error. Is there a way I can handle callbacks like this while retaining the context of the event?
Fiddle
http://jsfiddle.net/szrjt6ta/
AFAIK, jquery's this in that callback function refers to the event.currentTarget value. So, you should also pass the event object and do something like this:
$("#container").on("click", ".button", function () {
$(this).text("foo");
});
theApp = {
bindAnEventToAnElement: function (theElement, theEvent, theFunctions) {
$("body").on(theEvent, theElement, function (e) {
theFunctions.apply(this /* or e.currentTarget */, arguments);
});
}
}
theApp.bindAnEventToAnElement(".button-two", "click", function () {
$(this).text("foo");
});
Working Fiddle
If I try to explain the problem, jquery is binding the callback function to pass this as e.currentTarget. But you are passing an another callback function inside that callback function whose scope will not be its parent callback function but will be the window. So, you need to again bind the this to the wrapped function, which you can do using apply or call.
You have to manually bind the context to the function in order to have this valorized inside your callback:
$("body").on(theEvent, theElement, function() {
theFunctions.apply(this);
});
example http://jsfiddle.net/szrjt6ta/1/
Find more about apply() here
you can pass the event, then use $(e.target)
https://jsfiddle.net/szrjt6ta/3/
Use .call(this) The call() method calls a function with a given this value and arguments provided individually.
Note: While the syntax of this function is almost identical to that of
apply(), the fundamental difference is that call() accepts an argument
list, while apply() accepts a single array of arguments.
$("#container").on("click",".button", function() {
$(this).text("foo");
});
theApp = {
bindAnEventToAnElement: function(theEvent, theElement, theFunctions) {
$("body").on(theEvent, theElement, function() {
theFunctions.call(this);
});
}
}
theApp.bindAnEventToAnElement("click", ".button-two", function() {
$(this).text("fooe");
});
Fiddle
Change the event handler attachment from
$("body").on(theEvent, theElement, function() {theFunctions();});
to
$("body " + theElement).on(theEvent, theFunctions);
Like this:
HTML:
<div id="container">
<a class="button">Button</a><br />
<a class="button-two">Button Binded</a>
</div>
JQuery:
$("#container").on("click",".button", function() {
$(this).text("foo");
});
theApp = {
bindAnEventToAnElement: function(theElement, theEvent, theFunctions) {
$("body " + theElement).on(theEvent, theFunctions);
}
}
theApp.bindAnEventToAnElement(".button-two", "click", function() {
$(this).text("foo");
});
Fiddle: https://jsfiddle.net/szrjt6ta/10/
Good Day, this maybe a silly question :) how can I pass a parameter to an external javascript function using .on ?
view:
<script>
var attachedPo = 0;
$this.ready(function(){
$('.chckboxPo').on('ifChecked', addPoToBill(attachedPo));
$('.chckboxPo').on('ifUnchecked', removePoToBill(attachedPo ));
});
</script>
external script:
function addPoToBill(attachedPo){
attachedPo++;
}
function removePoToBill(attachedPo){
attachedPo--;
}
but Im getting an error! thanks for guiding :)
You need to wrap your handlers in anonymous functions:
$('.chckboxPo')
.on('ifChecked', function() {
addPoToBill(attachedPo);
})
.on('ifUnchecked', function() {
removePoToBill(attachedPo);
});
You can also chain the calls to on as they are being attached to the same element.
If your intention is to count how many boxes are checked, via passing variable indirectly to functions try using an object instead like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pBkhX/
var attachedPo = {
count: 0
};
$(function () {
$('.chckboxPo')
.on('change', function () {
if ($(this).is(':checked')) {
addPoToBill(attachedPo);
} else {
removePoToBill(attachedPo);
}
$("#output").prepend("" + attachedPo.count + "<br/>");
});
});
function addPoToBill(attachedPo) {
attachedPo.count++;
}
function removePoToBill(attachedPo) {
attachedPo.count--;
}
If it is not doing anything else you can simplify the whole thing to count checked checkboxes:
$(function () {
var attachedPo = 0;
$('.chckboxPo')
.on('change', function () {
attachedPo = $(".chckboxPo:checked").length;
});
});
"DOM Ready" events:
you also needed to wrap it in a ready handler like this instead of what you have now:
$(function(){
...
});
*Note: $(function(){YOUR CODE HERE}); is just a shortcut for $(document).ready(function(){YOUR CODE HERE});
You can also do the "safer version" (that ensures a locally scoped $) like this:
jQuery(function($){
...
});
This works because jQuery passes a reference to itself through as the first parameter when your "on load" anonymous function is called.
There are other variations to avoid conflicts with other libraries (not very common as most modern libs know to leave $ to jQuery nowadays). Just look up jQuery.noConflict to find out more.
i try to pass paramater to function. When i click the div it will alert the paramater that i pass
i have 2 file
index.html
script.js
here's what i try
Example 1
index.html
<div id="thediv" >
script.js
window.onload = initialize;
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = myFunction(" something ");
}
//end of bind
//function
function myFunction(parameter) { alert( parameter ) };
//end of all function
the trouble is the function its executed without click
Example 2
index.html
<div id="thediv" onclick="myfunction('something')" >
script.js
function myFunction(parameter) { alert( parameter ) };
yap its done with this but the trouble if i have many element in index.html it will painful to read which element have which listener
i want to separate my code into 3 section (similiar with example1)
the view(html element)
the element have which listener
the function
what should i do? or can i do this?
(i don't want to use another library)
Placing () (with any number of arguments in it) will call a function. The return value (undefined in this case) will then be assigned as the event handler.
If you want to assign a function, then you need to pass the function itself.
...onclick = myFunction;
If you want to give it arguments when it is called, then the easiest way is to create a new function and assign that.
...onclick = function () {
myFunction("arguments");
};
Your first solution logic is absolutely ok .. just need to assign a delegate ... what you are doing is calling the function .. So do something like this ...
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function () { myFunction(" something "); };
}
//end of bind
Instead of assign you invoke a function with myFunction();
Use it like this
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function(){
myFunction(" something ");
}
}
How do you call function lol() from outside the $(document).ready() for example:
$(document).ready(function(){
function lol(){
alert('lol');
}
});
Tried:
$(document).ready(function(){
lol();
});
And simply:
lol();
It must be called within an outside javascript like:
function dostuff(url){
lol(); // call the function lol() thats inside the $(document).ready()
}
Define the function on the window object to make it global from within another function scope:
$(document).ready(function(){
window.lol = function(){
alert('lol');
}
});
Outside of the block that function is defined in, it is out of scope and you won't be able to call it.
There is however no need to define the function there. Why not simply:
function lol() {
alert("lol");
}
$(function() {
lol(); //works
});
function dostuff(url) {
lol(); // also works
}
You could define the function globally like this:
$(function() {
lol = function() {
alert("lol");
};
});
$(function() {
lol();
});
That works but not recommended. If you're going to define something in the global namespace you should use the first method.
You don't need and of that - If a function is defined outside of Document.Ready - but you want to call in it Document.Ready - this is how you do it - these answer led me in the wrong direction, don't type function again, just the name of the function.
$(document).ready(function () {
fnGetContent();
});
Where fnGetContent is here:
function fnGetContent(keyword) {
var NewKeyword = keyword.tag;
var type = keyword.type;
$.ajax({ .......
Short version: you can't, it's out of scope. Define your method like this so it's available:
function lol(){
alert('lol');
}
$(function(){
lol();
});
What about the case where Prototype is installed with jQuery and we have noconflicts set for jQuery?
jQuery(document).ready(function($){
window.lol = function(){
$.('#funnyThat').html("LOL");
}
});
Now we can call lol from anywhere but did we introduce a conflict with Prototype?