[Javascript] onclick - unobtrusive javascript

Julien Nadeau junado at junado.com
Mon Aug 1 17:01:19 CDT 2005


I'm not exactly sure why, but here's my thoughts and a working solution.

Since you're applying a function to an onclick event that refers to  
the item itself, you have to refer to it as you normally would if it  
was inline.

Therefore, changing the line:

links[i].style.color = 'red';

to

this.style.color = 'red';

works for me in Firefox 1.0.4 and Safari 2.0 on Tiger, so I guess it  
will work everywhere else.

Julien Nadeau
junado at junado.com

Le 05-07-22 à 22:14, Tim Burgan a écrit :

> Hello,
>
> I'm trying to use some unobtrusive Javascript by separating  
> behavior from structure.
>
> When an element is clicked, I am unable to change it's text color  
> to red.
> But for the same element, the code does work if I choose to open a  
> new window on click.
>
> Is there any particular reason why I can't get this to work? My  
> code is attached below.
>
> Thanks
>
> Tim
>
>
>
> <script type="text/javascript">
>   function doPopups()
>   {
>      if ( !document.getElementsByTagName )
>         return false;
>         var links = document.getElementsByTagName("a");
>         for ( var i = 0; i < links.length; i++ )
>      {
>         if ( links[i].className.match("change") )
>         {
>            links[i].onclick = function()
>            {
>               // this line works
>               window.open(this.href);
>               // this line does not
>               links[i].style.color = 'red';
>               return false;
>            }
>         }
>      }
>   }
>   window.onload = doPopups;
> </script>
>
>
> <a href="#" class="change">Use another address</a>
>
>
> _______________________________________________
> Javascript mailing list
> Javascript at LaTech.edu
> https://lists.LaTech.edu/mailman/listinfo/javascript
>
>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.evolt.org/pipermail/javascript/attachments/20050801/5a2794c7/attachment.htm>


More information about the Javascript mailing list