Why is my JS function executed onload instead of onchange? - javascript

Here's the code:
window.onload = function() {
oldonload && oldonload();
function test() {
alert("meh");
}
$('input[type=file]').change(test());
}
The code is fairly straight forward, test() is called only when input[type=file] is changed. However test() is being called whenever my page is loaded.
What is going on here? How would I execute the function only when user interacts with the input element?

You are calling the method on this line:
$('input[type=file]').change(test());
Change it to:
$('input[type=file]').change(test);
If you want to pass a parameter to test:
var myVar = 5;
$('input[type=file]').change(function () {
test(myVar);
});

Just change the file change event like this :
$('input[type=file]').change(function() { test() });

You're executing the function immedietaly instead of assigning a handler. You should instead do:
$('input[type=file]').change(test);

change takes function as argument, so you just need to provide function name to be called.
$('input[type=file]').change(test);

Related

Javascript function execution order

I am new to javascript and have a quick question. Say i have the following code:
function entryPoint()
{
callFunction(parameter);
}
function callFunction(parameter)
{
... //do something here
var anotherFunction = function () { isRun(true); };
}
My question is that when callFunction(parameter) is called, and the variable anotherFunction is declared, does isRun(true) actually execute during this instantiation? I am thinking it doesnt and the contents of the anotherFunction are only "stored" in the variable to be actually executed line by line when, somewhere down the line, the call anotherFunction() is made. Can anyone please clarify the function confusion?
It seems the confusion is this line of code
var anotherFunction = function () { isRun(true); };
This declares a variable of a function / lambda type. The lambda is declared it is not run. The code inside of it will not execute until you invoke it via the variable
anotherFunction(); // Now it runs
You almost described it perfectly.
anotherFunction just receives a reference to a newly created Function Object (yes, Functions are also Objects in this language) but it does not get executed.
You could execute it by calling
anotherFunction();
for instance.
You can write a simple test like so:
entryPoint();
function entryPoint()
{
alert("In entryPoint");
callFunction();
}
function callFunction()
{
alert("In callFunction");
var anotherFunction = function () { isRun(); };
}
function isRun()
{
alert("In isRun");
}
​
And, the answer is no, isRun() does not get called.

javascript from onclick into a function

I have the javascript code for a link click:
document.getElementById('giddy').onclick = function {
alert(this.href);
};
and I want to separate the function part of it...I have
document.getElementById('giddy').onclick = poro(this);
function poro(yyyy) {
alert(yyyy.href);
};
But it is not working (says undefined in the alert)...what am I doing wrong?
You don't need to pass this as a parameter. this will be the context for the function when it is called. You should just have:
document.getElementById('giddy').onclick = poro;
function poro() {
alert(this.href);
};
Get rid of (this) and use this in the function instead of yyyy.
document.getElementById('giddy').onclick = poro;
function poro() {
alert(this.href);
};
You're immediately calling the poro function.
Essentially, you're telling Javascript that the element's onclick value will equal the result of calling the poro(this [window] ) function.
To get around this, you can wrap the poro(this) function inside an empty function, like so:
document.getElementById('giddy').onclick = function(){poro(this)} function poro(yyyy) { alert(yyyy.href); };
You may also want to consider using an eventListener, as it allows room for expansion.
Almost there! You should do:
document.getElementById('giddy').onclick = function(){ poro(this); }
function poro(yyyy) {
alert(yyyy.href);
};
Note poro(this); wrapped in an anonymous function.
I'd recommend using addEventListener instead of the onclick method.
Try this:
var giddy = document.getElementById('giddy');
giddy.addEventListener('click', function(e) { poro(this); }, false);
function poro(yyyy) {
alert(yyyy.href);
}
since you are using jquery use :
$('#giddy').click(function(){ poro($(this));});
or you can use the bind() function
$("#giddy").bind("click", $(this), poro);

Passing Parameters into a Callback Function

