473,770 Members | 1,870 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to add extra action to onclick event ?

abs
My element:
<span onclick="alert( 'test')" id="mySpan">tes t</span>

Let's say that I don't know what is in this span's onclick event. Is it
possible to add another action to this element's onclick event ? I've tried
something like this:

oncl = document.getEle mentById('mySpa n').onclick
oncl = oncl + '\n;alert(\'add ed\')'
document.getEle mentById('mySpa n').onclick = oncl

And after this operation there'e no reaction to clicking on the <span>.
Anybody knows how to fix it ?

Best regards,
ABS


Jul 23 '05 #1
17 4882
alu

"abs" <no****@wp.pl > wrote in message news:d7******** **@inews.gazeta .pl...
My element:
<span onclick="alert( 'test')" id="mySpan">tes t</span>

Let's say that I don't know what is in this span's onclick event. Is it
possible to add another action to this element's onclick event ? I've tried something like this:

oncl = document.getEle mentById('mySpa n').onclick
oncl = oncl + '\n;alert(\'add ed\')'
document.getEle mentById('mySpa n').onclick = oncl

And after this operation there'e no reaction to clicking on the <span>.
Anybody knows how to fix it ?

Best regards,
ABS

I'm probably misunderstandin g the problem, but it would seem easier
to set onclick to a function, then add lines to the -function- dynamically.

<scr ipt>
function mySpanClicked() {
alert("test");
}
</scr ipt>

<span onclick="mySpan Clicked()" id="mySpan">tes t</span>

<scr ipt>
.... script to add to mySpanClicked()
</scr ipt>

-alu
Jul 23 '05 #2
You cant just add another action to the onClick event, but you may find
this handy....

<span onclick="alert( 'test');alert(' second function')"
id="mySpan">tes t</span>

This will now call the 2 actions one after the other. note the
semi-colon in there after the first event.

You can repeat that more to add extra actions.

Best Regards,
Sandfordc

Jul 23 '05 #3
On 26/05/2005 20:32, abs wrote:
My element:
<span onclick="alert( 'test')" id="mySpan">tes t</span>

Let's say that I don't know what is in this span's onclick event. Is it
possible to add another action to this element's onclick event ?
The code at the end of this post is a very generic way of adding and
removing listeners from an element, much in the same way as the
addEventListene r method.

Though the code looks daunting, a lot of it is internal. For basic
usage, you need only three methods:

DispatcherFacto ry.createDispat cher()

This creates and returns a dispatcher object. Each dispatcher
maintains a list of listeners that are associated with a type
of event. When the dispatcher is attached to an element, it
forwards all events of this type to the listeners it manages.

The other two important methods are members of the dispatcher objects
returned by createDispatche r.

Dispatcher.add( listener)

This method adds a function to the internal list. Simple.
Dispatcher.atta ch(element, type)

This methods associates the dispatcher with a particular
event type, such as the click event, and a particular element.
If a listener already exists on that element for that type (an
onclick attribute, for example), it will be added to the
internal list before the dispatcher is attached.

So, given:

<span id="mySpan" onclick="alert( 'original');">T est</span>

and a reference to that element:

var element = document.getEle mentById('mySpa n');

you can add a new function with:

var dispatcher = DispatcherFacto ry.createDispat cher();

dispatcher.add( function() {
alert('added');
});
dispatcher.atta ch(element, 'onclick');

You can call add and attach in any order, and you can add listeners at
any time. You can also attach the same dispatcher to several different
elements with different types, though I doubt you'll have any use for that.

The other two methods you can use are again dispatcher members.

Dispatcher.remo ve(listener)

This searches for the given function. If it exists within the
list, it's discarded.
Dispatcher.deta ch(element, type)

This removes the dispatcher and all of its listeners of the
given type from the element.
There are simpler solutions, but they aren't as flexible. It's
incredibly late now, so someone else will have to continue with those
alternatives.
oncl = document.getEle mentById('mySpa n').onclick
oncl = oncl + '\n;alert(\'add ed\')'
document.getEle mentById('mySpa n').onclick = oncl


There's a misconception here: the onclick property isn't a string. When
a user agent parses attributes like onclick in HTML, it converts the
code to a function. So, it's not simply a matter of added more code. The
dispatcher object below allows you to manage several functions on one
property.

Do ask if you have any questions.

Mike
Parts of the code below can be removed. If you won't be removing
listeners, you can eliminate the two remove methods (in Node and
createDispatche r), the detachDispatche r function, and the line:

Dispatcher.deta ch = detachDispatche r;

