Document.ready function - javascript

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??

function shuffleStuffAround() {
// truffle shuffle
}
$(function($) { // DOM ready
shuffleStuffAround();
$("#some-button").click(function() {
shuffleStuffAround();
return false; // you probably want this
});
});

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.
});

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
}

Related

Between two event listeners: How do I pass my function without using trigger()?

Please check out my diagram, and the pseudo-code below. I'm trying to figure out how to pass a function between two event listeners.
Basically, I want to execute some code if "Availability" is less than 0, OR when a user clicks "confirm" in a bootstrap dialog. If the Availability is greater than 0, you'll get the special bootstrap dialog.
I'm trying to avoid writing the same code twice. I'm also trying to avoid using trigger $("#btnConfirm").trigger("click", fn1); --- my assumption is that there is a sexier way, like a callback, or something...
So.... how do I get the code I want to execute into the other 'button click' event listener --OR-- how do I return "btnConfirm" back to the event listener that called the dialog?
$("#Select").on("change", function(e) {
fn1 = function() {
//stuff I want to do
};
//a check that must be passed
currAvail = $("#Availability").val();
if (currAvail > 0) {
//show a message, "Are you sure you want to make the thing?"
//if YES, execute fn1()
//fn1() needs to be available to btnConfirm click listener
// use trigger("click", fn1) ????
} else {
//execute the code
fn1();
};
});
$("#btnConfirm").on("click", function(e, param1) {
//Ok, well, they said YES...
//so I need to execute fn1();
});
Since the requirement is to call fn1() in both cases, you can separate the logic out into a method and call when it is needed
function fn1() {
//code to execute on no goes here
}
$("#Select").on("change", function(e) {
let currAvail = $("#Availability").val();
if (currAvail > 0) {
//show modal window
} else {
//execute the code
fn1();
};
});
$("#btnConfirm").on("click", function(e, param1) {
fn1()
});
Why not just move the function definition to outside the change callback?
$("#Select").on("change", function(e) {
//a check that must be passed
currAvail = $("#Availability").val();
if (currAvail > 0) {
//show a message, "Are you sure you want to make the thing?"
//if YES, execute fn1()
//fn1() needs to be available to btnConfirm click listener
// use trigger("click", fn1) ????
} else {
//execute the code
fn1();
};
});
$("#btnConfirm").on("click", function(e, param1) {
//Ok, well, they said YES...
//so I need to execute fn1();
});
// Function move to here.
function fn1() {
//stuff I want to do
};

Jquery Click-handler doesn't work with named function?

