I have tried using a function to execute two functions when the page loads using window.onload, the issue I am having is that the function (myFunc) only executes the first function from the top (Func1) but not (Func2), the function looks like this
window.onload = function myFunc(){
return Func1();
return Func2();
}
So how can I execute both of them?
Try this :)
make sure you define Functions before calling them, this is good practice
//Arrow function and remove the return
const Func1 = () => {
console.log('This is Func1');
}
const Func2 = () => {
console.log('This is Func2');
}
window.onload = myFunc = () => {
Func1();
Func2();
}
do not return because after return goes out of function
window.onload = function myFunc(){
Func1();
Func2();
}
Remove the return keywords, and just run the function as is.
Ref: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
window.onload = function() {
Func1();
Func2();
};
No need for return statements and naming the function. It should trigger both functions, if not please make sure the code change is reflected in the source by putting a breakpoint or adding a debugger; inside the function. Also check if both the function body are doing the same action so that you are concluding as second one not executing.
js engine finishes the execution of function on return keyword.
so dont use return keyword to execute both functions
Related
Been googling and looking for an answer to this / best practice.
Let's say you have most of your javascript inside $(document).ready() for whatever reason, and inside there you have a function that you want to "fire" based on some external javascript function..
What would be the best way to do that? Simply moving the function to the global space isn't entirely a feasible option due to all the variables and stuff inside $(document).ready()
So in this example, there's external javascript that does an ajax request, so when the request is completed, data get's loaded on the page, and then I want to somehow be able to fire that function inside $(document).ready() when that external javascript ajax completes, but I can't simply call that function due to it not being in the global space.
you can use a setter to cast there:
let ready = false
const observe = {}
function run(name, ...args) {
if (observe[name]) observe[name](...args)
else {
let fn
Object.defineProperty(observe, name, {
get() {
return fn
},
set(fnL) {
fn = fnL
fnL(...args)
}
})
}
}
function set(name, fn) {
observe[name] = fn
}
$(document).ready(() => {
ready = true
const textEl = $("#text")
function setText(text) {
textEl.text(text)
}
set('setText', setText)
})
run('setText', 'first run')
setTimeout(() => run('setText', 'delayed 2s'), 2000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text">no thing</div>
this is quite powerful if you call the function before $().ready has completed it will wait until $().ready runs. and if $().ready is already running it will call the function too
Usage
in $().ready you have to call set('<function name>', <function>) and when you want to call the function run run('<function name>', ...<argumentts> )
or simpler way you remove $().ready and type <script> at the end of <body> it will work
If you do not want to expose a global then you can make an event that the code has to trigger which will inform when it is done.
$(function () {
function myLocalFunction (e, data) {
console.log('called', data);
}
$(document).on("loadedTheStuff", myLocalFunction);
});
window.setTimeout(function () {
$(document).trigger("loadedTheStuff", "Hello!");
}, 300);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I want to call a function that is in another function.
example for the functions:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
}
I need to call to funcTwo function, when I click on a button which is outside of these two functions
how can i do it?
No, You can't call unless you return that function.
Function2 is private to function1.
you use
function funcOne() {
return {
funcTwo :function() { // i want to call to this function
//do something
}
}
}
EDIT: Structuring code
function funcOne() {
var funcTwo = function() { // private function
//do something
}
return {
funcTwo : funcTwo
}
}
Now you can call it as:
funcOne().funcTwo()
As you have it defined in your example, you can't. funcTwo is scoped inside of funcOne, so it can only be called from inside funcOne. You can assign funcTwo to a variable that is scoped outside of funcOne and that would work:
var funcRef;
function funcOne() {
funcRef = function funcTwo() {
}
}
In this case, funcRef would hold a reference and could be used, but that reference is only set once funcOne has been executed.
Reading some Douglas Crockford may help you understand...
Try recoding as:
function funcOne() {
this.funcTwo = function() {
}
}
I think you'd have to declare an instance of a funcOne object and then call the funcTwo method of that object. I'm a bit busy at the moment so I can't refine this answer at the moment.
It is not possible as the second function will be created just when the first function is called. it is not existent prior to that.
You would have to define it outside the first function like so:
function funcOne() {
}
function funcTwo() { // i want to call to this function
//do something
}
Or you could also call the first function and return the second function like this:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
return functTwo;
}
And then call it like this:
var f = funcOne();
f();
I'm using in a project the following code which is not working:
window.onload=function(){
//code here
};
but if I add at the end () it works:
window.onload=function(){
//code here
}();
My question is, what's the difference? What does the () at the end?
I presume that the first one doesn't work because somewhere else the "onload" has been already called killing this one.
Would it have the same behaviour if I always use the second option ?
() at the end of function, calls this function immediately after declaration
window.onload=function(){
//code ehere
}() // function is called
And in this case
window.onload=function(){
//code here
};
function will be called after
window.onload()
When you have () after a lambda function such as that, it means you're calling the function immediately on that line.
So, for example,
var x=function() {
return 5;
}();
console.log(x);
would log 5 in the console. In the case of
window.onload=function() {
//code here
}();
that function most likely returns another function that gets called when the page loads.
For example,
window.onload=function() {
return function() {
console.log("Hello!");
};
}();
will log "Hello!" in the console when the page loads.
function is assigned to onload
window.onload=function(){
//code ehere
};
result of function is assigned to onload
window.onload=function(){
//code ehere
}();
With the () the function you define is called immediately. In that case, it better return a function to assign to window.onload.
So I dont understand why the console logs 1 right away onload or something when i have one.onclick = alterIt(1) shouldn't it wait till i click one. Anyway, obviously I am not ver good at javascript, thanks for your help.
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = alterIt(1);
}
function alterIt(x) {
console.log(x);
}
When you wrote:
one.onclick = alterIt(1);
...then you invoked the alterIt function and set the return value as the onclick handler. Instead, you wanted:
one.onclick = function(){ alterIt(1) };
// ...or better yet
one.addEventListener('click',function(){ alterIt(1) },false);
When the line one.onclick = alterIt(1); is executed, alterIt(1) is actually evaluated. What you want is to bind a function to one.onclick, which is only executed when the onclick event fires. You need something like
one.onclick = function() { alterIt(1) };
which doesn't bind the result of alterIt(1) to one.onclick, but rather the result of the function evaluation.
Wrap the function call like this so it doesn't fire until click:
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = function(){ alterIt(1);};
}
function alterIt(x) {
console.log(x);
}
Example fiddle: http://jsfiddle.net/RkH6Q/
There are two ways that you could code to work around this issue:
//Anonymous Closures
one.onclick = function(){ alterIt(1); };
//Bind Closures
one.onclick = alertIt.bind(window, 1);
Note: Function.bind() is supported by all the browsers for a year. If you care about old browsers, anonymous closures is the way to go.
What is happening is that you are calling the alterIt function when you should just be passing it in. So remove the parenthesis like so:
one.onclick = alterIt;
Why when i load page it runs function and alerts me "function run" i did not call it nowhere i need function to only trigger on element click.
<script type="text/javascript">
open_close = function() {
alert("function run");
//some code ...
}
window.onload = function() {
//some code ...
var myButton = document.getElementById('button');
myButton.onclick = open_close();
//some code ...
}
</script>
Here's jfiddle demo http://jsfiddle.net/ayeBP/
Ah, but you did run it:
myButton.onclick = open_close();
Parentheses invoke a function. Use this instead:
myButton.onclick = open_close;
Better still (click through for legacy IE support):
myButton.addEventListener('click', open_close);
Okay this was simplidied function i need to actually pass 2 variables to it e.g. myButton.onclick = open_close(var1,var2);
You still cannot use parentheses as you keep trying to do, because parentheses invoke the function. Use an anonymous function:
myButton.onclick = function () {
open_close(var1, var2);
};
// or, even better,
myButton.addEventListener('click', function () {
open_close(var1, var2);
});
Replace open_close() with open_close
Using parentheses here will invoke the function immediately and assign the return value of it to myButton.onclick