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
Related
I have a code like this:
function myfunc () {
alert('executed');
}
$('.classname').on('click' function () {
myfunc();
});
I want to run myfunc once. I mean I don't want to execute it every time when user clicks on .classname element. I guess I need to warp function-calling into a condition. Something like this:
if ( /* that function never executed so far */ ) {
myfunc();
}
How can I do that?
The simplest way with jQuery is to use .one
function myfunc() {
alert('executed');
}
$('.classname').one('click', function() {
myfunc();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="classname">click here!</button>
You should remove the event listener in the function you're calling:
function myfunc () {
alert('executed');
$('.classname').off('click', myfunc);
}
$('.classname').on('click', myfunc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='classname'>Click Me</div>
Don't set a global variable like the other posts describe - there's no need for that and then you're still doing an unnecessary function call. This ensures the function is never called again and the event isn't being listed for.
$( document ).ready(function() {
var hasBeenExecuted = false;
function myfunc () {
alert('executed');
hasBeenExecuted = true;
}
$('.classname').on('click' function () {
if(!hasBeenExecuted){
myfunc();
}
});
});
var functionWasRun = false;
function myfunc () {
functionWasRun = true;
alert('executed');
}
$(document).ready(function() {
$('.classname').on('click', function () {
if (!functionWasRun) {
myfunc();
}
});
});
I would suggest, as an alternative to a global variable, assigning a property to the function.
function myfunc () {
alert('executed');
myfunc.executed = true;
}
$('.classname').on('click', function () {
if(!myfunc.executed) {
myfunc();
}
});
This has the advantage of working the same way while not polluting the global scope unnecessarily. However, if skyline3000's answer works for you, you should use that instead as it's cleaner and more sensible overall.
I have this function:
$("#btn").click(function(e,someOtherArguments)
{ //some code
e.stopPropagation();});
It works, but If I have named function I can't use e because it is undefined.
var namedFunction= function(e,someOtherArguments)
{
//some code
e.stopPropagation();
}
$("#btn").click(namedFunction(e,someOtherArguments));
I would like to use this namedFunction because several buttons use it.
Either:
$("#btn").click(namedFunction);
Or:
$("#btn").click(function(e,someOtherArguments){
namedFunction(e, someOtherArguments);
});
You can call that function directly in the click event
$("#btn").click(function(e,someOtherArguments){
namedFunction(e, someOtherArguments);
});
You can use apply like so:
$("#btn").click(function(e,someOtherArguments){
namedFunction.apply(this, arguments);
});
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
}
I have this:
function cool(){
function alsocool(){
}
}
And I run the cool() on button click:
$(selector).on('click', function(){
cool();
}
How can I run the cool() and the alsocool() from the same click? Note that I don't want to do:
function cool(){
function alsocool(){
}
alsocool();
}
If I do :
$(selector).on('click', function(){
cool(); alsocool();
}
it doesn't work.
Is it possible to run a function inside a function on the same call?
EDIT:
I DO WANT to pass cool() since obviously alsocool() is not recognized once its inside function cool() BUT cool(); is passed from many selector thus I want to know from which selector is passed and take the appropriate action.
Example I want something like this:
function cool(){
// If this was called by button1, run alsocool() else bypass it
function alsocool(){
}
// some code goes here
}
$("#button1").on('click', function(){
cool(); alsocool();
// If button1 clicked, run cool AND alsocool
}
$("#button2").on('click', function(){
cool(); // If button2 clicked, run cool ONLY.
}
The answer is simple: It is impossible.
The inner function is local to the containing function's scope so unless that function calls it, it cannot be called at all.
If you want both functions to be reachable from outside, define alsocool outside cool, i.e. on the same level as cool.
As per your comment, here's a way that would use a parameter to determine if the inner function should be called or not:
function cool(callInner){
function alsocool(){
}
if(callInner) {
alsocool();
}
}
If you do
function cool() {
function alsocool() { ... }
}
Then 'alsocool' only exists while the cool() function is executing. It will not be externally accessible.
You'd want:
function cool() { ... }
function alsocool() { ... }
$(selector).click(function() {
cool();
alsocool();
}):
The problem is that because you've defined the function alsocool within cool, it's visibility is limited to that scope.
Because of this, you can only call the function alsocool from within cool.
You can, of course, move the declaration of alsocool outside of cool, and this will still allow you to call alsocool from within cool, but you will loose access to the scope of cool from within alsocool.
You could also limit the invocation of alsocool inside cool depending on a parameter passed, if this is a viable option for you;
function cool(alsoAlsoCool){
function alsocool(){
}
if (alsoAlsoCool) {
alsocool();
}
}
// cool(true) will call it, but cool() or cool(false) won't.
You can't do that. alsocool only exists inside cool, the click handler has no idea alsocool exists.
If you don't want to call alsocool from inside cool, then you're gonna have to make alsocool global.
I don't understand why you want to do that, but you can do this :
function cool()
{
arguments.callee.alsoCool = function() {
alert("also cool");
};
alert("cool");
}
$("#b").click(function() {
cool();
cool.alsoCool();
});
Live demo: http://jsfiddle.net/ENqsZ/
Alternatively, as a Rocket suggested, you can do this :
function cool()
{
alert("cool");
return function() {
alert("also cool");
};
}
$("#b").click(function() {
var alsoCool = cool();
alsoCool();
});
How do you call function lol() from outside the $(document).ready() for example:
$(document).ready(function(){
function lol(){
alert('lol');
}
});
Tried:
$(document).ready(function(){
lol();
});
And simply:
lol();
It must be called within an outside javascript like:
function dostuff(url){
lol(); // call the function lol() thats inside the $(document).ready()
}
Define the function on the window object to make it global from within another function scope:
$(document).ready(function(){
window.lol = function(){
alert('lol');
}
});
Outside of the block that function is defined in, it is out of scope and you won't be able to call it.
There is however no need to define the function there. Why not simply:
function lol() {
alert("lol");
}
$(function() {
lol(); //works
});
function dostuff(url) {
lol(); // also works
}
You could define the function globally like this:
$(function() {
lol = function() {
alert("lol");
};
});
$(function() {
lol();
});
That works but not recommended. If you're going to define something in the global namespace you should use the first method.
You don't need and of that - If a function is defined outside of Document.Ready - but you want to call in it Document.Ready - this is how you do it - these answer led me in the wrong direction, don't type function again, just the name of the function.
$(document).ready(function () {
fnGetContent();
});
Where fnGetContent is here:
function fnGetContent(keyword) {
var NewKeyword = keyword.tag;
var type = keyword.type;
$.ajax({ .......
Short version: you can't, it's out of scope. Define your method like this so it's available:
function lol(){
alert('lol');
}
$(function(){
lol();
});
What about the case where Prototype is installed with jQuery and we have noconflicts set for jQuery?
jQuery(document).ready(function($){
window.lol = function(){
$.('#funnyThat').html("LOL");
}
});
Now we can call lol from anywhere but did we introduce a conflict with Prototype?