I have an array with functions: var ranArray = [funct1(), funct2()] and the functions themselves:
function funct1() {
document.write("hello");
};
function funct2() {
document.write("hi");
};
I am trying to make it so that whenever a button is pressed, either funct1 or funct2 is executed.
However, without me even pressing the button, on the page I see my button and "hellohi". Here is the function for the randomization:
function getFunctions() {
return ranArray[Math.floor(Math.random * ranArray.length)];
};
and here is the HTML:
<button type="button" name="ranButton" id="ranButton" onclick="getFunctions();">Random Button</button>
Firstly you need to store the function references ([funct1, funct2]), the () will immediately call the functions. Next you can use .call() to call the function, or more simply add () at the end of ranArray[Math.floor(Math.random() * ranArray.length)] as #jfriend00 mentioned. Also note that Math.random needs to be Math.random().
var ranArray = [funct1, funct2];
function funct1() {
document.write("hello");
};
function funct2() {
document.write("hi");
};
function getFunctions() { // Note you don't really need a 'return' here
return ranArray[Math.floor(Math.random() * ranArray.length)]();
};
Demo
Also the use of document.write() here is overwriting the DOM. So I don't recommend it, rather you may want to place this content inside a element. If you have some element of the id #foo you could instead set the text of that DOM element:
document.getElementById("foo").textContent = "...";
Demo 2
Your array declaration is actually calling funct1 and funct2 and trying to store the return values in the array. What you want is an array of functions. Remove the parentheses so the functions themselves are stored in the array rather than the return values. It should look like this:
var ranArray = [funct1, funct2];
Related
I need to add parameter passing to this code but don't know how, i tried a few different things but it just broke the code everytime
If you need to pass parameters to your calc function, you can just create an anonymous function from the click event, add some code to gather your parameters to pass in and then call the calc function like so:
document.getElementById("currencybtn").addEventListener('click', function () {
let myParameter = 10;
calc(myParameter);
});
And then in your calc function, you can name that parameter anything you'd like. It doesn't have to be named myParameter because your calc function will use the first variable you pass to it with the first variable you put inside of the parenthesis when you call your calc function:
function calc(param1) {
//param1 is myParameter from above
//JavaScript pulls in variables based on the order they are received
return param1 + 3;
}
You can fetch the arguments from the target attribute of the event, somehing like this:
const button = document.querySelector('button');
button.addEventListener('click', calc, false);
button.randomParam = 'just a random parameter';
function calc(e)
{
window.alert(e.currentTarget.randomParam);
}
<button class="input">click me</button>
I want to use 2 helper functions for a function. Output is not showing any error but the output is showing the function syntax instead of return value
function cuboidlwsidesSurfaceArea(length,width,height) {
return 2*length*width
}
function cuboidwhsidesSurfaceArea(length,width,height) {
return cuboidlwsidesSurfaceArea(length,width,height) + 2*width*height
}
function cuboidsurfaceArea(length,width,height) {
return cuboidwhsidesSurfaceArea(length,width,height) +2*length*height
}
document.write = cuboidsurfaceArea(10,5,20)
</script>
document.write = cuboidsurfaceArea(10,5,20)
document.write is a function. Call it as such.
document.write(cuboidsurfaceArea(10,5,20));
If you want the value returned somewhere, assign it to a variable or return it from a function. Append it to a DOM element. You need to be specific about the use case if you want additional help on what to do with it.
I have a problem where if i want to add a parameter to my click attribute then it calls the function as soon as it renders
here is my test html:
return html`
<button class="menu-btn" #click="${this._OpenSubMenu(1)}>test</button>"
`;
}
And the function:
_OpenSubMenu(test:number) {
console.log("Hello")
}
This output Hello as soon as the page is rendered.
So how can i avoid this while still adding a parameter to my function?
You need to make your function return a function. Your click function will then execute the returned function, and due to closure's will still have access to the params.
eg..
_OpenSubMenu(test:number) {
var that = this;
return function () {
console.log("Hello");
//test is also a closure so you can use here
//that will equal this
}
}
If you want access to this, you could also use an arrow function
_OpenSubMenu(test:number) {
return () => {
console.log("Hello");
//test is also a closure so you can use here
//this will also still be valid here
}
}
I have been using ReactJs for a couple of days now. And I find some syntax a bit curious.
For example, sometimes I have to call a function this way:
{this.functionName}
Without the parentheses at the end.
And sometimes I have to call it like this:
{this.functionName()}
Like in this example:
<button onClick={this.streamCamVideo}>Start streaming</button>
<h1>{this.logErrors()}</h1>
See the difference between calling this.streamCamVideo and this.logErrors().
Can someone please provide an explanation for this?
EDIT 1:
As requested, here are their definitions :
streamCamVideo() {
var constraints = { audio: true, video: { width: 1280, height: 720 } };
navigator.mediaDevices
.getUserMedia(constraints)
.then(function(mediaStream) {
var video = document.querySelector("video");
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
video.play();
};
})
.catch(function(err) {
console.log(err.name + ": " + err.message);
}); // always check for errors at the end.
}
logErrors(){
return(navigator.mediaDevices.toString())
}
{this.streamCamVideo} is a reference to the streamCamVideo function. You can think of this.streamCamVideo as a variable whose value is a function. Think about it like this:
const myVariable = 'some text'
const myOtherVariable = function() {
console.log("You are inside the myOtherVariable function");
}
Both myVariable and myOtherVariable are variables. One has the value of a string, the other has the value of a function. Let's say you want to pass both of these variables to another function:
const anotherVariable = function(aStringVariable, aFunctionVariable) {
console.log(aStringVariable, aFunctionVariable)
}
anotherVariable(myVariable, myOtherVariable)
You might see something like this logged to the console:
some text
[Function]
Notice that you don't ever see the text "You are inside the myOtherVariable function" logged to the console. That's because the myOtherVariable function is never called. It's just passed to the anotherVariable function. In order to call the function, you would need to do something like this:
const anotherVariable = function(aStringVariable, aFunctionVariable) {
aFunctionVariable()
console.log(aStringVariable, aFunctionVariable)
}
Notice the parentheses after aFunctionVariable()? That's what it looks like to actually call a function. So in this case, you'd see something like this logged to the console:
You are inside the myOtherVariable function
some text
[Function]
The function is actually being called.
So in your example:
<button onClick={this.streamCamVideo}>Start streaming</button>
<h1>{this.logErrors()}</h1>
this.streamCamVideo is just being passed as a variable to the <button> element. When the button is clicked, whatever has been assigned to onClick will be executed. That's when the function you passed as a variable will actually be called.
Also, notice the parentheses after this.logErrors()? The logErrors function is being executed. It is not being passed as a variable to anything.
{this.functionName} means referencing the function on a particular trigger. this way function will get called only when triggered.
{this.functionName()} is an actual function call, this method can be used to pass arguments. this function call will get called when page renders. This way function will get called repeatedly without any triggers. To stop that repeated function call we can use callback. like the following,
{() => this.functionName()}. this way the function will get executed only once.
{this.functionName} is used a reference type and it does not create instance on every render but {this.functionName()} is creates an instance of functionName on every render
<button onClick={this.streamCamVideo}>Start streaming</button>
Here if you use this.streamCamVideo Now it uses the reference type it does not create an instance of streamCamVideo but instead of if you use like this
<button onClick={()=>{this.streamCamVideo()}}>Start streaming</button>
Now it creates an instance of streamCamVideo instead of using the reference of streamCamVideo.
Creating an instance on every render it slows the performance of your application
Moreover, When evaluated, the first one is just a reference to the function, in the second case the function gets executed, and the expression will be evaluated to be the return value of the function.
We can use this.logErrors() when you want the function to be invoked and its result returned immediately.
In React, we typically follow this approach to split parts of your JSX code to a separate function for readability or reusability.
For Example:
render() {
someFunction() {
return <p>Hello World</p>;
}
return (
<div>
{this.logErrors()}
</div>
);
}
We can use this.streamCamVideo when you want only to pass the reference to that function to do something else.
In React, this is used while handling an event handler which can be passed down to another child-component via props, so that component can call the event handler when it needs to or when it gets triggered.
For Example:
class myExample extends React.Component {
streamCamVideo() {
console.log("button clicked!");
}
render() {
return (
<div>
<Button someCustomFunction={this.streamCamVideo} />
</div>
);
}
}
class Button extends React.Component {
render() {
return (
<button onClick={this.props.someCustomFunction}>Click me</button>
);
}
}
...
this.functionName(args) {
...
}
When its called like
... onClick={this.functionName}
The react component accepts like
function SomeReactComponent({ onClick }) {
...
so that onClick function can be called like
...
onClick(someEvent);
...
so that your function can use those args
...
this.functionName(someEvent) {
...
}
When it calls like this
... onClick={this.functionName()}
onClick accepts the result of functionName, which should also be a function in this case.
One is attribute, another with "()" is function.
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!'))