The code at the very end emulates the call method that should exist on
all functions. JScript versions prior to 5.5 (and so usually IE versions
prior to 5.5) don't include this method so a substitute needs to be
included. The dispatcher code only needs case 1 within the switch
statement, so you could remove the other clauses. They were included to
make the substitute more useful.

var DispatcherFacto ry = (function(globa l) {
function Node(data) {
var next = null;

this.fire = function(elemen t, event) {
var performDefault = next
? next.fire(eleme nt, event)
: true;

return data.call(eleme nt, event) && performDefault;
};

this.add = function(listen er) {
if(data == listener) {return;}

if(next) {
next.add(listen er);
} else {
next = new Node(listener);
}
};
this.remove = function(listen er) {
if(data == listener) {
return next;
} else if(next) {
next = next.remove(lis tener);
}
return this;
};
}

function attachDispatche r(element, type) {
var listener = element[type];

if(('function' == typeof listener)
&& (this.construct or != listener.constr uctor))
{
this.add(listen er);
}
element[type] = this;
}
function detachDispatche r(element, type) {
if(this == element[type]) {
element[type] = null;
}
}

return {
createDispatche r : function() {
var list = null;

function Dispatcher(even t) {
return list
? list.fire(this, event || global.event)
: true;
}
}
Dispatcher.cons tructor = this;

Dispatcher.add = function(listen er) {
if(list) {
list.add(listen er);
} else {
list = new Node(listener);
}
};
Dispatcher.remo ve = function(listen er) {
if(list) {
list = list.remove(lis tener);
}
};

Dispatcher.atta ch = attachDispatche r;
Dispatcher.deta ch = detachDispatche r;
}
};
})(this);

if('function' != typeof Function.protot ype.call) {
Function.protot ype.call = function(object ) {
var property = '__call', result, undef;

while('undefine d' != typeof object[property]) {
property = '__' + property;
}
object[property] = this;

switch(argument s.length - 1) {
case 0:
result = object[property]();
break;
case 1:
result = object[property](arguments[1]);
break;
case 2:
result = object[property](arguments[1], arguments[2]);
break;
case 3:
result = object[property](arguments[1], arguments[2],
arguments[3]);
break;
case 4:
result = object[property](arguments[1], arguments[2],
arguments[3], arguments[4]);
break;
case 5:
result = object[property](arguments[1], arguments[2],
arguments[3], arguments[4], arguments[5]);
break;
default: alert('Too many arguments!');
}
object[property] = undef;

return result;
};
}

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #4
On 27/05/2005 03:26, Michael Winter wrote:

[snip]
function Dispatcher(even t) {
return list
? list.fire(this, event || global.event)
: true;
}

^
I don't know where that closing brace came from, but it shouldn't be there.

I'll make the disclaimer now: this code is untested, and will remain so
until I wake up tomorrow. I don't think there are any more problems, but
I'm too tired to make any kind of guarantee.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
abs
Michael Winter wrote:
I'll make the disclaimer now: this code is untested, and will remain
so until I wake up tomorrow. I don't think there are any more
problems, but I'm too tired to make any kind of guarantee.


First, thank you so much for your post containing so lot of knowledge.
I've got one problem with that: when I call:

dispatcher.add( function() {
alert('added');
});

Firefox, throws an error: 'dispatcher has no properties'. I'm trying to fix
it by myself, but until now I couldn't see any mistakes in the code.

Best regards,
ABS
Jul 23 '05 #6
abs
alu wrote:
I'm probably misunderstandin g the problem, but it would seem easier
to set onclick to a function, then add lines to the -function-
dynamically.


Thanks, but it's impossible. This is a part of bigger project and it has to
be universal, I don't even know the name of the function of onclick.

Regards,
ABS
Jul 23 '05 #7
abs
And another question: will I be able to pass the parameter to added function
?

ABS
Jul 23 '05 #8
VK
var success = (window.addEven tListener)?
someObject.addE ventListener('c lick',
functionPointer , false) :
someObject.atta chEvent('onclic k',
functionPointer );

You can add/attach any amount of functions to any object. Three points
to pay attention to:

1. With multiple event handlers each event handler will be called in a
random order (so you don't know which one will be called 1st, 2nd, 3rd,
n-th)

2. attachEvent in IE requires function pointer as its argument, so you
cannot use anonymous function declaration instead. You can bypass it by
doing:
var newFun = new Function(...);
someObject.atta chEvent('onclic k', newFun);

