You have defined the method hello
with the closure of the dom ready handler, so it won't be a property of the window object, only global variables/function are accesible as property of window object.
So either assign it as a property of the window object
$(document).ready(function() {
$('input').click(function() {
var name = 'hello';
var msg = 'hello world!';
window[name](msg);
});
window.hello = function hello(msg) {
alert(msg);
}
});
input {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">
Or define it outside of the closure
$(document).ready(function() {
$('input').click(function() {
var name = 'hello';
var msg = 'hello world!';
window[name](msg);
});
});
function hello(msg) {
alert(msg);
}
input {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">
But a more appropriate approach could to use a different object than the window object like
$(document).ready(function() {
$('input').click(function() {
var name = 'hello';
var msg = 'hello world!';
fns[name](msg);
});
var fns = {};
fns.hello = function hello(msg) {
alert(msg);
}
});
input {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">