I'm trying to auto click a button after 5 seconds, it does nothing.
Manually clicking works
<button id="test1" onclick="tFunction()">Button</button>
<script>
function tFunction(){
alert("Hello!");
}
setTimeout(document.getElementByID('test1').click(),5000);
</script>
setTimeout accepts a function. What you're doing is you're immediately calling .click(), then passing its return value to setTimeout.
Wrap the .click() inside a function instead:
function tFunction() {
console.log("Hello!");
}
setTimeout(() => document.getElementById('test1').click(), 5000);
<button id="test1" onclick="tFunction()">Button</button>
Also note that getElementById is case-sensitive - the last d should not be capitalized.
Also, don't use inline handlers, they have too many problems and have no place in modern codebases. Use addEventListener instead:
const test1 = document.getElementById('test1');
function tFunction() {
console.log("Hello!");
}
test1.addEventListener('click', tFunction);
setTimeout(() => test1.click(), 5000);
<button id="test1">Button</button>
Related
Is there any way to use the onclick html attribute to call more than one JavaScript function?
onclick="doSomething();doSomethingElse();"
But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.
A link with 1 function defined
Click me To fire some functions
Firing multiple functions from someFunc()
function someFunc() {
showAlert();
validate();
anotherFunction();
YetAnotherFunction();
}
This is the code required if you're using only JavaScript and not jQuery
var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);
I would use the element.addEventListener method to link it to a function. From that function you can call multiple functions.
The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria are met.
Sure, simply bind multiple listeners to it.
Short cutting with jQuery
$("#id").bind("click", function() {
alert("Event 1");
});
$(".foo").bind("click", function() {
alert("Foo class");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo" id="id">Click</div>
ES6 React
<MenuItem
onClick={() => {
this.props.toggleTheme();
this.handleMenuClose();
}}
>
var btn = document.querySelector('#twofuns');
btn.addEventListener('click',method1);
btn.addEventListener('click',method2);
function method2(){
console.log("Method 2");
}
function method1(){
console.log("Method 1");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pramod Kharade-Javascript</title>
</head>
<body>
<button id="twofuns">Click Me!</button>
</body>
</html>
You can achieve/call one event with one or more methods.
You can add multiple only by code even if you have the second onclick atribute in the html it gets ignored, and click2 triggered never gets printed, you could add one on action the mousedown but that is just an workaround.
So the best to do is add them by code as in:
var element = document.getElementById("multiple_onclicks");
element.addEventListener("click", function(){console.log("click3 triggered")}, false);
element.addEventListener("click", function(){console.log("click4 triggered")}, false);
<button id="multiple_onclicks" onclick='console.log("click1 triggered");' onclick='console.log("click2 triggered");' onmousedown='console.log("click mousedown triggered");' > Click me</button>
You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.
One addition, for maintainable JavaScript is using a named function.
This is the example of the anonymous function:
var el = document.getElementById('id');
// example using an anonymous function (not recommended):
el.addEventListener('click', function() { alert('hello world'); });
el.addEventListener('click', function() { alert('another event') });
But imagine you have a couple of them attached to that same element and want to remove one of them. It is not possible to remove a single anonymous function from that event listener.
Instead, you can use named functions:
var el = document.getElementById('id');
// create named functions:
function alertFirst() { alert('hello world'); };
function alertSecond() { alert('hello world'); };
// assign functions to the event listeners (recommended):
el.addEventListener('click', alertFirst);
el.addEventListener('click', alertSecond);
// then you could remove either one of the functions using:
el.removeEventListener('click', alertFirst);
This also keeps your code a lot easier to read and maintain. Especially if your function is larger.
React Functional components
<Button
onClick={() => {
cancelAppointment();
handlerModal();
}}
>
Cancel
</Button>
const callDouble = () =>{
increaseHandler();
addToBasket();
}
<button onClick={callDouble} > Click </button>
It's worked for me, you can call multiple functions in a single function. then call that single function.
Here is another answer that attaches the click event to the DOM node in a .js file. It has a function, callAll, that is used to call each function:
const btn = document.querySelector('.btn');
const callAll =
(...fns) =>
(...args) =>
fns.forEach(fn => fn?.(...args));
function logHello() {
console.log('hello');
}
function logBye() {
console.log('bye');
}
btn.addEventListener('click',
callAll(logHello, logBye)
);
<button type="button" class="btn">
Click me
</button>
You can compose all the functions into one and call them.Libraries like Ramdajs has a function to compose multiple functions into one.
Click me To fire some functions
or you can put the composition as a seperate function in js file and call it
const newFunction = R.compose(fn1,fn2,fn3);
Click me To fire some functions
This is alternative of brad anser - you can use comma as follows
onclick="funA(), funB(), ..."
however is better to NOT use this approach - for small projects you can use onclick only in case of one function calling (more: updated unobtrusive javascript).
function funA() {
console.log('A');
}
function funB(clickedElement) {
console.log('B: ' + clickedElement.innerText);
}
function funC(cilckEvent) {
console.log('C: ' + cilckEvent.timeStamp);
}
div {cursor:pointer}
<div onclick="funA(), funB(this), funC(event)">Click me</div>
I have written a small and simple slider with Javascript. Because I want to be sure that the slider works when I load the javascript in the footer of the page. I added an onload event and copied the whole slider application inside the event. In the HTML I unfortunately have an inline onclick element in a tag. But since I have the code inside the onload scope the onclick doesn't work anymore. My idea is not to bind the event inline in the html but directly in the javascript. That should work. But I am also interested if it is possible to do it with the inline onclick.
Question What do I have to do so that the onclick element addresses the corresponding function within the onclick function?
document.querySelector('body').onload = function() {
function init() {
// ...
}
const f2 = function() {
// ...
}
init();
/* that will work */
const anchorPrev = document.querySelector('.prev');
anchorPrev.addEventListener('click', () => {
console.log('prev');
});
/* My question */
function next() {
console.log('next')
}
};
a {
cursor: pointer;
}
<body>
<a class="next" onclick="next()">next (I'm curious to know if it works!?)</a><br/>
<a class="prev">prev (Will work)</a>
</body>
Two issues:
It's better to wait for the DOMContentLoaded event on the window object.
You're defining the function within the scope of the function, so it's not globally accessible. This means that the onclick can't see the function. Use a let variable, then set the function inside the listener callback like this:
<button onclick="log()">click me</button>
<script>
let log;
window.addEventListener('DOMContentLoaded', () => {
console.log('loaded');
log = () => console.log('clicked');
});
</script>
You can add that the onload event = function next()
JavaSript code:
document.querySelector('body').onload = function() {
const a = document.querySelector('a')
a.onclick = function next() {
event.preventDefault()
console.log('next')
}
};
I am using the ButtonGroup and Button from ReactStrap. I have set an onClick function when you click one of the buttons:
< ButtonGroup >
<Button>Edit</Button>
<Button onClick={console.log("Print some text")}>Print text</Button>
<Button>Set as default</Button>
</ButtonGroup >
But when I load the page this is what I get:
Before I have even clicked the button. And if I do click it, nothing comes out in the console. Any ideas?
Onclick must be function. You just set onlick as result of console.log("Print some text")
Try this
<Button onClick={() => {console.log("Print some text")}}>Print text</Button>
onClick parameter is evaluated as a callback, so if you pass something that is not a function, is evaluated and executed in the runtime.
Instead, you should pass a function to the onClick parameter:
<Button onClick={() => { console.log("Print some text"); }}>Print text</Button>
Be careful with the inline functions because they are evaluated each time that render is executed, that can be multiple times, each functions is more memory used by the browser.
If you has a class, you can use a arrow fat method:
/* ... */
handleOnClick = () => {
console.log("Print some text");
}
render() {
return (
<ButtonGroup>
<Button>Edit</Button>
<Button onClick={this.handleOnClick}>Print text</Button>
<Button>Set as default</Button>
</ButtonGroup >
);
}
/* ... */
To make it clearer
On any event trigger (onClick, onChange , etc) you must specified a function to call when the event occur
not calling the function right away
Consider this function
ES5:
function callMe() {
console.log("Some text");
}
ES6:
const callMe = () => {
console.log("Some text");
}
if you want to call this function when clicking the button you can't do this
<Button onClick={callMe()}>Print text</Button>
This will call the fuction callMe when the button is loaded once.
What you need to do to make it works is
<Button onClick={callMe}>Print text</Button>
Notice that there is no parenthesis after the function name which indicate that the function is not yet called.
I am using the ButtonGroup and Button from ReactStrap. I have set an onClick function when you click one of the buttons:
< ButtonGroup >
<Button>Edit</Button>
<Button onClick={console.log("Print some text")}>Print text</Button>
<Button>Set as default</Button>
</ButtonGroup >
But when I load the page this is what I get:
Before I have even clicked the button. And if I do click it, nothing comes out in the console. Any ideas?
Onclick must be function. You just set onlick as result of console.log("Print some text")
Try this
<Button onClick={() => {console.log("Print some text")}}>Print text</Button>
onClick parameter is evaluated as a callback, so if you pass something that is not a function, is evaluated and executed in the runtime.
Instead, you should pass a function to the onClick parameter:
<Button onClick={() => { console.log("Print some text"); }}>Print text</Button>
Be careful with the inline functions because they are evaluated each time that render is executed, that can be multiple times, each functions is more memory used by the browser.
If you has a class, you can use a arrow fat method:
/* ... */
handleOnClick = () => {
console.log("Print some text");
}
render() {
return (
<ButtonGroup>
<Button>Edit</Button>
<Button onClick={this.handleOnClick}>Print text</Button>
<Button>Set as default</Button>
</ButtonGroup >
);
}
/* ... */
To make it clearer
On any event trigger (onClick, onChange , etc) you must specified a function to call when the event occur
not calling the function right away
Consider this function
ES5:
function callMe() {
console.log("Some text");
}
ES6:
const callMe = () => {
console.log("Some text");
}
if you want to call this function when clicking the button you can't do this
<Button onClick={callMe()}>Print text</Button>
This will call the fuction callMe when the button is loaded once.
What you need to do to make it works is
<Button onClick={callMe}>Print text</Button>
Notice that there is no parenthesis after the function name which indicate that the function is not yet called.
The setInterval function is not working in my jsp page, below is my code:-
<script>
$(document).ready(function(){
$('form[name="lgform"]').submit(function(evnt){
evnt.preventDefault();
try{
mapPlotVar.clearInterval();
}
catch(e)
{
}
mapPlotVar=setInterval($("#btn_login").click(function(){console.log("update");},20000));
});
$("#btn_login").click(function(){
alert("hi");
});
});
</script>
<body>
<form name="lgform">
<div>
<table id="table" >
<tr>
<td width="35px"><input id="mob" type="text" name="mob_nu" placeholder="1234567890" maxlength="10"></td>
<td width="100px"><input type="button" name="login_btn" id="btn_login" value="Login"></td>
<td width="100px"><label for="Login" style="color: red" id="login_val"></label></td>
</tr>
</table>
</div>
</form>
</body>
</html>
After clicking the "btn_login" once i want the function to be called after every 20 seconds so that i get the alert message "hi" after every 20 seconds, but "hi" is only showing once, setInterval function is not working. What is wrong with my code? Any piece of code is appreciated.
I tried to use the set Interval here in a different manner because, i want the function to be called just after my first click and continue after every 20s and it wont work if we put the set interval function inside the function we call on button click in usual way.
Thanks in advance
setInterval($("#btn_login").click(function(){console.log("update");},20000));
The above will call jQuery.click once and pass its return value (a jQuery object) to setInterval but setInterval expects a callable function as its first argument.
The correct way to do it by wrapping into an anonymous function:
setInterval(function() {
$("#btn_login").click(function(){console.log("update");})
}, 20000);
But this still makes not much sense, since this way a new click event handler will be added (but not executed) to element every twenty seconds.
Your code has a lot of problems. Ignoring the other issues, if you want to set a 20s interval for a function on button click, you need to kick off the interval inside of the click handler.
$("#btn_login").click(function(){
setInterval( function () {
alert('hi');
}, 20000);
});
Of course, this will then happen on every button click. One way to solve it would be to use .one('click', function() { setInterval...}) instead of .click() because it will then work on first click only. But since it looks like you also want to cancel the interval, you'll need to take care of that as well.
edit:
var interval;
$("#btn_login").one( 'click', function() {
function run () {alert('hi');}
run();
interval = setInterval( run, 20000 );
});
// you can now cancel this interval somewhere else
function someCallback () {
if ( interval )
clearInterval(interval);
}
There are four basic things wrong with your code:
You do everything when the form is submitted, but you have no mechanism to submit the form (and your description says you don't want it to trigger on submission anyway).
Your code to tell the browser do stuff when the button is clicked is being passed to setInterval instead of the other way around.
You aren't passing a function to setInterval.
The code you want to run every time period is nowhere near your interval code
You need to throw out most of the code and start again.
var interval;
function run_on_interval_when_button_is_clicked(){
alert("hi!");
}
function run_when_button_is_clicked(event) {
event.preventDefault();
interval = setInterval(
run_on_interval_when_button_is_clicked,
20000
);
}
$(document).ready(function(){
$("#btn_login").on('click', run_when_button_is_clicked);
});
None of this has anything to do with JSP. That's server side code.
var interval;
$('#btn').on('click',function(){
if(typeof (interval) === 'undefined') {
interval = setInterval(function(){
alert('hi');
},20000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click</button>
$('#btn_login').on('click', function(){
setInterval(function(){ console.log("update"); }, 20000);
});