halkujabra
halkujabra

Reputation: 2942

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');
    };
});

Upvotes: 3

Views: 200

Answers (5)

Dreamwalker
Dreamwalker

Reputation: 3035

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.

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59292

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/

Upvotes: 0

Suman Bogati
Suman Bogati

Reputation: 6351

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

Upvotes: 0

Aaron Dufour
Aaron Dufour

Reputation: 17535

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

Upvotes: 1

Quentin
Quentin

Reputation: 944530

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

Upvotes: 10

Related Questions