Reputation: 37
I have some code in the - $(document).ready(function()
{ - that shuffles stuff around, the code is fired when the page is loaded but what I want to do is add a button so this function runs every time I press the button, how could I achieve this, thanks??
Upvotes: 0
Views: 6284
Reputation: 164740
function shuffleStuffAround() {
// truffle shuffle
}
$(function($) { // DOM ready
shuffleStuffAround();
$("#some-button").click(function() {
shuffleStuffAround();
return false; // you probably want this
});
});
Upvotes: 3
Reputation: 8882
You could simple refactor the code that you run on the ready function into its own function and call that in your button's click event:
$(document).ready(function(){
codeToRun();
$('.button').click(function(){codeToRun()});
});
function codeToRun(){
// do work
}
Upvotes: 0
Reputation: 187004
You can save you "shuffle stuff around" code as a function and call it from other parts of your codebase.
var foo = function() {
// code that shuffles stuff around
};
$(document).ready(function() {
foo();
// other stuff
});
$('#mybutton').click(foo);
//or
$('#mybutton').click(function() {
foo();
// other stuff.
});
Upvotes: 2