Change button onclick after first click - javascript

I'm having some struggles getting this to work.
I have a button, and I want it to execute Javascript function A, and in that function A, i want to change the Onclick to function B. Thus getting as result when the user taps the button a SECOND time, it's executing B. With the
<Button onclick="A();">Click me</button>
<script>
Function A() {
document.getElementById("button").onclick=B();
}
Function B() {
Alert("hello world");
}
In function A(), it doesn't execute FIRST A and after that B, it instantly executes B. Could anyone help me? Thanks :)

When you write a function name with the parenthesis, like B(), that invokes the function immediately. Instead, you'll want to set onclick to be just the name of the function, A or B.
Your overall solution could look something like this:
function A(event) {
// Function logic...
event.target.onclick = B;
}
function B() {
// Function logic...
}
document.getElementById("button").onclick = A;

You're calling B with B().
Use document.getElementById("button").onclick=B;. Note that there's no parentheses after B.

You can use Jquery to change any attribute of a button onclick. Below, I update the onclick attribute to instead execute function B()
function A() {
$('#toggler').attr('onclick', 'B()');
}
function B() {
console.log('Updated to B()!');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggler" onclick="A()">Click me!</button>

Use an id instead of the onclick for the button then target it from javascript like this:
function b()
{
console.log('I am in B.')
}
function a()
{
console.log('I am inside A.');
button1.removeEventListener('click', a);
button1.addEventListener('click', b);
}
var button1 = document.getElementById('button1'); // get the button element
button1.addEventListener('click',a); // assigns a click listener to a() at the beginning
<Button id="button1">Click me</button>

Related

How to call a function 10 seconds after calling another function?

I have two functions, functionOne() and functionTwo().
How can I go about calling functionTwo() 10 seconds after functionOne() ends/is called?
I'd like functionOne to occur after a button is clicked, and then functionTwo 10 seconds after functionOne ends (without the need to click a button again/have the user do anything!)!
See below for my code!
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText" onClick="functionOne()">Click!</button>
<script>
functionOne() {
document.getElementById("paragraphChange").innerHTML = "Bye World";
}
functionTwo() {
document.getElementById("paragraphChange").innerHTML = "Jokes I'm still here";
}
</script>
I tried to use setTimeout, but the problem is that I don't think there is an 'onend' event I can use for the first function. Eg:
setTimeout(functionOne.onend, 10,000);
This code calls functionOne onClick and calls functionTwo 10 seconds later.
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText" onClick="functionOne()">Click!</button>
<script>
function functionOne() {
document.getElementById("paragraphChange").innerHTML = "Bye World";
setTimeout(() => functionTwo(), 10000);
}
function functionTwo() {
document.getElementById("paragraphChange").innerHTML = "Jokes I'm still here";
}
</script>
Most importantly you have to declare your functions properly using the function keyword: function functionOne, function functionTwo.
Here's the documentation for setTimeout: "The global setTimeout() method sets a timer which executes a function... once the timer expires." So you pass in the function that you want to execute once the timer has completed.
And here are some more methods of approaching the problem.
Cache your paragraph element along with the button up front so you're making the code as DRY as possible.
Move the inline JS to the script, and use addEventListner to the para element
Use textContent instead of innerHTML because you're not adding HTML
// Cache the elements
const para = document.querySelector('#paragraphChange');
const button = document.querySelector('#clickToChangeText');
// Add a listener to the button
button.addEventListener('click', functionOne, false);
// Set the text content of the para element
// and then call the second function with a time out
function functionOne() {
para.textContent = 'Bye World';
setTimeout(functionTwo, 5000);
}
// Update the para with new text
function functionTwo() {
para.textContent = 'Jokes I\'m still here';
}
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText">Click!</button>
Define functionTow() first.
function functionTwo() {
//code to be execute
}
The call functionTwo in functionOne's body using setTimeout.
function functionOne(){
//code to be execute
//End of function
setTimeout(functionTwo, 10000);
}
I don't think there anything called onend in JavaScript you have to use setTimeout(functionTwo, 10000) at the end of functionOne() like this:
function functionTwo() {
//code to be execute
}
function functionOne(){
//code to be execute
//End of function
setTimeout(functionTwo, 10000);
}

One button runs a function, a second button runs a different function but only if the 1st function gets run

I have 4 buttons assigned to run 4 different functions. Seen below
document.getElementById("buttonOne").addEventListener("click", functionOne);
document.getElementById("buttonTwo").addEventListener("click", functionTwo);
document.getElementById("buttonThree").addEventListener("click", functionThree);
document.getElementById("buttonFour").addEventListener("click", functionFour);
I have another function,functionFive, that is not controlled by any button.
All of these functions set parameters on a 3D object when the given button is clicked. Clicking button one runs functionOne, setting a specific set of parameters. If those parameters are set from functionOne and I click button four, I want functionFive to be run.
If those parameters from functionOne are not set when button four is clicked, I want functionFour to run.
To clarify, I only want this functionFive to run if functionOnehas already run and its parameters are set.
Can someone help me write this script?
I've rewritten my question to fit my exact need. My original description was condensed to try and simplify it so it wouldn't be this long.
Maybe make a new boolean variable that is false when it's defined, but set to true when functionOne is run and that determines which function buttonTwo runs.
<html>
<script>
var oneClicked = false;
function functionOne() {
oneClicked = true;
alert('functionOne');
}
function functionTwo() {
alert('functionTwo');
}
function functionThree() {
alert('functionThree');
}
</script>
<button onclick="functionOne()">button one</button>
<button onclick="if (oneClicked) {functionThree()} else {functionTwo()}">button two</button>
</html>
Found the working solution to be....
var clicked = false;
function functionOne() {
/functionOne parameters
clicked = true;
}
function functionTwo() {
clicked = false;
//functionTwo parameters
}
functionFour() {
if (clicked) {
cliked = false;
functionFive()
} else {
//functionFour parameters
}
}
}