I feel like this is one of those problems you only run into after too little sleep or too many coffees...
I have an element
<a id="blah" href="#">somethinghere.com</a>
I define a function
function test(){
alert('hi');
};
I try to attach the function as a click-handler(https://jsfiddle.net/8r1rcfuw/30/):
$('#blah').on('click', test());
and load the page, and the handler executes immediately - without any clicks.
However when I just use an anonymous function as a handler(https://jsfiddle.net/8r1rcfuw/36/) :
$('#blah').on('click', function(){
alert('hi');
});
it works fine
Doing both (https://jsfiddle.net/8r1rcfuw/39/):
$('#blah').on('click', function(){
test();
});
function test(){
alert('hi');
}
seems to work fine - but seems a little redundant.
This feels like something I've done 1000 times before - what gives?
The event handler has to be a function, and you are passing the result of a function to it:
$('#blah').on('click', test());
is the same as:
$('#blah').on('click', undefined); //As your funcion doesn't return anything
Think of it as a function is a value, you can do:
var myFunction = function() {
alert("Hi");
}
or
function myFunction() {
alert("hi");
}
And then:
$('#blah').on('click', myFunction); //Without invocation!
or using an anonymous function:
$('#blah').on('click', function() {
alert("Hi");
});
You can also use object of function :
var temp=function test() {
alert('hi');
}
$('#blah').on('click', temp);
Try :
$('#blah').on('click', test); // your function name only
Updated Fiddle

On click myFunction and wait until it is finished

I thought this is something easy to do but I dont find anything helping me out of this.
I have a function
(function($){
myFunction = function(e){
e.preventDefault();
// do stuff
// load ajax content
// animate and show
}
$('.button').on( 'click', myFunction);
})(jQuery);
now this works but I need to know, wait untill everything is done if someone presses many .buttons in a short time cause there are a few elements with class button
I've tried with promise()
$('.button').on( 'click', function(){
$.when( myFunction() ).done(function() {
alert('finished')
});
});
but that gives me an error e is undefined and
$('.button').on( 'click', myFunction).promise().done(function() {
alert('finisehd');
});
anyone knowing what I'm doing wrong and how I could do it to get it to work?
The most common solution would be to set a variable inside the click handler when myFunction is called and check its state with every call of the click handler.
This could be done somewhere along the lines of this:
(function($){
var wait = false;
myFunction = function(e){
e.preventDefault();
if (wait) {
return;
}
wait = true;
// ...
wait = false;
}
$('.button').on( 'click', myFunction);
})(jQuery);
Your function myFunction expects one argument, when you call myFunction() the argument is missing.
Not tested but it should works:
$('.button').on( 'click', function(e){
$.when( myFunction(e) ).done(function() {
alert('finished')
});
});
In addition to not passing in the e variable. You're using $.when incorrectly.
If you want to have the done function called after myFunction finishes its ajax call. You'll need to return a promise from myFunction.
function myFunction(e) {
return $.Deferred(function(deferred) {
doAjax(function(content) { // callback
deferred.resolve(content);
});
});
}
Now when you do
// inside event handler
$.when(myFunction(e)).done(function(content) {
// whoo!
});

Function becomes undefined after first trigger

I have a block of code like so:
function doSomething() {
someVar.on("event_name", function() {
$('#elementId').click(function(e) {
doSomething();
});
});
}
// and on document ready
$(function () {
$('#anotherElemId').click(function () {
doSomething();
});
});
The problem that I'm encountering is that when I call doSomething() from anotherElemId click event(that is binded on document ready) it works as expected, but calling it recursively from elementId click doesn't work.
Any ideas? Thinking is something trivial that I'm missing.
Is someVar an actual jQuery reference to a dom element? (e.g. $('#someitem'))
The second problem is you cant put a .click event inside a function that you would like to instantiate later on. If you are trying to only allow #elementId to have a click event AFTER some previous event, try testing if a tester variable is true:
var activated = false;
$(function () {
$('#anotherElemId').click(function () {
activated = true;
});
$('#secondElemId').on("event_name", function() {
if (activated) {
// code that happens only after #anotherElemId was clicked.
}
});
});

Using Jquery calling different functions with a singe link

I would like to use single a href link to call different functions .
On first click it should call first_function() and on second click it should call second_function. Like toggling between two functions using same link. Suggest the best way to be done.
Jquery Code :
$(function() {
var IntervalId;
function first_function() {
//code goes here
};
function second_function(){
//code goes here
}
$("#link2").click((function(){
second_function();
}));
$("#link1").click((function(){
first_function();
}));
});
Html Code :
Call function2
Call function1
"Like toggling between two functions using same link."
$("#link1").toggle(
function first_function() {
// Code goes here
},
function second_function(){
// Code goes here
}
);
From the jQuery docs on toggle(fn1, fn2, [fn3, [fn4, [...]]]):
Toggle among two or more function calls every other click.
Javascript:
$(document).ready(function() {
function first_function() {
// Code goes here
};
function second_function(){
// Code goes here
}
$("#link").toggle(first_function, second_function);
});
HTML:
<!-- I'm pretty sure that <a> isn't the right tag for this. -->
<button id="link">Toggle between the two functions.</button>
the easiest way would be
var performFirstAction = true;
$(function() {
function first_function() {
// Code goes here
}
function second_function(){
// Code goes here
}
$("#link1").click(function(){
if(performFirstAction) {
first_function(); performFirstAction = false; }
else {
second_function(); performFirstAction = true; }
});
});
or using toggle as Tomalak mention and well,
$(function() {
function first_function() {
// Code goes here
}
function second_function(){
// Code goes here
}
$("#link1").toggle(
first_function,
second_function
);
});

Categories

Resources