mikroskeem
mikroskeem

Reputation: 47

JavaScript this and onClick

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?

Upvotes: 0

Views: 162

Answers (2)

Ryan
Ryan

Reputation: 14659

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

Upvotes: 2

ElGavilan
ElGavilan

Reputation: 6924

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>

Upvotes: 7

Related Questions