dynamically change assigned click function

<div id='example' data-fn='functiona'>OK</div>
$('#button').click function(){
$('#example').attr('data-fn', functionb');
});
function functiona(){
console.log('functiona');
}
function functionb(){
console.log('functionb');
}
$('#example').click(function(){
// execute function currently stored inside data-fn attribute
});
Probably everything is clear.
I need dinamically change the function which will be executed by clicking on example.
The current function should be stored inside data-fn.
Any help?
What you want to do is described in Can you set a javascript function name as an html attribute?
But I suggest that you solve it that way:
$('#button').click(function() {
$('#example').off('click.myNamespace') // remove the previously assigned callback
.on('click.myNamespace', creatClickCallback(functionb)); // register the new callback
});
function functiona() {
console.log('functiona');
}
function functionb() {
console.log('functionb');
}
function creatClickCallback(functionToCall) {
return function(evt) {
functionToCall()
}
}
$('#example').on('click.myNamespace', creatClickCallback(functiona));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='example'>OK</div>
<div id='button'>button</div>
This way you ensure that you do not accitantily name a function the wrong way, because you pass it as an actual reference to that function instead of a string.
Couldn't you just store the function name, then when you click you check which function is then call it and update the function to which one you want?
Something like this:
function functiona(){
console.log('called functiona');
document.body.style.background = '#aaa';
}
function functionb(){
console.log('called functionb');
document.body.style.background = '#fff';
}
$('#example').on("click", function(ev){
var func = $(ev.target).attr('data-fn');
console.log(func);
window[func]();
});
$('#changer').on("click", function(ev){
//HERE you can change the function will be called based on what you want
//Here I just changed it with a simple if...
var fn = $("#example").attr("data-fn");
if (fn == 'functiona'){
$("#example").attr("data-fn", "functionb");
}else {
$("#example").attr("data-fn", "functiona");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='example' data-fn='functiona'>Click Me to call function</div>
<button id='changer'>Change Function</button>
Here, the global variable window have your functions stored, so going through it by it's name and calling it, should work, if this name exist as a function window[stringOfFuncionName]();
This is not the best way of doing what you need (actually you didn't let completely clear your final objective), but this maybe can help.

Get contents of a JavaScript function

I was trying to make a function in JavaScript that could set the onClick property of an HTML button.
So, say I have this as my function:
function myFunc(action){
document.getElementById('mybtn').setAttribute("onClick", action);
}
That would set mybtn's attribute onClick to the contents of the variable action (which should be a function).
So, if I ran the function like this:
myFunc(function(){
alert("Hello, World!");
});
Then the variable action would be set to
function (){
alert("Hello, World!");
}
If I ran myFunc as shown, it would successfully add the contents of action to the button's onClick attribute. The only problem is, if I click the button after myFunc has been run, I just get an error. It says:
Uncaught SyntaxError: Unexpected token (
I think that's because in the onClick attribute, you can't have a new function defined.
How can I get only what's inside the function in the variable action?
You can add an event listener instead of altering the attribute for onclick like this:
function myFunc(action) {
document.getElementById('mybtn').addEventListener('click', action);
}
myFunc(function() {
alert('foo');
});
<button id="mybtn">Foo</button>
Attribute values can only be strings. Your function is stringified to something like
'function(){ alert("Hello, World!"); }'
And then the event handler parses it as a function body. That means it will be treated as a function declaration, but function declarations require a name. Therefore, yes, there is an unexpected (: there should be a name before it. Firefox provides a more meaningful error
SyntaxError: function statement requires a name
function() {
alert("Hello, World!");
}
If you really want to use event handler content attributes, you should pass a string containing only the body of the function:
myFunc('alert("Hello, World!")');
function myFunc(action){
document.getElementById('mybtn').setAttribute("onclick", action);
}
myFunc('alert("Hello, World!")');
<button id="mybtn">Click me</button>
But I strongly discourage event handler content attributes. Instead, use event handler IDL attributes:
function myFunc(action) {
document.getElementById('mybtn').onclick = action;
}
function myFunc(action) {
document.getElementById('mybtn').onclick = action;
}
myFunc(function (){
alert("Hello, World!");
});
<button id="mybtn">Click me</button>
Or even better, event listeners
function myFunc(action) {
document.getElementById('mybtn').addEventListener('click', action);
}
function myFunc(action) {
document.getElementById('mybtn').addEventListener('click', action);
}
myFunc(function (){
alert("Hello, World!");
});
<button id="mybtn">Click me</button>
html onclick event attribute expects a string, not a function. You can defined function to be called then pass string referencing function to myFunc
<div id="mybtn">click</div>
<script>
function myFunc(action) {
document.getElementById("mybtn").setAttribute("onclick", action);
}
function clickHandler() {
alert("Hello, World!");
}
myFunc("clickHandler()");
</script>

javascript onclick function does not run all code in function

This onClick function does not run the console.log in the code snippet below, any ideas?
var clickFunction = function myfunc() {
return function (){
return console.log('here');
}
};
<button onClick="clickFunction()"> Click here</button>
Thanks for your time
Because you're calling a function that returns a function. If you want to run the function that is returned you would need to do: clickFunction()()

Categories

Resources