PDA

View Full Version : The most basic question you will ever see. Regarding "this".



jlizarraga
06-23-2008, 05:51 PM
Can someone tell me what is going wrong in this example?

JS:



function hideMe() {
this.style.display="none";
}

HTML:



<a href="javascript:void(0);" onclick="hideMe();">
Some text.
</a>

I get the error "this.style is null or not an object" in IE6, and "this.style has no properties" in FF2. Shouldn't "this" in this instance be referencing the anchor tag?

jscheuer1
06-23-2008, 06:34 PM
This reminds me of the now infamous and probably mostly forgotten quote:

"That depends upon what the meaning of 'is' is."

Anyways, no. In a free standing function like that, this refers to the window.

You could:


function hideMe(el) {
el.style.display="none";
}

and:


<a href="javascript:void(0);" onclick="hideMe(this);return false;">
Some text.
</a>

There are other ways to assign functions as events to elements and, depending upon the browser and the method used, your original syntax would actually work.

jlizarraga
06-23-2008, 06:54 PM
Thanks!

boogyman
06-25-2008, 07:48 PM
You could:


function hideMe(el) {
el.style.display="none";
}

and:


<a href="javascript:void(0);" onclick="hideMe(this);return false;">
Some text.
</a>

There are other ways to assign functions as events to elements and, depending upon the browser and the method used, your original syntax would actually work.

While this solution works, its really overlapping the design with the dynamics. Another solution that would work would be to use the javascript to assign/re-assign the a class/id to this element which would use that class/id styles which state this element and its child parts as "obsolete" for the moment.



<script type="text/javascript">
function hideEl(el) {
el.setAttribute('class', 'className');
}
</script>

<style type="text/css">
.className {display:none}
</style>

<p><a href="" onclick="hideMe(this)">View/Hide</a></p>


that would work too, however at the same time you are still writing inline javascript, so depending on how many times you had this appear within the page and/or document it might be better to take out the javascript and use full obtrusive javascript, separating the content layer from the design layer