473,394 Members | 1,774 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Using Elements Created on the fly

I created an element on-the-fly using javascript like:

myA=document.createElement("A");
myA.href="javascript:acton(this)";
myA.className = "smallLink";
myText=document.createTextNode('sometext');
myA.appendChild(myText);

Then when I pressed the link I'd like to change the 'className' of this
link from 'smallLink' to 'biggerLink', but nothing happens.

function action(obj)
{
//alert(obj);
obj.className="biggerlink";
}

When I look at alert(obj) I get "[object]".
When I look at alert(obj.className) I get "undefined".

Anyone know what I am doing wrong here?

Mike

Jul 20 '05 #1
17 1475
Maybe

return obj.className="biggerlink";

--
George Hester
__________________________________
"Michael Hill" <hi****@ram.lmtas.lmco.com> wrote in message news:40***************@ram.lmtas.lmco.com...
I created an element on-the-fly using javascript like:

myA=document.createElement("A");
myA.href="javascript:acton(this)";
myA.className = "smallLink";
myText=document.createTextNode('sometext');
myA.appendChild(myText);

Then when I pressed the link I'd like to change the 'className' of this
link from 'smallLink' to 'biggerLink', but nothing happens.

function action(obj)
{
//alert(obj);
obj.className="biggerlink";
}

When I look at alert(obj) I get "[object]".
When I look at alert(obj.className) I get "undefined".

Anyone know what I am doing wrong here?

Mike

Jul 20 '05 #2
"Michael Hill" <hi****@ram.lmtas.lmco.com> wrote in message
news:40***************@ram.lmtas.lmco.com...
<snip>
myA=document.createElement("A");
myA.href="javascript:acton(this)";
myA.className = "smallLink";
myText=document.createTextNode('sometext');
myA.appendChild(myText); <snip> function action(obj)
{
//alert(obj);
obj.className="biggerlink";
}

<snip>

Javascript pseudo protocol HREFs are not methods of the created object
and are executed in the global scope, so - this - refers to the global
object and setting/creating a - className - property on the global
object is pointless.

You should never use javascript pseudo protocol HREFs:-

<URL: http://jibbering.com/faq/#FAQ4_24 >

- but to solve your specific problem you need to assign an onclick
method to the created object instead (though you will need the link to
have a HREF else it will not be a link, but then it probably could be a
SPAN element instead). E.g.:-

myA.onclick = function(){
this.className="biggerlink";
return false;
}

- or -

