Creating generic javascript functions (ie. el.onmouseclick = function ...)

B

bizt

Hi,

I want to learn more about creating functions for element events
without having to put onclick event in every tag. For example:

<script>

document.getElementsByTagName('input').onclick = function () {
alert('hello');
}

</script>

Now, I know the above does not work as I have tried it but hopefully
the idea of what I am trying to achieve here. Basically for every input
tag, when the user triggers the event (click) it will do the same
function.

Anyway, I would more so like to learn about this type of scripting
where you assign functions to events. However, I dont know what to
search for in google and the like. Where could I learn more about this?


Thanks

Burnsy
 
V

VK

bizt said:
Hi,

I want to learn more about creating functions for element events
without having to put onclick event in every tag. For example:

<script>

document.getElementsByTagName('input').onclick = function () {
alert('hello');
}

</script>

Now, I know the above does not work as I have tried it but hopefully
the idea of what I am trying to achieve here. Basically for every input
tag, when the user triggers the event (click) it will do the same
function.

You cannot do it withing the conventional javascript. You need to
attach behavior ("binding" by Mozilla) to input element.

Otherwise you have to create a single function, retrieve a collection
of needed elements and assign this function to event listener in a
loop:

function clickHandler() {
window.alert(this.tagName);
}

var elm = document.getElementsByTagName('input');
var len = elm.length;
for (var i=0; i<len; i++) {
elm.onclick = clickHandler;
}
 
R

Ray

bizt wrote:
Anyway, I would more so like to learn about this type of scripting
where you assign functions to events. However, I dont know what to
search for in google and the like. Where could I learn more about this?

Thanks

Burnsy

Hey Burnsy,

I'd point you here: http://bennolan.com/behaviour/

This does exactly the thing you have in mind.

HTH,
Ray
 

Ask a Question

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

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

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top