1

A simple JavaScript onclick event is not working but I don't understand why, here is the code:

<button onclick="removeLol()">remove style</button>

function removeLol() {
    alert("hello");
}

and here is a simple example: http://jsfiddle.net/YNQg6/1/

3
  • Changing the fiddle to use "No wrap" fixes it. But that solution may not be what you need in the real page. Commented Mar 31, 2013 at 7:55
  • Tip: Check the console for errors. Commented Mar 31, 2013 at 7:55
  • 1
    @funkybro No, that's not right. You need parentheses to call a function. Commented Mar 31, 2013 at 7:56

2 Answers 2

4

That's only because of the way how jsfiddle inserts the javascript.

Jsfiddle wraps your code into a function which limits the scope and protects the global namespace:

window.onload=function(){
  function removeLol() {
    alert("hello");
    element.className = element.className.replace(" lol ", "");
  }
}

If you tell jsfiddle to inject the code into the document body it works:

http://jsfiddle.net/YNQg6/13/

Or you could turn your "local" function in a global one:

window.removeLol = removeLol;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, now I understand I haven't tested the code on localhost because I have been playing on jsFiddle.
0

The code works just fine (just tried it on my server). Check your console for other errors that may be causing the script to not run

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.