David Mark's Javascript Tip Du Jour - Volume #1 - Tip #1234 - How toMeasure Element Dimensions

H

Hans-Georg Michna

<scr("|')\+("|')ipt lang:javascript

- of which a representative example (from an old dojo version, and
re-wrapped for posting) is:-

document.write(
"<scr"+"ipt type='text/javascript' src='"+tmps[x]+"'></scr"+"ipt>"
);

Thanks again! Nice examples.

Hans-Georg
 
H

Hans-Georg Michna

On 12/11/11 7:38 PM, Hans-Georg Michna wrote:
[...]
Anyway, do you have more examples? These would be good demos of
the general ignorance towards correct JavaScript programming.
Good for demos.
One that is specific to jQuery is the use, usually within a listener, of
the expression:

$(this).val()

Searching at Google code search with:

\$\(this\)\.val\(\) lang:javascript

returns over 5,000 hits.

Please help my vague memories of jQuery. What is it that .val()
does? Or do you mean that the $(...) is simply superfluous?

Hans-Georg
 
J

J.R.

J.R. said:
Thomas said:
J.R. wrote:
On 10/11/2011 12:09, David Mark wrote:
if (document.documentElement&& typeof
document.documentElement.clientWidth == 'number') {
var getInnerDimensions = function(el) {
return [el.clientHeight, el.clientWidth];
};
}

Considering an element having scrollbars, we might use:

return [el.scrollTop + el.clientHeight,
el.scrollLeft + el.clientWidth];

Please explain what the scroll position has to do with the element
dimensions.

[…]
A better approach would be using scrollWidth and scrollHeight, but these
properties are "buggy" in IE and Opera, according to
<http://www.quirksmode.org/dom/w3c_cssom.html#elementview>. The irony
here is that scrollWidth and scrollHeight were introduced by Microsoft
in their MSIE's DHTML object model...

Therefore, if we want a "getInnerDimensions" function to return the
correct dimensions for the element's content we will need to add the
scrollTop and scrollLeft values to the clientHeight and clientWidth
values respectively, otherwise we would not get the correct inner
dimensions if the element is scrolled all the way down or to the right.

But what if the element doesn't have scrollbars? No problem, because
scrollTop and scrollLeft will return zero.

And if I scroll down or right a scrollable element its content becomes
higher/wider?

No, but you can't retrieve the width / height of a scrollable element's
content with just clientHeight and clientWidth properties.

It is better to be aware of it and use *sensible* workarounds if necessary.
This is actually one case where property inference (window.opera) is useful
and acceptable; IE should be dealt with using Conditional Comments instead.

ACK.
 
R

RobG

[...]
Anyway, do you have more examples? These would be good demos of
the general ignorance towards correct JavaScript programming.
Good for demos.
One that is specific to jQuery is the use, usually within a listener, of
the expression:
  $(this).val()
Searching at Google code search with:
  \$\(this\)\.val\(\) lang:javascript
returns over 5,000 hits.

Please help my vague memories of jQuery. What is it that .val()
does? Or do you mean that the $(...) is simply superfluous?

It can be replaced with the very much faster (and less to type):

this.value;

$(this) "wraps" the target in a jQuery object (quite expensive in
performance terms).

The val() method does some fixing of issues with select elements and
option values, but they are well known and can be dealt with in the
markup.
 
T

Thomas 'PointedEars' Lahn

J.R. said:
Thomas said:
J.R. said:
Thomas 'PointedEars' Lahn wrote:
J.R. wrote:
On 10/11/2011 12:09, David Mark wrote:
if (document.documentElement&& typeof
document.documentElement.clientWidth == 'number') {
var getInnerDimensions = function(el) {
return [el.clientHeight, el.clientWidth];
};
}

Considering an element having scrollbars, we might use:

return [el.scrollTop + el.clientHeight,
el.scrollLeft + el.clientWidth];

Please explain what the scroll position has to do with the element
dimensions.

[…]
A better approach would be using scrollWidth and scrollHeight, but these
properties are "buggy" in IE and Opera, according to
<http://www.quirksmode.org/dom/w3c_cssom.html#elementview>. The irony
here is that scrollWidth and scrollHeight were introduced by Microsoft
in their MSIE's DHTML object model...

Therefore, if we want a "getInnerDimensions" function to return the
correct dimensions for the element's content we will need to add the
scrollTop and scrollLeft values to the clientHeight and clientWidth
values respectively, otherwise we would not get the correct inner
dimensions if the element is scrolled all the way down or to the right.

But what if the element doesn't have scrollbars? No problem, because
scrollTop and scrollLeft will return zero.

And if I scroll down or right a scrollable element its content becomes
higher/wider?

No, but you can't retrieve the width / height of a scrollable element's
content with just clientHeight and clientWidth properties.

(Apparently I have to be blunt.) Difficulties with using scrollWidth and
scrollHeight /notwithstanding/:

Your approach is *junk*. Because *again*, the *content* of the element
(scrollWidth/scrollHeight) does _not_ become wider or higher when I scroll
it right or down, so you MUST NOT add scrollTop or scrollLeft:

Not scrolled

scrollLeft
->.<-
 
T

Tim Down

On 12/11/11 7:38 PM, Hans-Georg Michna wrote:
[...]
Anyway, do you have more examples? These would be good demos of
the general ignorance towards correct JavaScript programming.
Good for demos.
One that is specific to jQuery is the use, usually within a listener, of
the expression:
  $(this).val()
Searching at Google code search with:
  \$\(this\)\.val\(\) lang:javascript
returns over 5,000 hits.
Please help my vague memories of jQuery. What is it that .val()
does? Or do you mean that the $(...) is simply superfluous?

It can be replaced with the very much faster (and less to type):

    this.value;

$(this) "wraps" the target in a jQuery object (quite expensive in
performance terms).

The val() method does some fixing of issues with select elements and
option values, but they are well known and can be dealt with in the
markup.

It also messes around with new lines and strips out CR carriage return
characters in the value in attempt to normalize browser behaviour.
However, this seems less than helpful to me: I can see no practical
advantage to it and it causes properties such as selectionStart and
selectionEnd to be unreliable as character indexes within a value
returned by val().

Tim
 
J

J.R.

J.R. said:
Thomas said:
J.R. wrote:
Thomas 'PointedEars' Lahn wrote:
J.R. wrote:
On 10/11/2011 12:09, David Mark wrote:
if (document.documentElement&& typeof
document.documentElement.clientWidth == 'number') {
var getInnerDimensions = function(el) {
return [el.clientHeight, el.clientWidth];
};
}

Considering an element having scrollbars, we might use:

return [el.scrollTop + el.clientHeight,
el.scrollLeft + el.clientWidth];

Please explain what the scroll position has to do with the element
dimensions.

[…]
A better approach would be using scrollWidth and scrollHeight, but these
properties are "buggy" in IE and Opera, according to
<http://www.quirksmode.org/dom/w3c_cssom.html#elementview>. The irony
here is that scrollWidth and scrollHeight were introduced by Microsoft
in their MSIE's DHTML object model...

Therefore, if we want a "getInnerDimensions" function to return the
correct dimensions for the element's content we will need to add the
scrollTop and scrollLeft values to the clientHeight and clientWidth
values respectively, otherwise we would not get the correct inner
dimensions if the element is scrolled all the way down or to the right.

But what if the element doesn't have scrollbars? No problem, because
scrollTop and scrollLeft will return zero.

And if I scroll down or right a scrollable element its content becomes
higher/wider?

No, but you can't retrieve the width / height of a scrollable element's
content with just clientHeight and clientWidth properties.

(Apparently I have to be blunt.) Difficulties with using scrollWidth and
scrollHeight /notwithstanding/:

Your approach is *junk*. Because *again*, the *content* of the element
(scrollWidth/scrollHeight) does _not_ become wider or higher when I scroll
it right or down, so you MUST NOT add scrollTop or scrollLeft:

Not scrolled

scrollLeft
->.<-
.
. scrollWidth
.<------------------>.
. .
. clientWidth .
.<----------->. . |
. . . v
,---------------.- --.- - - - - - - - - - scrollTop
| |^| : ^ ^
| |#| : | clientHeight |
| | | : v |
|_____________|v| _ _:_ _ | scrollHeight
|<#>| | : |
:---------------' : |
: : |
: : v
'-- -- -- -- -- -- --'- - - - - - - - - -

Scrolled right and down

scrollLeft
->. .<-
. .
.-- -- -- -- -- -- --.- - - - - - - - - - - - --
: . : ^ ^
: . : | scrollTop |
: . : v |
: ,---------------.- - - - | scrollHeight
: | |^| ^ |
: | | | | clientHeight |
: | |#| v v
:__ __ |_____________|v|_ _ _ _ _ _ _ _ _ _ _ __
' |< #>| |
' '---------------'
' ' '
' ' '
' ' '
' '<----------->'
' clientWidth '
' '
'<------------------>'
scrollWidth


See also:<http://msdn.microsoft.com/en-us/library/ms530302(VS.85).aspx>

You really don't seem to understand that a part of the content of a
scrollable element may be hidden because it's wider and/or taller than
the element's box. And that invisible part of the content cannot be
measured with just element.clientHeight and element.clientWidth
properties. If you want to get the element's content dimensions (not the
box dimensions), you MUST USE (el.scrollTop + el.clientHeight) and
(el.scrollLeft + el.clientWidth).
 
