0

Works:

<div onclick="UpdateAttributes();">Update</div>

<script>
function UpdateAttributes() {
            alert(1);

        }
<script>

Doesnt work: (UpdateAttributes is not defined)

<div onclick="UpdateAttributes();">Update</div>

<script>
$(function(){
function UpdateAttributes() {
            alert(1);

        }
 });

<script>

Why is this happening here? I thought good old onload is always the safest bet for declaration?

Thanks!

1
  • Where is the deception? Perhaps misunderstanding would be a more appropriate term. Commented Jul 8, 2015 at 22:38

2 Answers 2

3

In the second example, UpdateAttributes is only visible to the closure of the ready callback function.

It works in the first because the function is globally visible. For the second example, to get it working, you can modify it to

$(function(){
$('div').click(UpdateAttributes);
function UpdateAttributes() {
            alert(1);
        }
 });

since UpdateAttributes will be visible within the callback itself. Also, remove the inline onclick handler in the div itself.

Sign up to request clarification or add additional context in comments.

Comments

2

Because in the second example you declare the function within another function.

In javascript a function represents a local scope and anything created within that scope will be destroyed when the scope exits unless you explicitly expose it by returning it or some other way.

AmmarCSE show another way to explicitly expose the function by assigning it to the event handler.

In your example you assign it as a string and that only binds to global functions.

Another way would have been to use window["UpdateAttributes"] = UpdateAttributes; within the function, but that is a crude and ugly solution ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.