Andyjm
Andyjm

Reputation: 335

jQuery - re-execute a function on button click

I have a pretty unique situation where I need a bunch of jQuery code to re-execute on a button click. The added complications are:

I can't wrap the code inside a click event as it needs to run automatically on first opening or refresh of the page. To add a bit of context I've mocked up the following:

 setTimeout(function() {
     // all the scripts that need to run
 }, 2500);

 $('.btn').click(function() {
     // re-run the above code without refreshing window or browser
 });

Is there a way to re-run the code on a button click in this context?

Upvotes: 1

Views: 2520

Answers (4)

Carcigenicate
Carcigenicate

Reputation: 45750

This is actually a fairly common issue.

Make a function that contains the code you need to run in both places, and call the function from the setTimeout and onclick handler:

function someCode () {
    // Your code here
} 

setTimeout (someCode, 2500);

$('.btn').click(someCode);

When in doubt, make a function.

Upvotes: 2

synthet1c
synthet1c

Reputation: 6282

Javascript objects are passed by reference so you can just reference the function by name in each of the callacks.

function myFunc(){
  // all the scripts that need to run
}

setTimeout(myFunc, 2500)

$('.btn').click(myFunc)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Stewartside
Stewartside

Reputation: 20905

What you can do is set the functions within a variable which can be called in both the setTimeout() and also on a click() event

var nameOfFunction = function() {
  console.log('Hello World!');
}
setTimeout(nameOfFunction, 2500);

 $('.btn').on('click', function(e) {
     e.preventDefault();
     nameOfFunction();
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="btn">Click Me</button>

Upvotes: 1

hairmot
hairmot

Reputation: 2975

put all your code that needs running in a function of its own and call the function in both places

function myFunc()
{
    // all the scripts that need to run
}

setTimeout(function() {
     myFunc();
 }, 2500);

 $('.btn').click(function() {
     myFunc();
 });

Upvotes: 2

Related Questions