Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Attach event/function to links within span tag

Reply
Thread Tools

Attach event/function to links within span tag

 
 
johkar
Guest
Posts: n/a
 
      01-20-2006
I need to cancel the link and execute a function onclick of all the
links within the span tag which has a class of "container" assigned.
There will be only one span tag with this class applied.

I know you can get a specific tag using
document.getElementsByTagName('span')[0], but I am unsure how to get
the one with the class="container". I know there is a getAttribute
method, just need a pointer or two to put it all together. Once I know
how to access the specific links I want do the equivelant of <a
href="hello.do?contain=yes" onclick="someFunction(this);return
false">Hello</a>. I am thinking I can add a global function or
setAttributes. Ideas?

<span class="container">
<a href="hello.do?contain=yes">Hello</a>
<span class="container"><a
href="goodbye.do?contain=yes">Goodbye</a>
</span>

Thanks,

John

 
Reply With Quote
 
 
 
 
RobG
Guest
Posts: n/a
 
      01-20-2006
johkar wrote:
> I need to cancel the link and execute a function onclick of all the
> links within the span tag which has a class of "container" assigned.
> There will be only one span tag with this class applied.


Your example below has two. I'll guess that you didn't mean to add the
container class to the nested span.


> I know you can get a specific tag using
> document.getElementsByTagName('span')[0], but I am unsure how to get
> the one with the class="container". I know there is a getAttribute
> method, just need a pointer or two to put it all together. Once I know
> how to access the specific links I want do the equivelant of <a
> href="hello.do?contain=yes" onclick="someFunction(this);return
> false">Hello</a>. I am thinking I can add a global function or
> setAttributes. Ideas?


There is no 'document.getElementsByClassName' method, but you can get
all the spans using getElementsByTagName and look for one with a class
of 'container':

function getElementsByClassName(tName, cName)
{
var t = [];
var el, els = document.getElementsByTagName(tName);
for (var i=0, len=els.length; i<len; ++i){
el = els[i];
if (el.className && cName == el.className){
t[t.length] = el;
}
}
return t;
}

Then you can do:

var els = getElementsByClassName('span', 'container');


Now if you only have one 'container' element and you want all the A
elements inside it:

function addClicks()
{
var els = getElementsByClassName('span', 'container');
var aEl, aEls = els[0].getElementsByTagName('a');
for (var i=0, len=aEls.length; i<len; ++i){
aEl = aEls[i];
if (aEl.href){
// do stuff with aEl, e.g.
aEl.onclick = doAClick;
}
}
}

function doAClick()
{
var el = this;
alert(el.href);
return false;
}


If you don't want the link followed, have the onclick function return
false but make the HREF go somewhere useful for those without scripting
enabled. Or have script add the links in the first place, so non-script
users don't even see them.

If they aren't really links, use some other element and give them a
'clickable' style or use buttons.

Run 'addClicks' onload:

<body onload="addClicks();">


>
> <span class="container">
> <a href="hello.do?contain=yes">Hello</a>
> <span class="container"><a
> href="goodbye.do?contain=yes">Goodbye</a>
> </span>
>
> Thanks,
>
> John
>




--
Rob
 
Reply With Quote
 
 
 
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      01-20-2006
johkar wrote:

> I need to cancel the link and execute a function onclick of all the
> links within the span tag which has a class of "container" assigned.
> There will be only one span tag with this class applied.
>
> I know you can get a specific tag using
> document.getElementsByTagName('span')[0], but I am unsure how to get
> the one with the class="container". I know there is a getAttribute
> method, just need a pointer or two to put it all together.


You do not need and should not use getAttribute() for (X)HTML documents.
Although marked as deprecated in W3C DOM Level 2 HTML, the best way to
access attributes there, is to use the properties they are exposed as by
the respective element object interfaces.

> Once I know how to access the specific links I want do the equivelant
> of <a href="hello.do?contain=yes" onclick="someFunction(this);return
> false">Hello</a>.


ACK

