Reputation: 441
How to pass variables to an anonymous function. I want to pass few variables to an anonymous function, based on the function, it will create a new string. In this code, i want to pass url, timestamp, id and plan.
<script>
jQuery(document).ready(function() {
console.log("check")
var newUrl=url+'?id='+id+'×tamp='+timestamp+'&plan='+plan;
console.log(newUrl);
createStoryJS({
type: 'timeline',
width: '1250',
height: '240',
source: newUrl,
embed_id: 'my-timeline'
});
});
</script>
Upvotes: 2
Views: 953
Reputation: 3486
First of, jQuery(document).ready(function() {});
would be the entry point of document when it is ready to be accessed. There are several approaches to this.
The idea is you do not need to pass anything but use your resources you created in this anonymous function.
I want to pass few variables to an anonymous function, based on the function, it will create a new string.
I would not recommend you to use global variables. That function from which you probably get those values for id
, timestamp
and plan
should return you that sting itself which you can assign to newUrl
inside document ready function. You can use a closure also.
function returnUrl(){
// code to calculate id, timestamp and path..
// ....
// ....
return url+'?id='+id+'×tamp='+timestamp+'&plan='+plan;
}
jQuery(document).ready(function() {
// DOM ready to access..
console.log("check")
var newUrl = returnUrl();
console.log(newUrl);
createStoryJS({
type: 'timeline',
width: '1250',
height: '240',
source: newUrl,
embed_id: 'my-timeline'
});
});
Upvotes: 0
Reputation: 4601
You can declare a variable with global scope and use it inside the function call as below
var globalVar = 1;
jQuery(document).ready(function() {
console.log(globalVar);
});
Upvotes: 2
Reputation: 41065
The argument to the ready handler is passed by jQuery and is set to the jQuery object (see https://api.jquery.com/ready/ > Aliasing the jQuery Namespace). So you can't pass it into the function declaration in your above code.
You could set it to a global object or set a form field and then read it from inside your function. Fiddle for the latter - http://jsfiddle.net/eqz7410c/
HTML
<form>
<input id="b" type="hidden" value="123" />
</form>
JS
$(document).ready(function() {
alert($("#b").val())
});
Upvotes: 1