Jump to content

attaching events with Javascript


A-Damage
 Share

Recommended Posts

I'm not sure how tricky this is, but I want to be able to add events to anchors in a navbar as the page loads. Here is the html I want to target:

<div id="navbar">	<ul>		<li><a href="index.aspx">Table of Contents</a></li>	</ul></div>

Now, what I want to do is add events such as:

<a href="index.html" onmouseover="hover_animation()">

as the page loads, to each link. I want to do it this way as there will be an indeterminate amount of links in the navbar, so I want to dynamically add the events to each link, no matter how many will be on the page at any given time. I looked through the Javascript and DOM tutorials, but couldn't find anything. NOTE: There is more going on than just simple hovers that I can't do with CSS, which is why I want to target this with Javascript. Since this is for a client, I can't reveal all of the mark-up, but rest assured, there is a lot more going on then simple :hover pseudo classes will accomplish.Any help is appreciated.Thanks,- Adam

Link to comment
Share on other sites

You could use the document.getElementById('navbar').getElementsByTagName('a') method to loop through all <a> tags child of the element with id "navbar". However, this effect would only be applied after the page loads.

window.onload = function() {	hyperlinks = document.getElementById('navbar').getElementsByTagName('a');	for (i = 0; i < hyperlinks.length; i++) {		hyperlinks[i].onmouseover = hover_animation; //hover_animation() is the onmouseover function 	}}

Link to comment
Share on other sites

You could use the document.getElementById('navbar').getElementsByTagName('a') method to loop through all <a> tags child of the element with id "navbar". However, this effect would only be applied after the page loads.
window.onload = function() {	hyperlinks = document.getElementById('navbar').getElementsByTagName('a');	for (i = 0; i < hyperlinks.length; i++) {		hyperlinks[i].onmouseover = hover_animation; //hover_animation() is the onmouseover function 	}}

So, there's no way to append events to nodes with Javascript and the DOM? Something like
window.onload = function() {	hyperlinks = document.getElementById('navbar').getElementsByTagName('a');	for (i = 0; i < hyperlinks.length; i++) {		hyperlinks[i].add = "onmouseover='hover_animation()'"; 	}}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...