> I am thinking I can add a global function or setAttributes.


What applies to getAttribute(), applies to setAttribute() as well.
See previous discussions on how to add an event listener for an
event to an element.

Note that unlike stated on occasions, the proprietary approach for this
cannot really be identified with the standards compliant one, hence

foo.addEventListener(
'click',
function()
{
// ...
return false;
},
false);

in practice is _not_ semantically equal to

foo.onclick = function()
{
// ...
return false;
};

I noticed this recently while trying to make my ObjectInspector standards
compliant in that regard. I observed that using the first approach, it was
not possible to implement a reliable display property toggle on `a[href]'
elements (for `ul' elements) in Mozilla/5.0; however, it was possible again
using the second approach again. (In case I overlooked something, I would
be thankful for any pointers as well.)

> Ideas?


Yes. I have already written such a method and several people posted such
before, but to not spoil your coding experience, here is the pointer you
asked for:

The object referred to by `document' has a getElementsByTagName() method
(per the HTMLDocument interface of W3C DOM Level 2 HTML) that accepts an
asterisk (*; instead of an element type identifier) as string argument to
return a HTMLCollection of _all_ element objects in the DOM tree. You can
iterate through that collection and check for the `className'[1] string
property of each element object; references to all matching element objects
can be arranged in an Array or a user-defined collection object and
returned from a method. Note that `className', like the `class' attribute
value, can be a whitespace-separated list of (CSS) class names.

[1] `class' could not be specified, since that is a reserved word in
several languages a binding is provided for, including ECMAScript
implementations.

> <span class="container">
> <a href="hello.do?contain=yes">Hello</a>
> <span class="container"><a
> href="goodbye.do?contain=yes">Goodbye</a>
> </span>


Although `span' elements can be nested, this does not look like a reasonable
piece of markup. Consider block-level elements like `div' to contain other
block-level elements like `ul' and inline-level elements like `a' and
`span'.


Happy coding!

PointedEars
 
Reply With Quote
 
johkar
Guest
Posts: n/a
 
      01-20-2006
Perfect, thank you. Yes, I didn't mean to nest the spans, just a
stupid cut and paste mistake.

John

 
Reply With Quote
 
johkar
Guest
Posts: n/a
 
      01-20-2006
Thanks for your insight, the nested spans were a mistake in posting my
'simple' example.

John

 
Reply With Quote
 
RobG
Guest
Posts: n/a
 
      01-20-2006
johkar wrote:
> Perfect, thank you. Yes, I didn't mean to nest the spans, just a
> stupid cut and paste mistake.


Forgot to mention that the getElementsByClassName function returns an
array that will contain references to all the elements with the tagName
and className specified, so you can use it for other purposes.

Because you only wanted the one element, the posted code was hard-coded
it to get the first element (i.e. index 0) of the returned array, but
you could loop through all of them if you wanted to.

As Thomas says, don't use getAttributes for this. DOM element objects
(e.g. span elements) also have a getAttribute() method, but again it's
not suitable for what you are doing.


--
Rob
 
Reply With Quote
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      01-20-2006
VK wrote:

> Just another way as a suggestion (by using a separate tag for
> JavaScript psi-links).


You want to get informed about the informal meaning of the word "psi".

> IMHO much easier to handle in all aspects plus
> an explicit visual difference in case if script is disabled.
>
> <html>


Not Valid. <URL:http://validator.w3.org/>

> <head>
> <title>JS Link</title>
> <meta http-equiv="Content-Type"
> content="text/html; charset=iso-8859-1">
> <style type="text/css">
> body {
> background-color: #FFFFFF;


Missing (foreground) `color' declaration, so potentially harmful.

<URL:http://www.w3.org/QA/Tips/color>