3. in IE event names are always "onevent" (starts with "on"). In FF a
semi-philologic approach is chosen, so
obj.onevent = (with "on") but addEventListene r('event'...) (without
"on") Not really a problem but easy to mistype.

If you really need to call handlers in a fixed sequence (kinda
pointless because native JavaScript does not have synchronized methods)
you may use a function wrapper:
var newFun = new Function("metho d1; method2; method3;...");
var success = (window.addEven tListener)?
someObject.addE ventListener('c lick', newFun,
false) :
someObject.atta chEvent('onclic k', newFun);

Jul 23 '05 #9
VK wrote:
var success = (window.addEven tListener)?
someObject.addE ventListener('c lick',
The W3C events DOM - addEventListene r - method is specified as a
property of Node objects. The - window - is not a Node object and so is
not specified as having such a property, and in some environments
supporting the events DOM the window does not have such a method. The
obviously correct test to use in this context is the test that has a
one-to-one relationship with the action to be taken; -
(someObj.addEve ntListener)?som eObject.addEven tListener -.
functionPointer , false) :
someObject.atta chEvent('onclic k',
Not all browsers that do not implement a - window.addEvent Listener -
method implement an - attachEvent - method on elements. Indeed I can
only think of two that do. In the absence of such a method this code
would error-out with the call to a non-existent method, which is pretty
poor scripting.

<snip> 2. attachEvent in IE requires function pointer as its
argument, so you cannot use anonymous function declaration
instead.
There is no such thing as an 'anonymous function declaration'; the
function name Identifier is not optional in a function declaration.
You can bypass it by doing:
var newFun = new Function(...);
someObject.atta chEvent('onclic k', newFun);

<snip>

Bypass what? A function object is a function object regardless of how it
is created.

Richard.
Jul 23 '05 #10

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

Similar topics

2
1568
by: Matthew | last post by:
Hi, how can I create a <A HREF'ed> image that, with an onclick event will cause the cursor to jump into a particularly assigned text form input field?
17
61444
by: Mike Gratee | last post by:
Is it possible to use JavaScript to cause the browser to click a link on a page and have the browser act exactly like the user had clicked on the link directly? In other words, I need to programmatically issue a JavaScript statement which causes the browser to act just like the user clicked on a link in my page. And if that link has an onClick JS event defined, I'd want that onClick event to execute too, exactly the same as if the user...
2
3424
by: Vinita Sharma | last post by:
Hi All, I have a strange problem. I have 2 text boxes and a button in my form. There is a function called on onchange event of the first text box. There is another function called on onclick event of the button. Things work fine if you move from one field to another using tab keys. But if you change something in the first text box and move to button using mouse, the onchange event of the text box is called but the onclick event of the...
3
3810
by: f1crazed | last post by:
Hello, I am wanting to fire the onClick event of button1 by pressing button2. Does anyone have a clue if this is even posible? If so PLEASE HELP!! Thanks.
4
1968
by: Roland | last post by:
I was wondering, what happens when you have an onclick event and an error occurs in it: In an <a> element: onclick="zoomFullExtent(); return false;" I know that there is an error happening in zoomFullExtent. I didn't define my own error handler, so the default one is used.(My browser is Firefox 1.0).
5
13963
by: Stuart Shay | last post by:
Hello All I am working on ASP.NET 1.1 Custom Pager that allows a User to Enter a Number in a TextBox and go to the page selected. Since the OnClick Event does not work in ASP.NET 1.1 for a TextBox I want to use a hidden button to fire when the Onclick Event is fired for the TextBox.
3
6509
by: Michael_R_Banks | last post by:
I'm trying to dynamically build a table that allows users to remove rows when they click a corresponding button. For some reason, whenever I add the button to the table, it never fires the onclick event. I'm stumped with this one, any assistance would be appreciated. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:// www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"...
7
13223
by: Moses | last post by:
Hi Everybody, I have a problem with onClick event which works in FF and does not work in IE, Here I have giving the details Please help. I am creating a <aTag. dom_obj = document.createElement('a'); dom_obj.setAttribute('href', 'javascript:void(0)'); dom_obj.setAttribute('onclick', 'javascript:test()');
6
2178
by: Nathan Sokalski | last post by:
I have a DataList which contains several LinkButtons, which are used to select a category in my application. I want the currently selected category to use a different CSS class. Here is an example of the generated code for one of the buttons: <a onclick="UnselectCategories();datCategories_ctl00_lnkCategory.className='Category_Selected';" id="datCategories_ctl00_lnkCategory" class="Category_Selected"...
0
9617
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9453
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10254
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10099
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10036
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8929
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3607
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.