Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why this simple onclick function not working

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');
    };
});
like image 482
halkujabra Avatar asked Aug 09 '26 02:08

halkujabra


2 Answers

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

like image 180
Quentin Avatar answered Aug 10 '26 15:08

Quentin


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).

like image 24
Aaron Dufour Avatar answered Aug 10 '26 14:08

Aaron Dufour