> }
>
> var{
> font-style: normal;


Unnecessary; this is the general default. In fact, forcing a certain
font-style on this element (which has often font-style:italic in UA basic
stylesheets) is potentially harmful as it can no longer be distinguished
from the rest of the text. See below.

> color: #0000FF;


Not True Web-Safe[tm], should be #00f.

> text-decoration: underline;


Misleading for the user, as that element type specifies no visible
hyperlink.

> cursor: not-allowed;


Invalid property value.

<URL:http://www.w3.org/TR/REC-CSS2/ui.html#propdef-cursor>
<URL:http://jigsaw.w3.org/css-validator/>

> }
> </style>
>
> <script type="text/javascript">
>
> function hOver(e) {
> var hColor = '#FF0000';


See above.

> var lnk = null;
> if ((e)&&(e.currentTarget)&&

^^^^^^^^^^^^^^^^^
Misuse of the `currentTarget' property; should be

var t = e.target || e.srcElement;

before and using `t' in place of the marked section.

<URL:http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-currentTarget>

Simple expressions like variable references or property accesses
do not need to be enclosed in parantheses nor does it change the
result of the evaluation.

> (e.currentTarget.tagName == 'VAR')) {


HTML element type identifiers (informal: tag names) are
case-insensitive, so that should be

(t.tagName.toLowerCase() == 'var')) {

<URL:http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-5353782642>

> lnk = e.currentTarget;
> lnk.style.color = hColor;


See above.

> }
> else if ((event)&&
> (event.srcElement)&&(event.srcElement.tagName == 'VAR')) {


This kind of branching is completely unnecessary, ...

> lnk = event.srcElement;
> lnk.runtimeStyle.color = hColor;


.... especially because the `runtimeStyle' property is unnecessary for
write access. The `style' property suffices for all DOMs this is
scripted for.

> if (lnk.title) {window.status = lnk.title;}


Scripts should not manipulate the content of the status bar of windows
in such an irresponsible way.

<URL:http://jibbering.com/faq/#FAQ4_35>
<URL:http://groups.google.com/groups?as_q=status+bar&as_ugroup=comp.lang.javascr ipt&scoring=d&filter=0>

> }
> else {
> /*NOP*/
> }


There is no "else", either it is the W3C DOM/Gecko DOM or the IE4 DOM;
this branch is unnecessary, especially as the "NOP" comment indicates
that nothing should be done in that case.

> }
>
> function hOut(e) {
> [...]
> }


The same nonsense here, even though it is far more reasonable to write
one method and use different argument values to facilitate both features.

>
> function init() {
> var lnk = document.getElementsByTagName('VAR');


The previous test for the DOM method was omitted, this is error-prone.

<URL:http://pointedears.de/scripts/test/whatami#inference>
<URL:http://www.jibbering.com/faq/faq_notes/not_browser_detect.html#bdFD>

> var len = lnk.length;
> var cur = (window.ActiveXObject) ? 'hand' : 'pointer';


AFAIK, this is flawed as Netscape 6+ on Windows supports ActiveXObject
to facilitate support for the Windows Media Player plugin), but its
Gecko layout engine does not support the IE-proprietary cursor:hand.

<URL:http://www.iol.ie/~locka/mozilla/plugin.htm>

> for (var i=0; i<len; i++) {
> lnk[i].style.cursor = cur;
> lnk[i].onmouseover = hOver;
> lnk[i].onmouseout = hOut;
> }
> }
>
> window.onload = init;


Misusing the proprietary `onload' property of the object referred to by
`window', and not the standards compliant `onload' property of the `body'
element as it should be.

<URL:http://www.w3.org/TR/html4/interact/scripts.html#adef-onload>

> </script>
>
> </head>
>
> <body>
> <p>
> <var onclick="alert('OK')" title="Check mail">Click me 1</var>


Utter nonsensical misuse of the `var' element which has the purpose of
marking up variable identifiers or parameters in (X)HTML hypertext.

<URL:http://www.w3.org/TR/html4/struct/text.html#edef-VAR>

Once again you have proven sufficiently what an awfully bad (Web) developer
you really are.


PointedEars
 
Reply With Quote
 
VK
Guest
Posts: n/a
 
      01-20-2006

