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

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]();
});

Related

Function out of scope?

I have a function defined as follows:
window.onload = function() {
var ids = document.getElementById("idname");
function myFunction(){
/...*use ids var in here*./
}
}
I am trying to call myFunction from button onclick in html:
<button onclick="myFunction();"></button>
But it says myFunction is not defined. I understand because this is inside window.onload. How can I fix this? I need window.onload because I need to use document.getElementById("testID") to get content.
I need window.onload because I need to use document.getElementById("testID") to get content
No, you don't need window.onload. You simply have to put the code somewhere after the element with ID testID in the document.
Example:
<div id="testID"></div>
<script>
var ids = document.getElementById("testID");
function myFunction(){
/...*use ids var in here*./
}
</script>
However, if you want to keep using window.onload, then I suggest to not use inline event handlers, but bind the handler with JS:
window.onload = function() {
var ids = document.getElementById("testID");
ids.onclick = function(event){
/...*use ids var in here*./
}
};
(that might be a good thing to do anyway).
Lastly, you can get the a reference to the element inside the event handler using this or event.target:
<div id="testID"></div>
<script>
document.getElementById("testID").onclick = function(event) {
// access element via `this` or `event.target`
};
</script>
Learn more about event handling.
You defined it within a function so it's locked to that scope. Maybe you want to define it outside of that:
function myFunction() {
var ids = document.getElementById("idname");
// ...
}
window.onload = function() {
// ...
}
As a note, this is extremely old-school JavaScript. You could clean this up considerably using something like jQuery which would look something like this:
$(function() {
// Any initialization after page load.
});
function myFunction() {
var ids = $('#idname');
// ...
}

jQuery parse object to a secondary function

I am trying to parse $(this) to a function called by another function but without much luck. Essentially my question is; is it possible and if so, how?
Code is as follows:
Initial Call
$('.playform').on('click', playForm);
Primary Function
function playForm(e){
...snip...
TweenLite.to($('.video'), 1, {css:{'height':win.h+'px'}, ease:Power4.easeInOut, onComplete:showForm});
...snip...
}
Secondary Function
function showForm{
$('.video #youtube').append('<iframe class="show-form" src="'+$('.playform').attr('href')+'"></iframe>');
}
As I am going to be using more than one form, I wanted to automate this process but I cant seem to
Things I have tried so far but to no avail
Declared $(this) as a variable
Tried to give the functions parameters
Step 1
$('.playform').on('click', function(){
var whichVid = $(this);
playForm(whichVid);
});
Step 2
function playForm(e){
TweenLite.to($('.video'), 1, {css:{'height':win.h+'px'}, ease:Power4.easeInOut, onComplete:showForm(e)});
}
Step 3
function showForm(e){
$('.video #youtube').append('<iframe class="show-form" src="'+e.attr('href')+'"></iframe>');
}
Alternatively you could establish a global variable before step 1 and then set the value on the click event like
var window.whichVid = '';
$('.playform').on('click', function(){
window.whichVid = $(this);
playForm();
});
function playForm(){
TweenLite.to($('.video'), 1, {css:{'height':win.h+'px'}, ease:Power4.easeInOut, onComplete:showForm()});
}
function showForm(){
var thisVid = whichVid.attr('href');
$('.video #youtube').append('<iframe class="show-form" src="'+ thisVid +'"></iframe>');
}
you could put it like this (not tested) :
(function($){
var global_this;
function palyform(e){
global_this = $(this)
...
}
function showform(e){
// do shomething with global_this
...
}
$('.playform').on('click', playForm);
}(jQuery);

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/

Why cant my anchor fire this javascript object?

I have a page with a linked javascript object:
//the constructor function
function NewsScroller() {
}
//now put some config objects using the JSON structure
NewsScroller.prototype.config = {
serviceUrl : '/NewsProvider.svc/rest/GetNews/',
pageIndex : 0
}
//the argumented constuctor for this object
NewsScroller.prototype.init = function () {
this.getNews(this.config.pageIndex);
console.log(this.config.pageIndex);
}
NewsScroller.prototype.decreasePage = function () {
console.log('current page index ' + this.config.pageIndex);
}
Then I have the page ready declaration:
<script>
$(document).ready(function () {
var newsScrollerForPage = new NewsScroller();
newsScrollerForPage.init();
newsScrollerForPage.decreasePage();
});
</script>
Which produces the result:
current page index 0
I want to call the function from an anchor tag so I have:
<div class="scroller-left">
<a id="scroller-left-a" href="javascript:newsScrollerForPage.decreasePage();">
<img src="/Images/Left-Scroller.jpg"/>
</a>
</div>
But when I click the anchor I get:
newsScrollerForPage is not defined
Why is this? Surely I should be able to call the object and function just like I did in the .ready method?
You define the newsScrollerForPage inside the ready function with local scope (by using "var"), you can't use it outside of there except if you define a function in the same scope which uses it (scope is evaluated from where functions are defined, not from where they are called).
You can quickly fix the issue by taking away the var from before it (making it more global rather than local in scope) but I wouldn't suggest this as the best solution.
Better would be to link up the anchor like this:
$(document).ready(function () {
var newsScrollerForPage = new NewsScroller();
newsScrollerForPage.init();
newsScrollerForPage.decreasePage();
document.getElementById("scroller-left-a").onclick=function()
{
newsScrollerForPage.decreasePage();
return false;
}
});
and removing the href from the HTML element.

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

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?

Categories

Resources