How to call a function within $(document).ready from outside it - javascript

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?

Related

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

load a function from jquery defined from external js file

I am trying to do this but it give me an undefined function
$(function () {
function Test(){
Test1();
}
Test1();
});
external.js
$(function () {
function Test1(){
alert("HI");
}
});
how can I avoid the Test1() is undefined error ??
Make the function globally:
$(function () {
window.Test = function(){
Test1();
}
Test1();
});
also make sure Test1has been defined somewhere else!
Your "Test1" function is local to a anonymous function, cannot be visible outside that function. So you need put "Test1"'s definition global.
function Test1() {
//...
}
Don't put this in another function or
window.Test1 = function() {
//...
}
try to change you external.js file from
$(function () {
function Test1(){
alert("HI");
}
});
to
function Test1(){
alert("HI");
}
it has no sense to wrapping Test1 function into on-load

Calling a function (ex. namespace.show) by name

I want to call a function with a namespace based on its name.
Perhaps some background: What I want is, dynamically bind pages via $.mobile.loadPage(inStrUrl, { showLoadMsg: false }); and then, based on the current page, invoke a function within a loaded page. For example: each page has a showFilter function, the Event is attached to a main.html - page which should call the matching function in the current page.
I also tried some solutions, with jquery too, but nothing works for me.
This is my function code:
function namespace() { }
namespace.showFilter = function () {
alert("Test");
}
And want to "invoke" or "call" it via its name.
This is what i tried at least.
$(document).ready(function() {
var fn = window["namespace.showFilter"];
fn();
});
I get error TypeError: fn is not a function
Here is a fiddle http://jsfiddle.net/xBCes/1/
You can call it in the following way:
$(document).ready(function() {
window["namespace"]["showFilter"]();
});
or
$(document).ready(function() {
window["namespace"].showFilter();
});
or
$(document).ready(function() {
window.namespace.showFilter();
});
I found that I had to manually set it to window.
window.namespace = function() { }
window.namespace.showFilter = function () {
alert("Test");
};
$(document).ready(function() {
var fn = window["namespace"]["showFilter"];
fn();
});
http://jsfiddle.net/xBCes/4/
Like this:
$(function() {
window.namespace.showFilter();
});
P.S. I shortened the $(document).ready(...)
function namespace() {}
namespace.showFilter = function () {
alert("Test");
}
$(document).ready(function() {
var fn = namespace.showFilter();
fn();
});
http://jsfiddle.net/xBCes/3/

call a function using window[variablename](); in document.ready

I have functions in side a document.ready and I want to call them using value inside a variable.. I tried to use window[variablename](); but it is not working inside document.ready but when called it directly it works..
think this is the function inside the document.ready
$(document).ready(function() {
function jhon(){
alert('works');
};
});
I'm getting function name from a variable,value of that variable is the name of the function..
below code will get the URL's hashed part example: #JHON and remove # and store it inside URLHASH variable..example: JHON
var urlhash = document.location.hash;
urlhash = urlhash.replace(/^.*#/, '');
when I called like this it is not working..
window.onload=function() {
window[urlhash]();
};
but when I call the function like this it is working fine..
window.onload=function() {
jhon();
};
Is it possible to call a function using variable value?
This:
window.onload=function() {
window[urlhashed]();
};
Contains a typo: urlhashed ought to be urlhash
window.onload=function() {
window[urlhash]();
};
In addition to that you have defined jhon() inside of another function, which capture's it in that enclosing functions scope.
if you want to have this work as intended you ought to change this:
$(document).ready(function() {
function jhon(){
alert('works');
};
});
to be more like this:
$(document).ready(function() {
window.jhon = function(){
alert('works');
};
});
Define the function jhon outside of $(document).ready. Otherwise, it'll be hidden, and thus inaccessible via window[function_name]:
function jhon(){
alert('works');
};
$(document).ready(function() {
var urlhash = document.location.hash;
urlhash = urlhash.replace(/^.*#/, '');
window[urlhash]();
});

Javascript anonymous function vs normal function

What's the difference between:
<script type="text/javascript">
$().ready(function() {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=SomeLink]").click(function() {
if (!CompareDictionaries(InitialDictionary))
{
alert('Hello')
}
}
)
})
</script>
and
<script type="text/javascript">
$().ready(function () {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=SomeLink]").click(CheckValuesChanged(InitialDictionary));
})
function CheckValuesChanged(InitialDictionary) {
if (!CompareDictionaries(InitialDictionary))
{
alert('Hello')
}
}
</script>
Without going into details into what I'm trying to achieve here, is there any reason why an anonymous method works fine and the call to a function doesn't? Shouldn't they produce the same results?
To call a function you have to do this:
$("a[id*=LogoLink]").click(function(){CheckValuesChanged(InitialDictionary)});
Or:
$("a[id*=LogoLink]").click("CheckValuesChanged(InitialDictionary)"); //might work
They both work, but you cannot bind a function to an event like this
$("a[id*=LogoLink]").click(CheckValuesChanged(InitialDictionary));
because the a function must be bound to the click event. When you pass an argument to the function it returns undefined, which is not a function. You can fix this by changing your second code sample like so:
$().ready(function () {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=LogoLink]").click(CheckValuesChanged);
function CheckValuesChanged() {
if (!CompareDictionaries(InitialDictionary)) {
alert('Hello')
}
}
});
The second example is wrong:
$("a[id*=LogoLink]").click(CheckValuesChanged(InitialDictionary));
It should be:
$("a[id*=LogoLink]").click(CheckValuesChanged);
But because you want to pass InitialDictionary as argument you need to use the first approach which will capture it in the anonymous function.

Categories

Resources