T

Thomas 'PointedEars' Lahn

J.R. said:
J.R. said:
Thomas 'PointedEars' Lahn wrote:
J.R. wrote:
Thomas 'PointedEars' Lahn wrote:
J.R. wrote:
On 10/11/2011 12:09, David Mark wrote:
if (document.documentElement&& typeof
document.documentElement.clientWidth == 'number') {
var getInnerDimensions = function(el) {
return [el.clientHeight, el.clientWidth];
};
}

Considering an element having scrollbars, we might use:

return [el.scrollTop + el.clientHeight,
el.scrollLeft + el.clientWidth];

Please explain what the scroll position has to do with the element
dimensions.
[…]
Your approach is *junk*. Because *again*, the *content* of the element
(scrollWidth/scrollHeight) does _not_ become wider or higher when I
scroll it right or down, so you MUST NOT add scrollTop or scrollLeft:

[ASCII-Art: Element measures without and scrolling]

See also:<http://msdn.microsoft.com/en-us/library/ms530302(VS.85).aspx>

You really don't seem to understand that a part of the content of a
scrollable element may be hidden because it's wider and/or taller than
the element's box.

No, *I* really do. And −1 for full-quoting and still failing to understand
what took me quite some time to get painted right:

scrollWidth != clientWidth + scrollLeft
scrollHeight != clientHeight + scrollTop
And that invisible part of the content cannot be
measured with just element.clientHeight and element.clientWidth
properties. If you want to get the element's content dimensions (not the
box dimensions), you MUST USE (el.scrollTop + el.clientHeight) and
(el.scrollLeft + el.clientWidth).

