Home > HTML, JavaScript, Optimization, Tips & Tricks, UI > Javascript pseudo protocol (is EVIL)

Javascript pseudo protocol (is EVIL)

This post is somehow related to my previous post about javascript function context.  Recently I helped one of my friends to debug a very funny problem. He told me that his inline event handler doen’t work, because he could not pass this object to his function.
You probably wonder what did I find? :-)

    <script type="text/javascript">
        function doSomething(obj) {
            obj.style.color = '#cc0000';
        }
    </script>
    <a href="javascript:doSomething(this)">Link</a>

this keyword in his case was not A object as expected but window.
Having javascript:  in href attribute is like running JavaScript from address bar of your browser. It will run in window context.
Only if my friend was writing his code like this:

   ...
    <a onclick="doSomething(this)">Link</a>

it would work like charm.

But I never use javascript: at all in my markup. Why?
1. If you need text element that is clickable use span, any visual styling like text-decoration or cursor can be achieved using CSS.
2. If you don’t have actual link behind you shouldn’t use A tag. As far as I know it’s not good for SEO.
3. Javascript problems as i described above can arise
I would write the code above like this:

    ...
    <span style="text-decoration:underline;cursor:pointer;"
                 onclick="doSomething(this)">Link</span>

The only reason I know to use A for JavaScript triggers is to achieve hover effect without use of JavaScript.
If you know another reason why you should/shouldn’t use links as JavaScript triggers you’re welcome to comment.
After this post you can get an impression that I don’t like javascript: notation and you will be wrong,  actually there are very usefull tricks I use all the time:
1. Check some JS value on your page. Type javascript:alert(yourvariable) in the address bar and press enter.

You will get :

2. Or let’s say you have function somewhere on the page and you have to see it quick without searching through all your scripts. Or you wan’t to steal see how someone implemented something :-)
Just type  javascript:alert(yourdesiredfunction) and voila:

UPD:
Just googled good page with JS best practices, it has Javascript: pseudoprotocol part that says almost exactly the same as my conclusions.
http://www.javascripttoolbox.com/bestpractices/

VN:F [1.9.16_1159]
Rating: 4.6/5 (5 votes cast)
Javascript pseudo protocol (is EVIL), 4.6 out of 5 based on 5 ratings

  1. July 14th, 2009 at 06:43 | #1

    Hi, kossovsky.net to GoogleReader!

    VA:F [1.9.16_1159]
    Rating: 5.0/5 (1 vote cast)
  2. October 6th, 2011 at 23:02 | #2

    Hay bro !!!

    Your post was really helpful

    Thanks,
    scorpio

    VA:F [1.9.16_1159]
    Rating: 0.0/5 (0 votes cast)
  1. July 22nd, 2009 at 12:51 | #1

Subscribe without commenting

SEO Powered by Platinum SEO from Techblissonline
watch free movies