Onload Form Focus

I

ibizara

<script type="text/javascript">
function formfocus() {
document.getElementById('search').focus();
}
window.onload = formfocus;
</script>

I'm looking to add ¬

"is there is a element with the id search if so auto focus"

else

"do nothing"

Many Thanks to anyone wishing to help,
ibizara
 
B

Bart Van der Donck

ibizara said:
<script type="text/javascript">
   function formfocus() {
      document.getElementById('search').focus();
   }
   window.onload = formfocus;
</script>

I'm looking to add
"is there is a element with the id search if so auto focus"
else
"do nothing"

<body onLoad="
if (document.getElementById('search'))
document.getElementById('search').focus();
">

Hope this helps,
 
A

AKS

š <body onLoad="
š š š š š š š š šif (document.getElementById('search'))
š š š š š š š š šdocument.getElementById('search').focus();
š š š š š š š š">

Hope this helps,

It's not enough. In IE there can be an error. Check this:

<body onload="
if (document.getElementById('search'))
document.getElementById('search').focus();
">

<input type='text' id='search' style='visibility:hidden;'>
 
T

Thomas 'PointedEars' Lahn

AKS said:
It's not enough. In IE there can be an error. Check this:

<body onload="
if (document.getElementById('search'))
document.getElementById('search').focus();
">

<input type='text' id='search' style='visibility:hidden;'>

The logical course of action should be clear then:

<script type="text/javascript">
function isMethod(o, p)
{
return /\b(function|object)\b/i.test(o[p]) && o[p];
}

function focusElementById()
{
var o = document.getElementById("search");
if (o && isMethod(o, "focus")
&& typeof o.style == "undefined"
|| typeof o.style.visibility != "undefined")
{
o.focus();
}
}
</script>
</head>

<body onload="focusElementById('search');">
...
</body>

More feature-testing might be indicated. One might also want to employ
exception handling (try...catch) in case there are further conditions that
have to be met in order for the element to receive the focus which cannot be
tested for.


PointedEars
 
A

AKS

The logical course of action should be clear then:


"should be clear"? Not absolutely. What do you check here:
if (o && isMethod(o, "focus")
&& typeof o.style == "undefined"
|| typeof o.style.visibility != "undefined")

?
To avoid an error, it should look like this:

if (o && isMethod(o, "focus") &&
typeof o.style != "undefined" &&
typeof o.style.visibility != "hidden")

But in IE it is still dangerous. Because style can be specified in css
or can be inherited from the parent (hidden) element. Then your check
is useless.

One might also want to employ exception handling (try...catch)...

