How we can call start() JavaScript function for this case from HTML:
(function() {
var never, start;
never = function() {
return alert("try");
};
start = function() {
return alert("try harder");
};
}).call(this);
My HTML
<input type="button" value="press" onclick="never()" ></input>
3 Answers 3
When you assign event handler code to attributes, any functions that are used need to be available in the global variable scope.
To accomplish this, you can make them properties of window. Currently, your never and start functions are local to the IIFE function scope.
// IIFE function
(function() {
// var never, start; // local variables
// Make the functions globally scoped
window.never = function() {
return alert("try");
};
window.start = function() {
return alert("try harder");
};
}).call(this);
You can expose a single namespace if you prefer
// IIFE function
(function() {
var ns = window.ns = {};
// Make the functions globally scoped
ns.never = function() {
return alert("try");
};
ns.start = function() {
return alert("try harder");
};
}).call(this);
And then change your inline handler to use ns.never(); and ns.start();.
3 Comments
First give your input tag an id:
<input id="someInputField" type="button" ... />
Next register a callback on it by executing code when the document is ready:
$(document).ready( function() {
// define a function called never
function never() {
alert( 'Never say never');
}
// register a function on the click event handler of that input tag:
$('#someInputField').click( never );
});
5 Comments
onclick="start()" is obtrusive, but somehow it isn't obtrusive to do id="someInputField", and wait for the DOM to load, and manually assign a handler? Either way you're linking code into HTML.You may find it easier to use a javascript library like jQuery. Using that library you can do this:
<script type="text/javascript">
$(document).ready(function() {
var count = 0
$("#tryme").click(function () {
if (count == 0) {
alert('try');
count++
}
else if (count == 1) {
alert('try harder');
}
});
});
</script>
<input type="button" value="press" id="tryme" ></input>
neveris not the global and therefore cannot be found.