Why is window.onload function undefined? - javascript

I have made a simple function and it is supposed to run on window.onload. But instead, I get that it is undefined. Can anyone help me understand why I get this error?
The form id is kalkulator and the name of the inputs is liter and enheter
The function I have written is
window.onload = function () {
form.kalkulator.focus();
};
I have also written this
form.kalkulator = function () {
if (form.enheter.value == "") {
form.liter.value = "";
} else{
convertLiter();
};
}
function convertLiter() {
console.log(form.liter.value / person.volum() * person.sukker_g())
form.enheter.value = form.liter.value / person.volum();
}
function convertEnheter() {
console.log(form.enheter.value * person.sukker_g())
form.liter.value = form.enheter.value * person.volum();
}

This has nothing to do with window.onload.
You're invoking this...
form.kalkulator.focus();
but form.kalkulator is a function, it doesn't have a .focus() method. form.klalkulator.focus is undefined, and you're attempting to invoke it as a function, hence your error.

form.kalkulator doesn't have any return so you can't call
form.kalkulator.focus();
replace the function
form.kalkulator = function () {
if (form.enheter.value == "") {
form.liter.value = "";
} else{
convertLiter();
};
return form;
}
or split the instructions;
form.kalkulator();
form.focus();

Related

How do I call the function I pull out from an array in JavaScript?

I'm stuck with a problem, and I can't seem to figure out where to go. The code linked shows an array of 3 different functions. When the button is clicked it randomly splices one item out of the array after each click until the array is empty.
The cut out function shows fine in the console log, but I cannot figure out how to call the function and execute it. Anyone able to help me figuring out the correct way? I figured I'd use the new_numb like this (it does not work):
my_array[new_numb]();
Any help would be greatly appreciated!
Code for reference:
function first_function() {
console.log("test1");
}
function second_function() {
console.log("test2");
}
function third_function() {
console.log("test3");
}
Array.prototype.randsplice = function () {
var randomnr = Math.floor(Math.random() * this.length);
return this.splice(randomnr, 1);//removed extra variable
};
var my_array = [
first_function,
second_function,
third_function,
];
var button = document.getElementById("clicker");
button.onclick = function () {
if (my_array.length > 0) {
var new_numb = my_array.randsplice();
console.log(new_numb);
} else {
console.log('array is empty');
}
};
<button id="clicker">Click</button>
The array prototype function you're using returns an array with 1 index. So you need to access it with [0], then you can use apply() to call it.
new_numb[0].apply(null)
function first_function() {
console.log("test1");
}
function second_function() {
console.log("test2");
}
function third_function() {
console.log("test3");
}
Array.prototype.randsplice = function() {
var randomnr = Math.floor(Math.random() * this.length);
return this.splice(randomnr, 1); //removed extra variable
};
var my_array = [
first_function,
second_function,
third_function,
];
var button = document.getElementById("clicker");
button.onclick = function() {
if (my_array.length > 0) {
var new_numb = my_array.randsplice();
new_numb[0].apply(null)
} else {
console.log('array is empty');
}
};
<button id="clicker">Click</button>

Is it possible to call a function while not using all of its code in JavaScript?

Let's say I have a JS function that returns a value but has an alert command in it. I want to assign the returned value to a variable later on in the code. Is there a way to call the function but to ignore the alert command, in order to just assign the returned value to a variable later?
For example:
Let's say I havefunction f1(num) { alert ("hi); return num * 2; }
and thenfunction f2() { var x = f1(2); return x;}.
How can I ignore the alert and only save the returned
value in a variable on later functions?
Add an additional parameter to f1() to skip the alert:
function f1(num, skipAlert) {
if (skipAlert !== true) alert("hi");
return num * 2;
}
function f2() {
var x = f1(2);
return x;
}
function f2_skipAlert() {
var x = f1(2, true);
return x
}
document.querySelector('button#alert').addEventListener('click', function () {
console.log(f2());
});
document.querySelector('button#skip-alert').addEventListener('click', function () {
console.log(f2_skipAlert());
});
<button id="alert">Run with alert</button>
<button id="skip-alert">Run without alert</button>
Solution if you cannot change the f1 function
You can disable it with the following. Remember to define the disable function before the execution of the one that contains the alert function.
window.alert = function() {};
If you need to re-enable it, you can do temporarily associate it to another variable:
var oldalert = window.alert;
Then disable it as I did before and then re-enable later with window.alert = oldalert;
As esqew said, it's not a good practice to override it
Example of Use
function disableAlert(){
window.oldalert = window.alert;
window.alert = function() {};
}
function enableAlert(){
window.alert = window.oldalert;
}
And then, in your f2 function you can do like this:
function f2() {
disableAlert();
var x = f1(2);
enableAlert();
return x;
}
Solution if you can change the f1 function
Similar to esqew solution but using default parameters
function f1(num, skipAlert = false) {
if (skipAlert) alert("hi");
return num * 2;
}
function f2(skipAlert = false) {
var x = f1(2, skipAlert);
return x
}
If you want to call with alert you can use f2(true) otherwise just f2().

