Thursday, February 24, 2011

keyword "this" in javascript

Take a look at the following codes:
<span onclick="spanClick();" class="node" id="span1"><a href="#">link</a></span>

<script type="javascript/text">
  function spanClick() {
      $(this).addClass("style1"); 
  }
</script>

This will not work as expected because in javascript $(this) function in this case will refer to the browser window object instead of the HTMl element "span1".
To fix this, we need to add "this" inside the spanClick() and change it to:

<span onclick="spanClick(this);" class="node" id="span1"><a href="#">link</a></span>

<script type="javascript/text">
  function spanClick(obj) {
      $(obj).addClass("style1"); 

  }

</script>


This function will work as expected and add a css class "style1" to element "span1".

This link has very good explanation of the 'this' keyword.
http://www.quirksmode.org/js/this.html



The next function I want to mention is the Jquery function to select child and parent element.

In our above example again, if we want to use Jquery to select the link and change its style, we can use code:

$(obj).find('a:first').addClass('style2').



To set the parent style of the span element, we can use code:

$(obj).parent().addClass('style3').

If we don't just want to go to the immediate parent, we can use function parents()
for example,
$(obj).parents("span").addClass('style3').
to go to the parent element span.

Jquery is really powerful.

Happy programming!

No comments:

Post a Comment