I have a global function defined in one place:
function addToCart (){
var prodText = $(this).parent().siblings(".item1").text();
$("#"+prodId+"shopC").children(".item1").text(prodText);
alert(prodText);
}
Then, I want to call it inside a HTML element with an inline onClick event:
onClick='addToCart()'
It is not working, but it works if I put the function code directly inside the onClick event, so that must be a this scope issue.
There are many questions/explanations about this scope but I must confess I miss a simple straight answer for this specific case (I tried to use "use strict" with success either).
How to make this work?
As per current implementation this doesn't refers to the element which invoked the function. It refers to window object.
You need to pass the current element context i.e. this to the function as
onClick='addToCart(this)'
and modify the function to accept element as parameter.
function addToCart (elem){
var prodText = $(elem).parent().siblings(".item1").text();
$("#"+prodId+"shopC").children(".item1").text(prodText);
alert(prodText);
}
Basically this inside a plain function will point to window. you have to pass the this context to the inline handler onClick='addToCart(this)'. Receive it and use it inside of event handler like below.
function addToCart (_this){
var prodText = $(_this).parent().siblings(".item1").text();
you have to pass this keyword where you inline calling the addToCart function then you can capture that element
onClick='addToCart(this)'
this object in your function does not point to the object where you added the onClick function to. It rather points to the window object.
You need to pass this as a param to your function.
function addToCart (trigger) { // Code goes here }
and call addToCart(this) in your onClick.
Learn more about this in javascript here.
Related
I am trying to create a button listener function inside bindPop in leaflet. But it does not read parameter of onclick function. In the below code alertConfirmed()function works fine for me but filterEventsBasedOnCluster(feature) does not read the parameter 'feature'. It says feature is not defined. feature is an object.
here is the code:
layer.bindPopup('<div id="alert">Found...!<input type="button" value="Please confirm" onclick="alertConfirmed()"> <input type="button" id="create" value="see patients" onclick="filterEventsBasedOnCluster(feature)"><table id="table"></table></div>')
`
Any help is much appreciated.
If you attach event handlers via the onclick HTML attribute, you can not control the parameters received by that handler. Let me quote the docs:
The single argument passed to the specified event handler function is a MouseEvent object. Within the handler, this will be the element upon which the event was triggered.
The way to pass a custom argument is to define a closure, by having a function that returns a function that receives only the event reference.
This is exactly the same solution as described in «Leaflet.contextmenu callbacks» and «Leaflet marker event fires at wrong time».
Read that. I mean it.
So in the end it should look something like:
function getHandlerForFeature(feat) { // A function...
return function(ev) { // ...that returns a function...
console.log(feat); // ...that has a closure over the value.
}
}
layer.bindPopup("<button id='mybutton'>Foo!</button>")
// The button doesn't exist in the DOM until the popup has been opened, so
layer.on('popupopen', function(){
L.DomEvent.on(
document.getElementById('mybutton'),
'click',
getHandlerForFeature(layer) // The result of this call is the event handler func.
);
});
Note that you can not use the onclick="code" syntax, as you need to create a string of runnable code, and that code will only be able to access variables in the global scope. Sure, you can JSON.stringify() your data, but you won't be able to have references to variables outside.
try this:
I am just correcting the wrong part only:
onclick="filterEventsBasedOnCluster('+feature+')"
You are not passing the variable properly.
I have an event listener set up on a button using jQuery, and for some reason the function within the click listener is called without the button being clicked. I know that usually functions are anonymous in listeners, but it won't work as an anonymous function. The function I am calling also has to accept parameters, which is why I don't think I can just call a reference to the function. Any ideas on how I can fix the problem of the function getting called without a click even registered and still pass the necessary parameters to the function?
$('#keep-both').click(keepBothFiles(file, progress, audioSrc));
calls this function
function keepBothFiles(file, progress, audioSrc) {
...
...
}
You're referencing the function incorrectly. Try this instead:
$('#keep-both').click(function(){
keepBothFiles(file, progress, audioSrc);
});
Whenever you use the syntax funcName(), the () tell the interpreter to immediately invoke the function. The .click method requires that you pass it a reference to a function. Function references are passed by name only. You could also do:
$('#keep-both').click(keepBothFiles);
But you can't pass it your other arguments. It's given an event object by default
You must pass a function reference to the .click() function, not the result of calling a function. When you include the () like this keepBothFiles(...) at the end of the function name, you are telling javascript to execute the function now. When you just use the name of the function like keepBothFiles, you are getting a reference to the function (which can be called later).
You are currently calling your function immediately and then passing the return value of that function (which is not a function reference) to the .click() function, thus it does not do what you want.
The click handler callback function is passed exactly one parameter (the event) in jQuery so you cannot have it call your keepBothFiles(file, progress, audioSrc) function directly like you have it.
Instead, it could be done like this with a second wrapper function:
$('#keep-both').click(function(e) {
keepBothFiles(file, progress, audioSrc);
});
I created a custom variable/function that I am trying to execute when an element is clicked. For some reason, it decides to display onload and ignores the .click(). I've spent a while now trying to figure this out, but I'm not having much luck.
Here's my custom function:
var movebox = function (entry) {
$imagebox.css('left' , '0');
$('#wr').append(entry);
};
I'm attempting to call it like this, but it calls it when the page loads instead.
$l3.click(movebox('test'));
You're calling the movebox function immediately instead of passing the function as a reference to the click event handler. This is a common mistake in JavaScript. Instead, pass in your function inside of an anonymous function, like so:
$l3.click(function() {
movebox('test');
});
As an aside, the same mistake is oftentimes made with setTimeout, setInterval, addEventListener, and the infamous eval. Remember, when treating functions as arguments to another function, be sure to wrap them in anonymous functions.
You are calling the movebox then passing the returned value to click event handler, in this case you can use the .on() event registration helper to pass a data element to the event handler which can be accessed using the event object.
Try
var movebox = function (e) {
$imagebox.css('left' , '0');
$('#wr').append(e.data.entry);
};
$l3.on('click',{ entry: 'test'}, movebox);
window.onload = function() {
document.getElementById('clickMe').onclick = runTheExample;
}
function runTheExample() {
alert('running the example');
}
This is a simple event handler for the onclick event for an html input button with id = clickMe.
In line 2, why is the call to function runTheExample not immediately followed by ()? I thought that to call a function you must pass it any variables/objects it expects in an open/close parenthesis, and if the function isn't expecting anything, you must still include the open and close parenthesis like runTheExample().
document.getElementById('clickMe').onclick = runTheExample;
The intention here is not to call runTheExample() but to assign the reference to the function runTheExample to the onclick event.
Internally, when the onclick event is fired, Javascript is able to call the function runTheExample through the reference you provided on the code above.
Snippet
var myFunction = function() { return 42; };
// Assigning the reference
myObject.callback = myFunction;
myObject.callback(); // Has the same effect as calling myFunction();
// Assigning by calling the function
myObject.callback = myFunction();
myObject.callback; // Returns 42
myObject.callback(); // Exception! Cannot call "42();"
That's not Javascript-specific. Passing functions by reference is available in many languages.
You use the parenthesis only to invoke (call) a function. When you're assigning it to onclick, you're merely passing it by reference.
To better understand this, think about the other method of declaring a function:
var runTheExample = function () {
alert('running the example');
}
Regardless of what method you use, runTheExample will contain a reference to the function (there are some differences, like the function reference not being available before assignment, but that's a different story).
Functions are objects in javascript. That line sets the onclick property of the click me element to the runTheExample function, it doesn't call that function right then.
var a =runTheExample; //sets a to runTheExample
a(); //runs the runTheExample function
So when the function name is referenced without the () it is referring to the function object, when you add the () it is a call to the function, and the function executes.
It's not calling it, but rather setting the property onclick. When a call is made to onclick(), it will then run the function you've defined. Note however that the context of this will be the object that calls it (document.getElementById('clickMe')).
You're not calling the function here. You're setting the function as an event handler, and the function is not actually called called until the event is fired. What you've written references the function; that's a different notion than actually calling it.
In this case, the runTheExample function is being treated as a variable and being assigned to the onclick event handler. You use () after a function name to call a function. If you added them here, what would happen is that runTheExample() would be called once during load, showing an alert, and then a null value would be assigned to the onclick handler.
Because it binds runTheExample to onclick event.
When you add () it triggers the function.
I'm trying to register on +1 clicks from within my module, which is wrapped as an annonymous function.
For this end, I created a global object MyModule, and exported my click handler function through it. The problem is - my click handler doesn't get called.
Live demo. Code:
// Initialize +1 button
gapi.plusone.go();
(function(){
window.MyModule = {};
function plusOneClicked() {
alert("+1!");
}
window.MyModule.plusOneClicked = plusOneClicked;
})()
...
<g:plusone callback='window.MyModule.plusOneClicked'></g:plusone>
When I give as a callback an external function, whose only purpose is to forward the calls to window.MyModule.plusOneClicked, it works:
function foo() {
window.MyModule.plusOneClicked();
}
...
<g:plusone callback='foo'></g:plusone>
Why would the click handler miss window.MyModule.plusOneClicked(), but find foo()?
Google is probably writing
window[callback]();
in their code.
This requires that the callback string refer to a property of window, not a property of another object.
I believe because callback expects a direct handler method (as in foo()) rather than a reference (as in window.MyModule.plusOneClicked). So basically, you cannot simply assign such a reference to click handler, but write a (wrapper) method as the handler and have it perform the necessary invocation.