tags:

views:

57

answers:

3

This morning I asked a pretty mundane question about my JS syntax, and someone suggested I use their code instead, so I went ahead with it because I know virtually Zero about JS.

Using my moderate PHP knowledge, I made a slight modification adding a second ID with an 'else if' statement (see below) and was just wondering if you folks who know more about JavaScript could tell me if it all looks good?

Or maybe you would do it differently altogether?

window.onload = formfocus;

function formfocus()
{
    var id_one;
    var id_two;

    id_one = document.getElementById( 'author' );
    id_two = document.getElementById( 's_primary' );

    if ( id_one )
    {
     id_one.focus();
     id_one.value = '';
    }
    else if ( id_two )
    {
     id_two.focus();
     id_two.value = '';
    }
}

EDIT: I am slightly concerned about my window.onload = formfocus(); ... but not really sure if there is any other way to accomplish what I want.

A: 

It looks so good, it is readable and easy to understand.

Just to increase your knowledge about javascript syntax, you could do something like it too:

function formfocus()
{
    var id_one;
    var id_two;

    id_one = document.getElementById( 'author' );
    id_two = document.getElementById( 's_primary' );

    with(id_one || id_two)
    {
     focus();
     value = '';
    }
}

*ps, this example is ugly I know (but I love use "with" LOL).

Cleiton
Please don't use with() ... It's generally seen as a bad practice since any non-existing property access is assumed to be global.
J-P
While it is not significant in such a short snippet, "with" is generally considered bad practice. It forces the Javascript interpreter to check each variable and function call in the block against the functions in the id_one or id_two scope. Not to mention, there will be a great deal of ambiguity in larger scripts; for example, if "value" is also a global variable. See: http://www.barryvan.com.au/2009/05/avoid-javascripts-with-keyword/
Mike Koval
+3  A: 

It could definitely be more terse, especially if you use jquery. But assuming you want to stick to plain old javascript, I'd at least change the following:

var id_one;
var id_two;

id_one = document.getElementById( 'author' );
id_two = document.getElementById( 's_primary' );

to

var id_one = document.getElementById( 'author' );
var id_two = document.getElementById( 's_primary' );

Also, it's fairly standard practice not to surround function arguments with spaces, but I suppose that's a style issue that shouldn't be debated here.

Chris
A: 

While your code is functional, the following is much less verbose:

window.onload = function () {
    var id_one = document.getElementById("author");
    var id_two = document.getElementById("s_primary");

    // Original code...
}

Something to consider if you're planning on writing more Javascript.

Mike Koval