0

I thought that JavaScript is simple, but seems that it doesn't work

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
function org(){
    $(this).toggle()
}
</script>
<span onClick="org()" id="kaka">Click me and i hide</span>

Anyone knows what's wrong?

mikroskeem
  • 37
  • 1
  • 9

2 Answers2

7

this in your code is not referencing your <span> element. You need to pass a reference to your element.

<script>
function org(e){
    $(e).toggle()
}
</script>
<span onClick="org(this)" id="kaka">Click me and i hide</span>

Alternatively (and this is really the preferred way) you can attach an event handler and avoid using an inline handler:

<script>
$("kaka").on("click", function() {
    $(this).toggle()
});
</script>
<span id="kaka">Click me and i hide</span>
ElGavilan
  • 6,610
  • 16
  • 27
  • 36
  • 2
    Just saying for such a simple answer for a question that is asked here like everyday. It's not like this answer is innovative. – Ryan Apr 15 '14 at 19:03
  • @RPM If that's the case, you should close the question instead of answering it ;) Don't you have the rep? (I think it's 2000 but i'm not sure) – Karl-André Gagnon Apr 15 '14 at 19:07
  • I don't care that much. I just don't see this answer as being that valuable. It probably is for the beginners. – Ryan Apr 15 '14 at 19:08
2

You don't need to pass a reference to the element. You can also tell the function to use the element for this

<span onClick="org.call(this);" id="kaka">Click me and i hide</span>

Demo: JSFiddle

Ryan
  • 14,392
  • 8
  • 62
  • 102