So you want to execute a function whose name is in a string or variable:
var fn = "foobar";
function foobar() {
console.log('say something');
}
Answers like this - How to execute a JavaScript function when I have its name as a string - say to do this:
window[fn](); // outputs 'say something'
But... this does not work for some reason:
jQuery(document).ready(function($){
var fn = "foobar";
function foobar() {
console.log('say something');
}
window[fn](); // undefined
});
This works, however:
jQuery(document).ready(function($){
var fn = "foobar";
window[fn](); // outputs 'say something'
});
/* I'm outside the ready handler */
function foobar() {
console.log('say something');
}
I want to keep my functions inside that ready handler so I don't have to write a bunch of anonymous functions to define jQuery
as $
. How do I do that?
Update
Here's what I'm wanting to do:
<div data-control="toggleNext">FAQ</div>
<div>Here's some text that will be hidden until toggled</div>
JS:
jQuery(document).ready(function($){
function toggleNext() {
// add ".js_toggled" to .next() element
}
$('[data-control]').each(function(){
var fn = window[$(this).data('control')]; // <-- this don't werk
if (typeof fn === 'function') fn(this);
});
});