myA.onclick = new Funciton("this.className=\"biggerlink\";return
false;");

- depending on whether you understand the consequences of assigning an
inner function to an event handler or not (and/or whether the ECMA
Script compact profile will be relevant).

Richard.
Jul 20 '05 #3
>
- but to solve your specific problem you need to assign an onclick
method to the created object instead (though you will need the link to
have a HREF else it will not be a link, but then it probably could be a
SPAN element instead). E.g.:-

myA.onclick = function(){
this.className="biggerlink";
return false;
}


Richard,

Are you suggesting I change to something like:

mySPAN=document.createElement("SPAN");
mySPAN.className = "smallLink";
mySPAN.onclick = new Function("this.className=\"biggerlink\";return
false;");
myText=document.createTextNode('sometext');
mySPAN.appendChild(myText);

Mike
Jul 20 '05 #4
"Michael Hill" <hi****@charter.net> wrote in message
news:10*************@corp.supernews.com...

- but to solve your specific problem you need to assign an
onclick method to the created object instead (though you will
need the link to have a HREF else it will not be a link, but
then it probably could be a SPAN element instead). E.g.:-

myA.onclick = function(){
this.className="biggerlink";
return false;
}
Are you suggesting I change to something like:

mySPAN=document.createElement("SPAN");
mySPAN.className = "smallLink";
mySPAN.onclick = new Function("this.className=\"biggerlink\";
return false;");
I assume you realise that the preceding line should not wrap.
myText=document.createTextNode('sometext');
mySPAN.appendChild(myText);


I don't have enough information about the context to make that
judgement. But the original code seemed to be attempting to create an
element that, when clicked on, change CSS styles but did nothing else
and given that browsers that support creating new elements also support
onclick events on most elements (including SPANs) a SPAN element might
be better suited to the task.

The important things are to never use a javascript pseudo-protocol HREF
if it is not going to directly result in the replacement of the current
page, and that if you want to refer to an element with the - this -
keyword you can only do so from within a function that is a method of
the element, not code that is executed in the global context as a side
effect of clicking on it. (and never even consider doing anything
proposed by George Hester. Doing the opposite, or just banging your head
on a desk a few times, would always be more productive.)

Beyond that the type of element used depends on the design and
specification for the task. But an A element has inherent behaviour that
users understand an indicating a link with which they can navigate to
another page and undermining the user's expectation is generally not
considered good UI design.

Richard.
Jul 20 '05 #5
Jesus Richard why continue bashing me? What's the purpose? I been bashed I been made to eat dog meat you won! Are you a happy camper now? What's wrong with you? You don't like me that's fine. You need to tesase like a juvinelle. Are you that insecure that all in the world must know you dislike like? Grow up man!@!!

--
George Hester
__________________________________
"Richard Cornford" <Ri*****@litotes.demon.co.uk> wrote in message news:bv*******************@news.demon.co.uk...
"Michael Hill" <hi****@charter.net> wrote in message
news:10*************@corp.supernews.com...

- but to solve your specific problem you need to assign an
onclick method to the created object instead (though you will
need the link to have a HREF else it will not be a link, but
then it probably could be a SPAN element instead). E.g.:-

myA.onclick = function(){
this.className="biggerlink";
return false;
}

Are you suggesting I change to something like:

mySPAN=document.createElement("SPAN");
mySPAN.className = "smallLink";
mySPAN.onclick = new Function("this.className=\"biggerlink\";
return false;");


I assume you realise that the preceding line should not wrap.
myText=document.createTextNode('sometext');
mySPAN.appendChild(myText);


I don't have enough information about the context to make that
judgement. But the original code seemed to be attempting to create an
element that, when clicked on, change CSS styles but did nothing else
and given that browsers that support creating new elements also support
onclick events on most elements (including SPANs) a SPAN element might
be better suited to the task.

The important things are to never use a javascript pseudo-protocol HREF
if it is not going to directly result in the replacement of the current
page, and that if you want to refer to an element with the - this -
keyword you can only do so from within a function that is a method of
the element, not code that is executed in the global context as a side
effect of clicking on it. (and never even consider doing anything
proposed by George Hester. Doing the opposite, or just banging your head
on a desk a few times, would always be more productive.)

Beyond that the type of element used depends on the design and
specification for the task. But an A element has inherent behaviour that
users understand an indicating a link with which they can navigate to
another page and undermining the user's expectation is generally not
considered good UI design.

Richard.

Jul 20 '05 #6
On Thu, 29 Jan 2004 15:37:07 GMT, George Hester <he********@hotmail.com>
wrote:

[Fixed and trimmed top-post]
"Richard Cornford" <Ri*****@litotes.demon.co.uk> wrote in message
news:bv*******************@news.demon.co.uk...
The important things are to never use a javascript pseudo-protocol
HREF if it is not going to directly result in the replacement of
the current page, and that if you want to refer to an element with
the - this - keyword you can only do so from within a function that
is a method of the element, not code that is executed in the global
context as a side effect of clicking on it. (and never even
consider doing anything proposed by George Hester. Doing the
opposite, or just banging your head on a desk a few times, would
always be more productive.)


Jesus Richard why continue bashing me? What's the purpose? I been
bashed I been made to eat dog meat you won! Are you a happy camper
now? What's wrong with you? You don't like me that's fine. You
need to tesase like a juvinelle. Are you that insecure that all in
the world must know you dislike like? Grow up man!@!!


Actually, I believe the point of Mr Cornford's comments were to warn the
OP against following your useless advice. Did you actually try your
suggestion? I doubt it, for if you did, you would find that the entire
page would be replaced by the text, biggerlink. I might normally attempt
to explain why but the last time I offered you the explanation to a
problem, you told me, though more tersely, to f*** myself.

Mr Cornford's remarks about the OP "banging his head" are quite correct;
it would have been more productive than your suggestion. At least the OP
would only have the current situation to continue with, not the added
worry of why his page suddenly disappeared.

Mike

--
Michael Winter
M.******@blueyonder.co.invalid (replace ".invalid" with ".uk" to reply)
Jul 20 '05 #7
> Javascript pseudo protocol HREFs are not methods of the created object
and are executed in the global scope, so - this - refers to the global
object and setting/creating a - className - property on the global
object is pointless.

You should never use javascript pseudo protocol HREFs:-


Richard,

I was thinking about this some more and I thought I'd let you know that I
totally agree. I am using this though to open another window so it should
be ok to use a link in this case.

Here's that code modified some more:

I happen to be iterating over an array and producing some rows here,
putting in a link because I want the use to be able to click on them and
open a window:

<snip>
myA=document.createElement("A");
myA.href="javascript:void();"
myA.className = "smallLink";
//here I am creating bogus attributes and tieing them to the link object,
I'll need them later
myA.tmp1 = child_array[j][i-2]; // this is the parent number that is
key in the database
myA.tmp2 = child_array[j][i-1]; // this is the child number that is
also part of the key in the database
myA.onclick = function (evt) { this.className="smallred";
edit_action(this.tmp1,this.tmp2); return false; };
// this is the text title
myText=document.createTextNode(child_array[j][i]);
// Appends the text node to the td
myA.appendChild(myText);
<snip>

function edit_action(p_id,id)
{
var win = window.open("somepgm?p_num="+p_id+"&c_num="+id,<sn ip>
win.focus();
}

1) do you think this is a proper use, now?
2) this code works, but doesn't change the color of the link until after
the window opens. I want the link to change color immediately so the user
knows "something" is happening. Sometimes it takes the users window a min
to open. I don't want the user to be clicking on this over and over.

Thanks for your comments.

Mike

Jul 20 '05 #8
"George Hester" <he********@hotmail.com> wrote in message
news:DM***************@twister.nyroc.rr.com...
Jesus Richard why continue bashing me? What's the purpose?

<snip>

As Mr Winter correctly surmised, my comments were intended as a warning
to the OP rather than a superfluous effort to bash you.

You have made it abundantly clear (by belittling and directly insulting
everyone who has ever offered you any good advice here) that you are
completely confident in the validity of your coding style. Based as it
is on scouring the Internet and newsgroups for any old half-ass hack
that superficially satisfies your criteria for a solution and then
jamming them into web pages without any real understanding of the code
used, its mechanism or the consequences. And that you don't see any need
to do anything differently.

Eventually its inevitable consequences will demonstrate to you why your
whole approach is so spectacularly wrong. And when that happens the only
people left willing to talk to you will not be capable of doing any more
than offering you more half-ass hacks, as you have already reached a
position where none of the people on this group who know how to properly
implement a browser script are willing to bother with you at all. And
you have stated that that suites you just fine.

But as your hack agglomerate approaches its inevitable fatal complexity
threshold you are inventing fairy tails to explain the artefacts of the
ensuing chaos, and as a result are in the unique position of knowing
less and less about browser scripting as time goes by.

There is nothing that can be done about that (and ever less people
willing to try). That doesn't matter, you can rattle about in your own
misconceptions to you harts content. But when you start bothering other
people with your nonsense they deserve to be warned that the best that
they can expect from you is the worst approach available, that normally
what you say is an baseless fantasy and at worst your suggestions will
be positively harmful.

Richard.
Jul 20 '05 #9
"Michael Hill" <hi****@ram.lmtas.lmco.com> wrote in message
news:40***************@ram.lmtas.lmco.com...
<snip>
myA=document.createElement("A");
myA.href="javascript:void();"
It is probably harmless here because the onclick handler returns false
and cancels the navigation and without JavaScript enabled the A element
will never be created but javascript pseudo-protocol HREFs really should
be avoided as a matter of habit.
myA.className = "smallLink";
//here I am creating bogus attributes and tieing them to
//the link object, I'll need them later
myA.tmp1 = child_array[j][i-2]; // this is the parent
//number that is key in the database
myA.tmp2 = child_array[j][i-1]; // this is the child
//number that is also part of the key in the database myA.onclick = function (evt) { this.className="smallred";
edit_action(this.tmp1,this.tmp2); return false; };
This is OK so long as you are aware that assigning an inner function as
an event handler will produce a closure and that has implications
(particularly provoking the memory leak bug on IE browsers).

If you are creating numerous A elements with identical onclick functions
and having them retrieve the data they need from expando properties on
those elements then you could create a separate named function
definition and assign a reference to it to the onclick properties.

// this is the text title
myText=document.createTextNode(child_array[j][i]);
// Appends the text node to the td
myA.appendChild(myText);
<snip>

function edit_action(p_id,id)
{
var win = window.open("somepgm?p_num="+
p_id+"&c_num="+id,<snip>
Not all browsers support a window.open function and calling it
unverified on one of those browsers will generate an error.
win.focus();
}

1) do you think this is a proper use, now?
Yes, in principal if clicking on a link is going to result in the
display of a new page then that is probably within the expectations of
the users, even if that page is in a new window. Of course they may
still be confused if they happen to be operating a pop-up blocker or a
browser with that feature built in.

Generally the issues surrounding the consequences of the common use of
pop-up blocking mechanisms makes me always recommend never even
attempting to open a new window with a script. Even the most reliable
window opening script ever presented on this group is nowhere near
reliable enough for practical use.
2) this code works, but doesn't change the color of the link
until after the window opens. I want the link to change color
immediately so the user knows "something" is happening.
Sometimes it takes the users window a min to open. I don't
want the user to be clicking on this over and over.


You could experiment with using onmousedown to set the className for the
element and onclick to open the new window, or a CSS style for the
active link but it might just be that the browser/system is too busy
opening the new window to re-draw the existing one with the new styles.

It has been observed that changing the className property of an element
causes the browser to do considerably more work than would be required
by just making the relevant changes to the element's style object.

But I would not expect a long delay between opening a new window and its
contents starting to download to delay re-drawing of the original
window, there should be sufficient system resources available for the
existing window to be re-drawn while the new window is waiting for a
response to its initial request.

Richard.
Jul 20 '05 #10
> >myA.className = "smallLink";
//here I am creating bogus attributes and tieing them to
//the link object, I'll need them later
myA.tmp1 = child_array[j][i-2]; // this is the parent
//number that is key in the database
myA.tmp2 = child_array[j][i-1]; // this is the child
//number that is also part of the key in the database

myA.onclick = function (evt) { this.className="smallred";
edit_action(this.tmp1,this.tmp2); return false; };


This is OK so long as you are aware that assigning an inner function as
an event handler will produce a closure and that has implications
(particularly provoking the memory leak bug on IE browsers).


Do you know of a better way to assign these values?

Mike

Jul 20 '05 #11
> You could experiment with using onmousedown to set the className for the
element and onclick to open the new window, or a CSS style for the
active link but it might just be that the browser/system is too busy
opening the new window to re-draw the existing one with the new styles.


onmousedown works great!

Mike

Jul 20 '05 #12
>
If you are creating numerous A elements with identical onclick functions
and having them retrieve the data they need from expando properties on
those elements then you could create a separate named function
definition and assign a reference to it to the onclick properties.


Richard,

Yes I am, each is the same except for the combination of parent/child that
is passed.

Can you give me an example of what you are talking about here?

Mike
Jul 20 '05 #13
"Michael Hill" <hi****@ram.lmtas.lmco.com> wrote in message
news:40***************@ram.lmtas.lmco.com...
<snip>
myA.onclick = function (evt) { this.className="smallred";
edit_action(this.tmp1,this.tmp2); return false; };


This is OK so long as you are aware that assigning an inner
function as an event handler will produce a closure and that
has implications (particularly provoking the memory leak bug
on IE browsers).


Do you know of a better way to assign these values?


The method I posted to your preceding question is probably the safest
method with the least potential side effects (probably none). But better
or best would depend on the circumstances/context. I could probably come
up with 20-odd variations on assigning event handlers to elements, many
of them involving closures/inner functions and probably each well suited
to one context or another.

Richard.
Jul 20 '05 #14
"Michael Hill" <hi****@ram.lmtas.lmco.com> wrote in message
news:40***************@ram.lmtas.lmco.com...
... create a separate named function definition and
assign a reference to it to the onclick properties.


Richard,

Yes I am, each is the same except for the combination of
parent/child that is passed.

Can you give me an example of what you are talking about
here?


function forA_OnClick(evt){
edit_action(this.tmp1,this.tmp2);
return false;
}
function forA_OnMouseDown(){
this.className="smallred";
}

Then later in the function that creates the elements:-

myA.onclick = forA_OnClick;
myA.onmousedown = forA_OnMouseDown;

One function object is created for each function definition (in the
global scope) and then the name of the function is used to assign a
reference to that function object to the corresponding event handlers of
each A element created. No matter how many A elements are created they
all share references to the same function objects but the functions are
executed as methods of the elements so - this - always refers to the
element on which the handler is being called. Because the functions are
defined as global functions they are not inner function so assigning
references to them do not form closures.

Richard.
Jul 20 '05 #15
"Richard Cornford" <Ri*****@litotes.demon.co.uk> writes:
This is OK so long as you are aware that assigning an inner function as
an event handler will produce a closure and that has implications
(particularly provoking the memory leak bug on IE browsers).


Could you direct me to a reference? I didn't have much luck with
Google.

--
Chris Jeris cj****@oinvzer.net Apply (1 6 2 4)(3 7) to domain to reply.
Jul 20 '05 #16
"Christopher Jeris" <cj****@oinvzer.net> wrote in message
news:xi*************@hsph.harvard.edu...
<snip>
(particularly provoking the memory leak bug on IE browsers).


Could you direct me to a reference? I didn't have much
luck with Google.


Didn't you? You used the "Advance Search" page on groups.google.com to
search specifically comp.lang.javascirpt with the keywords "memory
leak"? It should have turned up at least two extensive discussions of
the problem with demonstration code, explanations and some solutions.

(maybe also worth searching microsoft.public.scripting.jscript as it has
been mentioned there also, though not in as much detail.)

Let me know if you cannot locate the threads on groups.google.com and I
will look them up myself and post the URLs later (much later, as I will
be busy for the next 5 or 6 hours).

Richard.
Jul 20 '05 #17
"Richard Cornford" <Ri*****@litotes.demon.co.uk> writes:
Didn't you? You used the "Advance Search" page on groups.google.com to
search specifically comp.lang.javascirpt with the keywords "memory
leak"?


No, I'm just stupid, as usual.

--
Chris Jeris cj****@oinvzer.net Apply (1 6 2 4)(3 7) to domain to reply.
Jul 20 '05 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: RCS | last post by:
I have a UI that needs a couple of threads to do some significant processing on a couple of different forms - and while it's at it, update the UI (set textboxes, fill in listviews). I created a...
1
by: CS Wong | last post by:
Hi, I have a page form where form elements are created dynamically using Javascript instead of programatically at the code-behind level. I have problems accessing the dynamically-created...
7
by: Lau Lei Cheong | last post by:
Hello, I'm using javascript's insertAdjacentHtml() to insert images to the webform at runtime. This runs fine(image successfully displayed at the browser) but when I tried to access the...
6
by: Vikram | last post by:
I have added some input elements on a page using javascript at client side. when i submit the page, i am unable to access the values of input elements created using request.form. Are elements...
53
by: Hexman | last post by:
Hello All, I'd like your comments on the code below. The sub does exactly what I want it to do but I don't feel that it is solid as all. It seems like I'm using some VB6 code, .Net2003 code,...
3
by: SMH | last post by:
Normally an SVG document is loaded/parsed/interpreted inside an HTML document using an 'object' (or 'embed') element, although there are supposedly other ways too. The problem is, the SVG document...
2
by: Roy Chastain | last post by:
I have some 'base' schema definitions that are going to be in several projects in the future. The processing of resulting classes created by XSD will be consistent across the new projects. I...
6
by: =?Utf-8?B?VGFtbXkgTmVqYWRpYW4=?= | last post by:
Hi, can someone please let me know how I can read xml elements using object oriented program. I created a class to use the get and set properties however I dont know how I can pass the values from...
1
by: javediq143 | last post by:
Hi All, This is my first post in this forum. I'm developing a CMS for my latest website. This CMS is also in PhP & MySQL. I'm done with the ADD section where the Admin can INSERT new records in...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.