[thelist] tying events and styles together in JS?
Duncan O'Neill
dbaxo at ihug.co.nz
Wed Feb 19 18:26:00 CST 2003
Tom Dell'Aringa wrote:
> Heres a question,
>
> Say I have a page where I want every table row to have a onmouseover
> and onmouseout event, in order to change the color of the row - so I
> am doing this:
>
> <tr onmouseover="this.className='on';"
> onmouseout="this.className='off';" class="trHighLight">Stuff</tr>
>
> If this is a page with 30 rows, thats a lot of code. If I have 10
> pages that have this behavior, you get the picture.
>
> Is there some way either in JS or otherwise that I can specify this
> behavior for a TR instead of each time in the actual tag? It would be
> even better if I could do it only for the TRs where a certain class
> is.
>
Tom,
I've done this on several pages with h3 headings, so
I guess it's do-able for <tr>s.
I'm juts going to copy and paste the code, and hope it
makes sense to you, comments and all. Watch the wraps. :-)
You can see it in action here:
http://urbanlegend.f2o.org/?p=portfolio
and another version:
http://urbanlegend.f2o.org/legends/
/* clickShowOK is a boolean variable to detect whether
the browser will be able to cope with this
*/
if (clickShowOk){
h = document.getElementsByTagName("h3");
if (h.length==0)
{
return;
}
for (var i=0;i<h.length;i++){
original_headings[i] = h.item(i).innerHTML;// collect the original headings
h.item(i).innerHTML = '+ ' +
h.item(i).innerHTML; // add a plus sign to them
h.item(i).onclick = showHide; // assign a function to the click event
h.item(i).onmouseover = function () {this.style.color = '#' +
'cc6600';}//assign function
h.item(i).onmouseout = function
(){this.style.color='#' + '990000';}//assign function
}
}
}
// This does the show and hide of the sections under the headings
function showHide(){
// find out which heading has been clicked
var j=0;
while (this.innerHTML != h.item(j).innerHTML){j++;}
// change the mouseout function reference
this.onmouseout = function () {this.style.color = '#' + 'cc9933';}
//change the color of the heading
this.style.color='#' + '333333';
// get a reference to the next object which is the div
if (document.all && !isMac){// for IE Windows
var nextObj=this.nextSibling;
}
else {// for W3C compliant browsers
var nextObj=this.nextSibling.nextSibling;
}
//change the divs' display property and the headings' color
if (nextObj.style.display=='block'){
nextObj.style.display='none';
// the following line just adds the '+' when the content is hidden
this.innerHTML = '+ ' + original_headings[j];
}
else {
nextObj.style.display = 'block';
//the following line just adds the '-' when the
content is hidden this.innerHTML = '- ' + original_headings[j];
}
}
hth,
--
Duncan O'Neill
http://homepages.ihug.co.nz/~dbaxo/
More information about the thelist
mailing list