How to wrap Javascript function within function expression?

I would like to add a wrapper function to one of my functions to show extra information.
Below is my wrapper function:
var wrap = function(functionToWarp, before) {
var wrappedFunction = function() {
if (before) before.apply(this, arguments);
result = functionToWrap.apply(this, arguments);
return result;
}
return wrappedFunction;
}
var beforeFunc = function(){
// print extra infos before functionToWarp() triggers.
}
and my function _printSth to wrap:
var Printer = function () {
this._printSth = function (input) {
// print something from input...
}
}
Printer._printSth = wrap(Printer._printSth, beforeFunc);
I have tried to wrap Printer._printSth by calling
Printer._printSth = wrap(Printer._printSth, beforeFunc); or similar codes but failed.
How should I declare my _printSth() to be able to be wrapped?
You could write
function Printer() {
this._printSth = function (input) {
// print something from input...
};
this._printSth = wrap(this._printSth, beforeFunc);
}
or
function Printer() {
this._printSth = wrap(function (input) {
// print something from input...
}, beforeFunc);
}
but that's equivalent to simply writing
function Printer() {
this._printSth = function (input) {
beforeFunc(input);
// print something from input...
};
}
Assuming you rather might want to wrap the method on a specific instance, you'd do
const p = new Printer();
p._printSth = wrap(p._printSth, beforeFunc);
Altering a method is done like that:
Printer.prototype._printSth = wrap(Printer.prototype._printSth, beforeFunc);

Calling function inside function called by setTimeout

I am trying to call the function scroll_page inside a function call_scroll_page that is called by setTimeout. And I get error file.js:5 Uncaught TypeError: scroll_page is not a function.
function scroll_page() {
return false;
}
function call_scroll_page() {
var scroll_page = scroll_page();
if(!scroll_page) {
$test = true;
}
}
setTimeout(call_scroll_page, 1000);
var scroll_page
You defined a new variable called scroll_page inside the call_scroll_page function which has masked the global one.
Rename that variable.
It is because you are declaring a var with same name as your function. So inside your function call_scroll_page() scroll_page refers to the local variable. Change your variable name and it will work as intended.
function scroll_page() {
return false;
}
function call_scroll_page() {
var scroll_page_var = scroll_page();
if(!scroll_page_var) {
$test = true;
}
}
setTimeout(call_scroll_page, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
This line is causing the error: var scroll_page = scroll_page();
Do not redeclare something with name of the scroll_page function.
It removes the link to the function, replaced by a variable, calling a function that is no longer "callable by its name".
Try:
function scroll_page() {
return false;
}
function call_scroll_page() {
var fn = scroll_page();
if(!fn) {
$test = true;
}
}
setTimeout(call_scroll_page, 1000);

Call functions inside of another function

I am having a problem calling functions inside a function.
This is the sample code:
<script>
function saveInfo() {
function returnEmail() {
var _e = document.getElementById("email").value;
return _e;
}
function returnName() {
var _n = document.getElementById("name").value;
return _n;
}
}
</script>
The saveInfo() method is made in a button:
<input type="submit" value="Save" onclick="saveInfo()" style="color: black">
So there are 2 forms, where you fill up your email and name. By clicking "Save" -button, the DIV will disappear (this works) and another DIV will appear within text like this: Name = (name) | Email = (email).
I am having problems to call the saveInfo()'s returnEmail() for the corresponding line (where there is 'Name = ').
I try to write them like this:
<p>Email:
<script>
var pEmail = saveInfo().returnEmail();
document.write(pEmail);
</script> <br>
</p>
I know that the script above is incorrect, this is not the only way I have tried to return it.
It looks like you're trying to return those functions to use later. Try doing this instead. This function now returns an object with two functions.
function saveInfo() {
return {
returnEmail: function() {
var _e = document.getElementById("email").value;
return _e;
},
returnName: function() {
var _n = document.getElementById("name").value;
return _n;
}
}
}
Previously, your saveInfo function wasn't returning anything, so
saveInfo().returnEmail();
would evaluate to
undefined.returnEmail();
and you'd get an error
You need to return the exposed functions from the function saveInfo. At this time, your code only declares the function, but doesn't return anything. So, saveInfo returns undefined. Below approach is an implementation of the Revealing module pattern to reveal the public members outside your function.
function saveInfo() {
var returnEmail = function () {
var _e = document.getElementById("email").value;
return _e;
}
var returnName= function () {
var _n = document.getElementById("name").value;
return _n;
}
return {
returnEmail :returnEmail,
returnName :returnName
}
}
If your set on calling it like saveInfo().returnEmail(); then you can do the following. saveInfo returns an object containing the returnEmail method.
<script>
function saveInfo() {
// Do any desired logic
return {
returnEmail: function() {
var _e = document.getElementById("email").value;
return _e;
},
returnName: function() {
var _n = document.getElementById("name").value;
return _n;
}
}
}
</script>

Categories

Resources