I have a function that listens for a click on the screen and fires a callback. It is part of a Helper object (which is why is preceded by the term Helper in my sample code. That is irrelevant however.
var Helper = {
bodyClickListener: function(fn) {
var window = document.getElementsByTagName('body')[0];
window.click();
CORE.dom.on(window, 'click', function(event) {
CORE.dom.off(window, 'click');
fn(event);
});
}
}
I need to be able to pass a function into this function with a parameter that has been previously set.
function someFunction() {
var popup = document.getElementById('tagResultsPopup');
Helper.bodyClickListener(function(popup) {
return function(event) {
event.stopPropagation();
removePopup(popup);
};
}(document.getElementById('tagResultsPopup')));
function removePopup(element) {
if(element) {
element.parentNode.removeChild(element);
}
};
}
The code above works, but you'll notice that I have to set the popup variable inside of the callback function. It has already been set above. How do I pass a reference to the earlier variable into the callback function.
If I understand your question correctly, you don't need to do much. You can just use the popup variable defined outside.
var popup = document.getElementById('tagResultsPopup');
Helper.bodyClickListener(function(event) {
event.stopPropagation();
//Don't set it
//var popup = document.getElementById('tagResultsPopup');
removePopup(popup);//popup will refer to the correct variable
});
The function that you are passing to bodyClickListener is a closure. You can simply reference 'popup' inside that function without any problem. You don't have to create a new variable.
The answer was to use closure in this way:
Helper.bodyClickListener(function(popup) {
return function(event) {
event.stopPropagation();
removePopup(popup);
};
}(document.getElementById('tagResultsPopup')));
That way the callback function has access to the variable I pass into the parameter function. So here, the return is actually the function I am passing as the callback.

Possible to stop a Javascript function with another Javascript call?

I am having a problem where I want to stop a particular function from executing. This function is located on another plugin which I can't change the core files so I am wondering if I can stop a specific function from that file from executing?
So for example that function is testFunction(); and I want to stop that later in the code maybe in on document ready...etc.
Thanks!
Is the function public (as opposed to private via a closure)? And, does it need to be operational at all for things to work, or can you chop it out in total and be fine? If the latter, you can replace the function with a new one:
otherLibrary.testFunction = function(){};
If you want to disable it for a temporary amount of time, you can store the function in a temporary variable, and restore it later:
var removedFunc = otherLibrary.testFunction;
otherLibrary.testFunction = function(){};
// do something, time passes, whatever...
otherLibrary.testFunction = removedFunc;
Or, if you want to be able to toggle it, a slight variation:
var removedFunc = otherLibrary.testFunction;
var testFunctionEnabled = true;
otherLibrary.textFunction = function(){
if(testFunctionEnabled){
removedFunc.call(this, arguments);
}
};
And then just set testFunctionEnabled as you need to.
you should try to extend the function before you call it e.g.
$.extend(plugin.function, myNewFunction);
also, check the plugin API to see if you can pass a paramter to override the function or actually access the api of the plugin e.g.
$('#mytip').api('hover', myHoverFunction);
If you have access to the object which refers to the "testFunction" function then you could replace it with an empty function, e.g.:
SomePlugin.testFunction = function() { };
Ultimately, if you don't have a way to overwrite that symbol then there's not much you can do to stop the method from running (unless you can provide more details).
If that function schedules itself with setInterval, you can use clearInterval(thefunction) to prevent it from being called again. But if it's a loop, I don't know if that's possible.
Simply set the function to null.
JavaScript example:
function write() {
el.innerHTML += 'Lorem ipsum dolor sit amet.<br />';
if (execute != null) execute();
}
function execute() {
setTimeout(function() { write() }, 500);
}
function abort() {
execute = null;
}
window.onload = function() {
el = document.getElementById('blah');
execute();
}
HTML:
<button type="button" onclick="abort()">Abort</button>
<p id="blah"></p>
Also you can change the following to implement stop/start. For this, assign the execute function to a variable so that you can later assign that variable back to execute.
var oldfunc = execute;
function abort() {
if (execute == null) {
execute = oldfunc;
execute();
} else {
execute = null;
}
alert(execute);//shows the function code
}
You can overwite any method you have access to- but if the code in your module calls it internally you better give it an appropriate return.
document.write=function(){return true};
alert(document.write('tell me more!'))

Is this how you define a function in jQuery?

Is this how you define a function in jQuery?
$(document).ready( function () {
var MyBlah = function($blah) { alert($blah); };
});
Now to call the function I do:
MyBlah('hello');
First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.
Here's an example:
$(document).ready( function () {
var MyBlah = function($blah) { alert($blah); };
MyBlah("Hello this works") // Inside the anonymous function we are cool.
});
MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function)
This is (sometimes) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.
Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.
Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).
Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:
$('div#message').myBlah("hello")
See also: http://www.re-cycledair.com/creating-jquery-plugins
No, you can just write the function as:
$(document).ready(function() {
MyBlah("hello");
});
function MyBlah(blah) {
alert(blah);
}
This calls the function MyBlah on content ready.
No.
You define the functions exactly the same way you would in regular javascript.
//document ready
$(function(){
myBlah();
})
var myBlah = function(blah){
alert(blah);
}
Also: There is no need for the $
You can extend jQuery prototype and use your function as a jQuery method.
(function($)
{
$.fn.MyBlah = function(blah)
{
$(this).addClass(blah);
console.log('blah class added');
};
})(jQuery);
jQuery(document).ready(function($)
{
$('#blahElementId').MyBlah('newClass');
});
More info on extending jQuery prototype here: http://api.jquery.com/jquery.fn.extend/
jQuery.fn.extend({
zigzag: function () {
var text = $(this).text();
var zigzagText = '';
var toggle = true; //lower/uppper toggle
$.each(text, function(i, nome) {
zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
toggle = (toggle) ? false : true;
});
return zigzagText;
}
});
The following example show you how to define a function in jQuery. You will see a button “Click here”, when you click on it, we call our function “myFunction()”.
$(document).ready(function(){
$.myFunction = function(){
alert('You have successfully defined the function!');
}
$(".btn").click(function(){
$.myFunction();
});
});
You can see an example here: How to define a function in jQuery?
That is how you define an anonymous function that gets called when the document is ready.

Categories