3

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');
    };
});
Barbara Laird
  • 12,599
  • 2
  • 44
  • 57
halkujabra
  • 2,844
  • 3
  • 25
  • 35

5 Answers5

10

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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

Aaron Dufour
  • 17,288
  • 1
  • 47
  • 69
0

You should attach the handler inside the document.ready something like

html

<div> hey <div>
    <button  id="mybutton"> click me to change color</button>

javaScript

$(document).ready(function(){
    //attach the function here
    $("#mybutton").click(
        function (){
           $('div').css('color','red');
        }
    );

});

DEMO

Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
0

CC is a global

I have updated you fiddle with a working example

Html

<div> hey <div>
<button> click me to change color</button>

Javascript

$('button').click(function()
{
    $('div').css('color','red');                       
});

http://jsfiddle.net/zWtZ2/4/

I wouldn't normally do this but I wanted to give you minimal changes to your code. As you are selecting every single button on div.

Dreamwalker
  • 3,032
  • 4
  • 30
  • 60
0

As said by Quentin, cc isn't a global function.

But also, the function needs to be declared before it is called. So in fiddle, you should wrap the function in head.

Updated demo:http://jsfiddle.net/zWtZ2/3/

Amit Joki
  • 58,320
  • 7
  • 77
  • 95