Why is this simple code not working? Can someone explain it to me?
JSFiddle
I have called the cc() function in onclick attribute.
HTML
<div> hey </div>
<button onclick="cc()"> click me to change color</button>
Javascript
$(document).ready(function () {
function cc() {
$('div').css('color', 'red');
};
});
cc is not a global function.
It is defined with a function declaration, so it is scoped to the function it is defined in.
That function is the anonymous one that you pass to the ready method. (And you do that inside a function that you run onload due to your jQuery configuration).
Globals are (in general) something to be avoided as much as possible, and intrinsic event attributes usually depend on them.
Don't use intrinsic event attributes. Bind your JavaScript event handlers using JavaScript. Since you are using jQuery, use the on method.
$(document).ready(function(){
function cc(){
$('div').css('color','red');
};
$('button').on('click', cc);
});
demo
The code in the onclick attribute only has access to global functions/variables. The function cc is local to the function it is defined in. You'll want to either define it outside of that function (so it is automatically global) or assign it to window.cc to explicitly make it global (I suggest the second option).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With