No, you MUST NOT use that because *inner dimensions* (i. e., that of the
element's *content*) computed this way will vary depending on the element's
scroll position, which is not measuring the inner dimensions *at all*.


Score adjusted

PointedEars
 
T

Thomas 'PointedEars' Lahn

J.R. said:
J.R. said:
Thomas 'PointedEars' Lahn wrote:
J.R. wrote:
Thomas 'PointedEars' Lahn wrote:
J.R. wrote:
On 10/11/2011 12:09, David Mark wrote:
if (document.documentElement&& typeof
document.documentElement.clientWidth == 'number') {
var getInnerDimensions = function(el) {
return [el.clientHeight, el.clientWidth];
};
}

Considering an element having scrollbars, we might use:

return [el.scrollTop + el.clientHeight,
el.scrollLeft + el.clientWidth];

Please explain what the scroll position has to do with the element
dimensions.
[…]
Your approach is *junk*. Because *again*, the *content* of the element
(scrollWidth/scrollHeight) does _not_ become wider or higher when I
scroll it right or down, so you MUST NOT add scrollTop or scrollLeft:

[ASCII-Art: Element measures without and with scrolling]

See also:<http://msdn.microsoft.com/en-us/library/ms530302(VS.85).aspx>

You really don't seem to understand that a part of the content of a
scrollable element may be hidden because it's wider and/or taller than
the element's box.

No, *I* really do. And −1 for full-quoting and still failing to understand
what took me quite some time to get painted right:

scrollWidth != clientWidth + scrollLeft
scrollHeight != clientHeight + scrollTop
And that invisible part of the content cannot be
measured with just element.clientHeight and element.clientWidth
properties. If you want to get the element's content dimensions (not the
box dimensions), you MUST USE (el.scrollTop + el.clientHeight) and
(el.scrollLeft + el.clientWidth).