Thomas 'PointedEars' Lahn wrote:
> ...


Have it read, had a lot of real fun (thanks for that).

No comments needed.

 
Reply With Quote
 
Michael Winter
Guest
Posts: n/a
 
      01-20-2006
On 20/01/2006 16:25, Thomas 'PointedEars' Lahn wrote:

> VK wrote:


[snip]

>> color: #0000FF;

>
> Not True Web-Safe[tm], should be #00f.


I personally don't care for that suggestion, and they are equivalent
(digit replication leads to the same value). General colour contrast is
a far more important concern.

[snip]

>> var lnk = null;
>> if ((e)&&(e.currentTarget)&&

>
> ^^^^^^^^^^^^^^^^^
> Misuse of the `currentTarget' property; should be
>
> var t = e.target || e.srcElement;


A far better suggestion is to use the this operator. The obvious intent
is to change the colour of the element to which the listener is
attached, therefore:

function hOver() {
if(this.style) {
this.style.color = '#ff0000';
}
}
function hOut() {
if(this.style) {
this.style.color = '#0000ff';
}
}

would seem a better solution, though one could go a step further and use:

function setColor(object, color) {
if(object && (object = object.style)) {
object.color = colour;
}
}

function hOver() {
setColor(this, '#ff0000');
}
function hOut() {
setColor(this, '#0000ff');
}

[snip]

>> window.onload = init;

>
> Misusing the proprietary `onload' property of the object referred to by
> `window', and not the standards compliant `onload' property of the `body'
> element as it should be.


That thought isn't always practical. For the BODY element to be
accessible as a property of the document object, it needs to have been
parsed on most, if not all, implementations. Clearly, it won't have been
if the code is included by a SCRIPT element child of HEAD.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
 
Reply With Quote
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      01-20-2006
Michael Winter wrote:

> On 20/01/2006 16:25, Thomas 'PointedEars' Lahn wrote:
>> VK wrote:
>>> color: #0000FF;

>> Not True Web-Safe[tm], should be #00f.

>
> I personally don't care for that suggestion, and they are equivalent
> (digit replication leads to the same value).


First read and understand the CSS section about this, then try to argue
about it. Digit replication is only performed if the display device
supports it.

> General colour contrast is a far more important concern.


It is an important aspect as well, one that is addressed better with
True Web-Safe[tm] colors.

>>> var lnk = null;
>>> if ((e)&&(e.currentTarget)&&

>>
>> ^^^^^^^^^^^^^^^^^
>> Misuse of the `currentTarget' property; should be
>>
>> var t = e.target || e.srcElement;

>
> A far better suggestion is to use the this operator.


True, in this case.

>>> window.onload = init;

>>
>> Misusing the proprietary `onload' property of the object referred to by
>> `window', and not the standards compliant `onload' property of the `body'
>> element as it should be.

>
> That thought isn't always practical. For the BODY element to be
> accessible as a property of the document object, it needs to have been
> parsed on most, if not all, implementations. Clearly, it won't have been
> if the code is included by a SCRIPT element child of HEAD.


I do not see your point. The most important point of preferring
the `onload' event handler attribute of the `body' element over
`window.onload' is that you can be _sure_ that the _document_ was
loaded and that the respective element objects have been created.


PointedEars
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
I'm looking for html cleaner. Example : convert <h1><span><font>my title</font></span></h1> => <h1>my title</h1>… Stéphane Klein Python 2 03-30-2010 12:35 AM
Can span include span? Fulio Open HTML 5 06-26-2009 10:24 PM
Is there any shortcut for "Debug > Attach > Attach to aspnet_wp.exe"? Warren Tang ASP .Net 1 09-17-2008 03:46 PM
attach agent to applet running in firefox (attach api) craiget@gmail.com Java 0 06-14-2007 12:28 AM
how do u invoke Tag b's Tag Handler from within Tag a's tag Handler? shruds Java 1 01-27-2006 03:00 AM



Advertisments