And one might (who don't care about IE older 5.5) also want to employ
this safety method:

o.setActive();
 
A

AKS

if (o && isMethod(o, "focus") &&
typeof o.style != "undefined" &&
typeof o.style.visibility != "hidden")

if (o && isMethod(o, "focus") &&
typeof o.style != "undefined" &&
o.style.visibility != "hidden")
 
A

AKS

Error: document.getElementById("that").setActive is not a function

It's for IE only (other browsers do not throw an error).

(o.setActive || o.focus)(); // in short

Still, not a lot of sense in making an element "active" if it is hidden.

You never know in what environment the script will work. I've noticed
IE feature and no more .
 
A

AKS

It won't? The error message I posted was a direct copy/paste from Firefox.

I wrote about an error which IE throws when you try to call focus() on
hidden element.
Why though? Just use focus...
IE will setActive() on a hidden input (type="hidden"). It will throw an
error if you try to set focus() to it.

I know (see my very first post).
 
A

AKS

The simplest solution to that is in my reply to Thomas. Test the .type
property and if it is not type="hidden" then set focus.

You haven't looked at my first post.
OK! Let's try your "simplest solution: test the .type property and if
it is not type="hidden" then set focus":

<script type='text/javascript'>

function F() {
var o = document.getElementById('search');
if (o && o.type != 'hidden') {
o.focus();
};
};

</script>

<body onload='F()'>

<input type='text' id='search' style='visibility:hidden'>

</body>

What will happen in IE?
 
A

AKS

Personally, I think the entire discussion is nothing more than a mental
exercise. The simplest solution is the one Bart gave. If it throws an
error then the programmer needs to know it *then*, not let it be hidden
in a function somewhere.

Something, like this, can be more reliable (with hope that there are
no users of IE 5.0 and earlier):

function F() {
var o = document.getElementById('search');
if (o) {
if (o.setActive) {
o.setActive();
} else if (o.focus) {
o.focus();
};
};
};

But may be I'll choose select() method instead of two setActive/focus
(I wrote *may be*)...
 
T

Thomas 'PointedEars' Lahn

AKS said:
"should be clear"? Not absolutely. What do you check here:


?

The element object must have a focus() method. If it has, then either it
does not support a `style' object or if it does, it has to support the
`visibility' property.
To avoid an error, it should look like this:

if (o && isMethod(o, "focus") &&
typeof o.style != "undefined" &&
typeof o.style.visibility != "hidden")

I took into account that the element may be focused if there was no CSS
scripting support (with the assumption that then there was no CSS support
and the element could not be hidden), while your "correction" would not
allow the element to receive focus then.
But in IE it is still dangerous. Because style can be specified in css

It would already "be specified in css" in the `style' attribute value of the
element. You mean instead "specified in a document-global or linked
stylesheet".
or can be inherited from the parent (hidden) element.
Then your check is useless.

True. However, that occasion is something that can be tested for as well.
Quick hack:

function _getComputedStyle(o, p)
{
var s;

if (typeof document.defaultView != "undefined"
&& isMethod(document.defaultView, "getComputedStyle")
&& (s = document.defaultView.getComputedStyle(o, null))
&& isMethod(s, "getPropertyValue"))
{
return s.getPropertyValue(p);
}
else if (typeof o.currentStyle != "undefined"
&& typeof o.currentStyle[p] != "undefined")
{
return o.currentStyle[p];
}

return s;
}

function isHidden(o)
{
while (o)
{
if (typeof o.style == "undefined"
|| typeof o.style.visibility != "undefined"
&& /hidden/i.test(o.style.visibility)
|| /hidden/i.test(_getComputedStyle(o, "visibility"))
{
return true;
}

o = o.parentNode;
}

return false;
}

function focusElement(s)
{
var o = document.getElementById(s), s;
if (o && isMethod(o, "focus") && !isHidden(o))
{
o.focus();
}
}

Nevertheless, when observing this much of (feature) testing for one simple
call, this is one of the occasions where I wish that there was a universally
supported and easily scriptable DOM interface -- or at least that exception
handling was universally supported, for

try
{
o.focus();
}
catch (e)
{
}

is simply much more beautiful than the above, while the former might not
even suffice (consider `disabled').
And one might (who don't care about IE older 5.5) also want to employ
this safety method:

o.setActive();

I don't see why that would qualify as a "safety method". It does a
completely different thing:

| setActive Method
|
| Sets the object as active without setting focus to the object.


PointedEars
 
A

AKS

I don't see why that would qualify as a "safety method". It does a
completely different thing:

| setActive Method
|
| Sets the object as active without setting focus to the object.

Ok, good quote. But let's get back into the real world.
Test this (only in IE, of course):

<script type='text/javascript'>

function F() {
var o = document.getElementById('search');
if (o && (o = o.setActive)) {
o();
};
};

</script>

<body onload='F()'>

<input type='text' id='search' onfocus='window.status =
event.type'>

</body>
 
D

David Mark

"should be clear"? Not absolutely. What do you check here:

It is clear as mud to me.
?
To avoid an error, it should look like this:

if (o && isMethod(o, "focus") &&
        typeof o.style != "undefined" &&
        typeof o.style.visibility != "hidden")

This isn't right either. But any further sliding down this slope is a
waste of time. There is no way to reliably detect when an element can
be focused, so an application shouldn't rely on such a test.
But in IE it is still dangerous. Because style can be specified in css
or can be inherited from the parent (hidden) element. Then your check
is useless.


And one might (who don't care about IE older 5.5) also want to employ
this safety method:

o.setActive();

That does something else.
 
D

David Mark

The element object must have a focus() method.  If it has, then either it
does not support a `style' object or if it does, it has to support the
`visibility' property.



I took into account that the element may be focused if there was no CSS
scripting support (with the assumption that then there was no CSS support

That is a bad assumption. For instance, it is well known that some
CSS-enabled agents do not allow certain style properties to be updated
with script (display being the most common.) Testing whether these
properties are strings is a good indication as to whether scripted
updates will have any effect. These tests do not exclude the
possibility of the rules being applied with style sheets.
and the element could not be hidden), while your "correction" would not
allow the element to receive focus then.


It would already "be specified in css" in the `style' attribute value of the
element.  You mean instead "specified in a document-global or linked
stylesheet".

That isn't true for visibility rules (though it is for display.)
True.  However, that occasion is something that can be tested for as well.

No, it is false in this case.
Quick hack:

Not one of those.
  function _getComputedStyle(o, p)
  {
    var s;

    if (typeof document.defaultView != "undefined"
        && isMethod(document.defaultView, "getComputedStyle")
        && (s = document.defaultView.getComputedStyle(o, null))
        && isMethod(s, "getPropertyValue"))
    {
      return s.getPropertyValue(p);
    }
    else if (typeof o.currentStyle != "undefined"
             && typeof o.currentStyle[p] != "undefined")
    {
      return o.currentStyle[p];
    }

    return s;
  }

Mixing cascaded and computed styles is an error-prone approach. This
wouldn't work for display rules.
  function isHidden(o)
  {
    while (o)
    {
      if (typeof o.style == "undefined"
          || typeof o.style.visibility != "undefined"
          && /hidden/i.test(o.style.visibility)
          || /hidden/i.test(_getComputedStyle(o, "visibility"))

This will error if _getComputedStyle returns an undefined result.
      {
        return true;
      }

      o = o.parentNode;

This is wrong. If the computed, cascaded or inline style is visible,
then there is no reason to check the parent node(s). As mentioned,
display rules are a different story. So this function is worthless
for what is designed to do.
    }

    return false;
  }

  function focusElement(s)
  {
    var o = document.getElementById(s), s;
    if (o && isMethod(o, "focus") && !isHidden(o))
    {
      o.focus();
    }
  }

Nevertheless, when observing this much of (feature) testing for one simple
call, this is one of the occasions where I wish that there was a universally
supported and easily scriptable DOM interface -- or at least that exception
handling was universally supported, for

  try
  {
    o.focus();
  }
  catch (e)
  {
  }

If an application doesn't know when it is safe to focus an element,
then it can lean on this crutch. Other than the remote possibility of
an !important user style hiding an element, this issue shouldn't come
up.
is simply much more beautiful than the above, while the former might not
even suffice (consider `disabled').

It won't even come close. And hopefully nobody will post an addendum
that tests for disabled elements as there is no way to do that
reliably either.
 
D

David Mark

What exactly? And what's the difference? Did you test code snippet
from my previous post?

According to the quote from Microsoft, it doesn't focus the element.
Even if for some unforeseen reason it does, that behavior should not
be relied upon. If it is a bug, a future Windows update could fix it.

Regardless, for reasons previously mentioned, this whole thread is a
waste of time.
 
I

ibizara

Bart Van der Donck
<body onLoad="if (document.getElementById('search'))
document.getElementById('search').focus();">

Perfect and as this is for a local intranet everyone has IE7 so many
thanks works great :)

Thanks to all other replies :D
 
T

Thomas 'PointedEars' Lahn

ibizara said:
Bart Van der Donck [wrote:]
<body onLoad="if (document.getElementById('search'))
document.getElementById('search').focus();">

Perfect and as this is for a local intranet everyone has IE7 so many
thanks works great :)

Nevertheless, it is needlessly inefficient (and error-prone). Consider this
more efficient and slightly less error-prone solution:

<body onLoad="var o = document.getElementById('search');
if (o && o.focus) o.focus();">

Consider more feature-testing for an even less error-prone solution. YOu
should also consider that now everyone there may be using IE 7 but that will
change in the future. As a responsible developer you should be prepared for
that event as much as you can so that little to no further development costs
will have to be invested then. Implementing feature tests helps a great
deal in achieving that.
Thanks to all other replies :D

You're welcome.


PointedEars
 
D

David Mark

Thomas 'PointedEars' Lahn said the following on 12/23/2007 5:29 PM:
ibizara said:
Bart Van der Donck [wrote:]
<body onLoad="if (document.getElementById('search'))
document.getElementById('search').focus();">
Perfect and as this is for a local intranet everyone has IE7 so many
thanks works great :)
Nevertheless, it is needlessly inefficient (and error-prone).  Consider this
more efficient and slightly less error-prone solution:
  <body onLoad="var o = document.getElementById('search');
                if (o && o.focus) o.focus();">

Hmm. A "solution" that is still highly error-prone. Maybe you should
Google this thread and read it - in its entirety - to find out why it is
not as "simple" as you portray it to be. Just because an element has a
"focus" property doesn't mean you can set focus to it.

No, but it is something that cannot be stipulated by the developer
(unlike the initial visibility, display and disabled states.) I am
surprised to see "PointedEars" testing a method by boolean type
conversion though. We've been over that.
A *lot* more feature-testing. Especially in IE.

Which (as I think you previously mentioned) would be a complete waste
of time (unless you are trying to defend against user style sheets.)
And IIRC, IE doesn't support user style sheets.
As it is, I can post code that will "break" even your "quick-hack" in at
least 4 different ways. Two of which I have already posted.

The less said about that "quick-hack" the better. The usual
translation for that is "bad-code."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top