No, you MUST NOT use that because *inner dimensions* (i. e., that of the
element's *content*) computed this way will vary depending on the element's
scroll position, which is not measuring the inner dimensions *at all*.


Score adjusted

PointedEars
 
H

Hans-Georg Michna

It can be replaced with the very much faster (and less to type):

this.value;

$(this) "wraps" the target in a jQuery object (quite expensive in
performance terms).

The val() method does some fixing of issues with select elements and
option values, but they are well known and can be dealt with in the
markup.

Thanks! Another interesting example.

Hans-Georg
 
R

RobG

38 PM, Hans-Georg Michna wrote:
[...]
Anyway, do you have more examples? These would be good demos of
the general ignorance towards correct JavaScript programming.
Good for demos.
One that is specific to jQuery is the use, usually within a listener, of
the expression:
$(this).val()
Searching at Google code search with:
\$\(this\)\.val\(\) lang:javascript
returns over 5,000 hits.
Please help my vague memories of jQuery. What is it that .val()
does? Or do you mean that the $(...) is simply superfluous?
It can be replaced with the very much faster (and less to type):

$(this) "wraps" the target in a jQuery object (quite expensive in
performance terms).
The val() method does some fixing of issues with select elements and
option values, but they are well known and can be dealt with in the
markup.

It also messes around with new lines and strips out CR carriage return
characters in the value in attempt to normalize browser behaviour.
However, this seems less than helpful to me: I can see no practical
advantage to it and it causes properties such as selectionStart and
selectionEnd to be unreliable as character indexes within a value
returned by val().

Looking at the documentation for .val[1] (which is included under
"attributes"), the example uses $(this).val(), adding weight to its
categorisation as "cargo cult programming".

The documentation also says that .val returns "String, Number, Array",
which suggests that it returns String, Number or Array objects. It
will return an array in only one case: the values of a multiple
select. Allowing for sloppy documentation and that they really meant
that it might also return string or number primitives, I can't see any
case where it should return a number.

1. <URL: http://api.jquery.com/val/ >
 
E

Eric Bednarz

Thomas 'PointedEars' Lahn said:
This is actually one case where property inference (window.opera) is useful
and acceptable; […]

var opera = 'Der Ring des Nibelungen';

On the other hand, Opera has a proper way of dealing with
(version-)detection (unless the opera object is shadowed, and I’d rather
have a false negative than a false positive; but surely YMWD), e.g.:

var OPERA = (function (global) {
var dom_window = global.window,
opera,
version,
subversion,
build;
if ('object' == typeof dom_window.opera) {
opera = dom_window.opera;
// the version method was introduced in Opera 8
if (('function' == typeof opera.version) &&
('function' == typeof opera.buildNumber)
) {
version = opera.version();
subversion = version.split('.');
// The return value of the version method has
// three parts up to Opera 9.27 (including the
// build number) and two since 9.50
version = [subversion[0], subversion[1]].join('.');
build = opera.buildNumber();
return {
major: +subversion[0],
minor: +subversion[1],
build: +build,
number: +version,
string: [version, build].join('.')
};
}
}
return null;
}(this));

In this group it is probably not safe not to say the obvious, practical
applications would be less verbose and have a more practical return
value. :)
 
