Skip to Navigation or
Skip to Content

JavaScript What Is This And How Do I Use It

Feeds

RSS Feed

<< July | August | September >>

Tuesday, 10th August 2010

I was asked today to explain the "this" keyword in JavaScript, so here is a quick explanation of how it works...

Simple "this" example

<p onclick="alert(this.id);" id="example">Click On Me</p>

"this" is a great way of getting the HTML element that started off an event. In the little snippet above, "this" is the paragraph. When you call "this.id", you get the id of the paragraph, i.e. "example".

A Bit More Complicated "this" example

<p id="example">Click On Me</p>
<script type="text/javascript">
    document.getElementById("example").onclick = function () {
        alert(this.id);
    };
</script>

This example works in exactly the same way as before, so you don't have to put your events on the HTML element to use "this". In this example we bind the event using JavaScript and everything directly inside of our function will magically understand that "this" refers to the paragraph you click on.

If you bind the same event handler to lots of HTML elements, "this" will always be the one that got clicked on - really handy!

 

You Are Here: Home » Blog » JavaScript What Is This And How Do I Use It

 

I use a cookie on this website. This cookie doesn't contain or relate to any personal information and it isn't shared with any other website, it just ensures that I don't count you more than once in my website statistics. The Privacy and Electronic Communications Regulations require me to ask your permission to use this cookie, so please indicate below that you are happy for me to do this - I will remember your selection with a cookie, so if you accept I won't ask again...