T

Thomas 'PointedEars' Lahn

Eric said:
Thomas 'PointedEars' Lahn said:
This is actually one case where property inference (window.opera) is
useful and acceptable; […]

var opera = 'Der Ring des Nibelungen';

Don't be ridiculous. Oh wait, it's you.
On the other hand, Opera has a proper way of dealing with
(version-)detection (unless the opera object is shadowed, and I’d rather
have a false negative than a false positive; but surely YMWD), e.g.:

var OPERA = (function (global) {
var dom_window = global.window,
AISB.

opera,
version,
subversion,
build;
if ('object' == typeof dom_window.opera) {

You have overlooked the case of dom_window.opera === null. Also, it is a
host object, so all bets (other than it would have to be a true-value to be
useful) are off.
opera = dom_window.opera;
// the version method was introduced in Opera 8
if (('function' == typeof opera.version) &&
('function' == typeof opera.buildNumber)

You have overlooked the case where a host object's method would not yield
`function', which might be the case with Opera's DOM implementation.


PointedEars
 
E

Eric Bednarz

Thomas 'PointedEars' Lahn said:
Eric said:
Thomas 'PointedEars' Lahn said:
This is actually one case where property inference (window.opera) is
useful and acceptable; […]

var opera = 'Der Ring des Nibelungen';

Don't be ridiculous.

That reminds me. You know what Wagner said after deciding to write his
magnus opus around Wotan’s world dominance plot instead of yours?

“Score adjusted.â€
Oh wait, it's you.

Says the one who is constantly beating reality with a big hammer until
it fits into his views.
You have overlooked the case of dom_window.opera === null.

That’s a fair point.
Also, it is a
host object, so all bets (other than it would have to be a true-value to be
useful) are off.

Cases where it isn’t Opera’s host object are not really interesting.
You have overlooked the case where a host object's method would not yield
`function', which might be the case with Opera's DOM implementation.

See above. The only thing I have overlooked is the case where it is
pointless to reply.
 
E

Eric Bednarz

Richard Cornford said:
Eric said:
Richard said:
document.write(
"<scr"+"ipt type='text/javascript' src='"+tmps[x]+"'></scr"+"ipt>"
);

The cargo-cult programming structure is the first (left-most)
string concatenation operation. The final (right-most) string
concatenation operation has some justification in some contexts.
Its use in those contexts demonstrates a shallow understanding
of the reasons for its use (as there are more efficient, shorter
and more formally correct alternatives), and it was almost
certainly that shallow understanding that inspired the real
cargo-cult structure to the left. However, One context where
the final (right-most) concatenation is purposeless is when it
is found in an imported JS file, which is of course where
Google's code search is finding it. So that too is pushing
cargo-cult programming in the contexts where it is being found
above.

I’m getting the impression that you think that the purpose of
splitting and concatenating the generic identifier is somehow
related to escaping the ETAGO delimiter (‘</’),

"Somehow related" seems applicable.

Well, I don’t understand what you mean by “some justification in some
contextsâ€. In the context of a CDATA content model it doesn’t make any
sense at all because CDATA ends with ETAGO foolowed by a name start
character. So that habit wouldn’t have made it valid HTML (4) either.
In a cause and effect relationship I would expect the cause to
pre-date the effect. This concatenation 'trick' was common when I
started working with javascript in 2001.

Well, I’m unlikely to ever catch up with that head start. :)

References I’ve seen connecting this practice with NIS were from around
2004 to 2006, as far as I can remember.
The odds are that it
pre-dates Norton 'internet security'

But why? Were there *practical* problems that are not related to
validation?
and my observations of Norton's
inserted scripts have been that it has been varying over time.

That’s inherent with cat and mouse games. For a while it seems to have
been possible to prevent NIS from modifying the first script element in
the HTML source by preceding it with an HTML comment containing script
markup (this kind of thing is pretty hard to verify now, but it sounds
plausible; ad-hoc parsing is usually broken and gets fixed feature by
feature later).
I also don't think that the mindset where people are scripting only
for the default configurations of the most recent versions of 4 or 5
known browsers will tend to leave then thinking about the possible
actions of 'security' proxies (or being willing to take action to
accommodate them if they did).

It doesn’t create much overhead, and might have been a best practice
that is so good that nobody checks what it is for ;-)

On the other hand, it’s really not easy to know which cargo cult bits
are redundant or not, and why. Somewhere around 2007 I removed HTML
comments out of script elements in the course of a redesign of a
website. I got kicked royally for that because the client had some
really crappy HTML to PDF conversion software that included the script
content after that.
In any event, HTML mark-up modification is still not relevant to the
contents of an imported javascript.

But it is supposed to have been *only* about external script, the
premise being that NIS was looking for the first occurance of something
that looks like a start tag of a script element, which isn’t a problem
in a HTML context.
 
F

Frobernik

On 11-11-10 12:47 PM, Ant wrote:
"HTML 5 Boilerplate" is a massive set of server
configurations, CSS file(s) ("normalizing", they call it),
JavaScript files (including jQuery & modernizr, neither of which
have any particular use to me), and other assorted bits.

"normalizing" is just a set of resets in the real world made for so
called "web apps" - because nothing says futuristic like a splash screen
or a spinning dial
The biggest blow is marketing. Take a gander at
"HTML 5 Boilerplate"'s website (won't link). It's chock full of
over-the-top marketing speak. The first time I read it, I was
heavily offended by the textual content. I seriously pondered
if it was written by a prepubescent.

Well there are people (apart from the punters on here) fighting
modernizer, jQuery and other junk (will link)

http://nefariousdesigns.co.uk/archive/2011/05/sniff-my-browser-the-modernizr-inadequacy/

Frobernik
 
D

David Mark

In comp.lang.javascript message <bd12b66f-33f5-43d2-8e22-6f81b42c3d8b@n1
4g2000vbn.googlegroups.com>, Thu, 10 Nov 2011 06:09:29, David Mark
How to Measure Element Dimensions

It could be useful if there were, linked from within each posted Tip, a
Web Index of Tips, linking to Web copies.

One Tip might be the answer to "I have an on-screen element, of known
size, with an on[dbl]click method; how do I obtain the co-ordinates of a
[double-]click with respect to a given position in the element itself?"

The aforementioned index page could have a feedback form, partly for
suggesting topics for tips and possible answers.  The latter, when
imperfect, would provide fodder for further Tips, of course.

I suppose.

In what appears to be the cinsoft home page, "By" should be "To".

Huh?


Consider a page, <http://www.cinsoft.net/position.html>, which has been
found by a serendipitous Google search for "starting point for a move
animation" or otherwise.  It recommends
        o = getElementPositionStyles(el);
- and that does not work

It's necessary to have the included script.


 The necessary further information is not
clearly provided; indeed, the page seems to have no <a href="...">Home
Page</a>.


Wrong. It's the logo and likely has alt text. Leads to library page.
Site untouched for years; primers not even part of main site or
library. Just a dumping ground for examples that came up here.




Thanks! Buy the book when it comes out. No UK release date yet.
 
D

David Mark

if (document.documentElement&&  typeof
document.documentElement.clientWidth == 'number') {
   var getInnerDimensions = function(el) {
     return [el.clientHeight, el.clientWidth];
   };
}

Considering an element having scrollbars, we might use:

   return [el.scrollTop + el.clientHeight,
           el.scrollLeft + el.clientWidth];


I don't follow. Use for what?
Note: scrollWidth/scrollHeight are buggy in IE6-8 and Opera 10. So, we'd
need to compare (scrollTop + clientHeight) to scrollHeight too. In IE8,
scrollWidth is 5 pixels off. See
<http://www.quirksmode.org/dom/w3c_cssom.html>

Not buggy, at least not in contexts I use. Who uses scrollWidth? And
thanks, but I am not interested PPK's notes on subject. Usually vague
and/or confused.
 
D

David Mark

J.R. wrote:
On 10/11/2011 12:09, David Mark wrote:
if (document.documentElement&&   typeof
document.documentElement.clientWidth == 'number') {
    var getInnerDimensions = function(el) {
      return [el.clientHeight, el.clientWidth];
    };
}
Considering an element having scrollbars, we might use:
    return [el.scrollTop + el.clientHeight,
            el.scrollLeft + el.clientWidth];
Please explain what the scroll position has to do with the element
dimensions.

The clientWidth and clientHeight properties return the width and height
of the content field, excluding borders and *scrollbars* (when visible),
but including padding. If the element's content overflows then the
browser might show scrollbars depending on the overflow CSS property. In
the latter case, clientWidth and clientHeight won't retrieve the
measurement of the hidden parts of the element's content.


No problem there; overflowed content not supposed to count.
A better approach would be using scrollWidth and scrollHeight, but these
properties are "buggy" in IE and Opera, according to
<http://www.quirksmode.org/dom/w3c_cssom.html#elementview>.

No. That's getScrollDimensions. And may well be susceptible to quirks
in some cases. Particularly the HTML element.

The irony
here is that scrollWidth and scrollHeight were introduced by Microsoft
in their MSIE's DHTML object model...

As were others. IE 4.
 
D

David Mark

On 12/11/11 7:38 PM, Hans-Georg Michna wrote:
[...]
Anyway, do you have more examples? These would be good demos of
the general ignorance towards correctJavaScriptprogramming.
Good for demos.
One that is specific tojQueryis the use, usually within a listener, of
the expression:
  $(this).val()
Searching atGooglecode search with:
  \$\(this\)\.val\(\) lang:javascript
returns over 5,000 hits.
Please help my vague memories ofjQuery. What is it that .val()
does? Or do you mean that the $(...) is simply superfluous?

It can be replaced with the very much faster (and less to type):

    this.value;

Well, not necessarily. A better (or worse, depending on view) example
of this cargo cult pattern would be:

$(this).attr('id');

Now, anything like that is clearly BS on many levels: performance,
reliability, etc. It's a major misunderstanding.
$(this) "wraps" the target in ajQueryobject (quite expensive in
performance terms).

Absolutely. But, in this case, the (rather unfortunately named) "val"
method may be useful. It's just unfortunate how jQuery works (create
a huge object, discard same), turning every line into an epic snarl of
function calls, created objects, etc.

But if there are more than text inputs (or selects in very specific
contexts) involved, a "getInputValue" function of some sort is in
order. God knows, I wouldn't trust jQuery's rendition.


This is indeed one viable rendition:-

function getInputValue(el) {
return el.value;
}

But you have to know when it is appropriate. The renditions get
larger as you accommodate checkboxes, radio buttons, etc. as typically
this type of function is interested in the value that will be
submitted to the server (if any). And, as mentioned, unless you set
down strict rules for selects, you can't use the above with them
either.
The val() method does some fixing of issues with select elements and
option values, but they are well known and can be dealt with in the
markup.

Right. I suppose it tries; but wouldn't even waste the time reading
the code. I imagine it accounts for unchecked inputs and returns
array of strings for multi select as well. Pretty standard stuff that
hasn't changed... ever. Unlikely jQuery has put some must-have new
spin on form control serialization. I did see where somebody said the
docs state their "val" function may return a number. That I did not
expect. :)
 

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
474,073
Messages
2,570,539
Members
47,197
Latest member
NDTShavonn

Latest Threads

Top