Forum Moderators: open

Message Too Old, No Replies

Quick javascript help

         

hOtTiGeR123

6:28 pm on Nov 13, 2008 (gmt 0)

10+ Year Member



Hi,

If I have two anchor tags with ids, how would I say if you mouseover anchor 1 add a class to anchor 2 and if you mouseout remove the class? I have prototype if that helps?

If someone could point me in the right direction, thanks.

Fotiman

6:49 pm on Nov 13, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If you're using Prototype, then like this maybe:


<a id="A1">A1</a>
<a id="B2">B2</a>
<script type="text/javascript">
Event.observe(window, 'load', function() {
$('A1').observe('mouseover', function (e) {
$('B2').addClassName('shiny');
});
$('A1').observe('mouseout', function (e) {
$('B2').removeClassName('shiny');
});
});
</script>

hOtTiGeR123

7:04 pm on Nov 13, 2008 (gmt 0)

10+ Year Member



Hi, thanks for the reply. I actually just got it working using this, but your method might be better:

<a id="A1">A1</a>
<a id="B2" onMouseOver="javascript:A1On();" onMouseOut="javascript:A1Off();>B2</a>

<script type="text/javascript">
function A1On() {
$("A1").removeClassName("remove");
$("A1").addClassName("add");
}
function A1off() {
$("A1").removeClassName("remove");
$("A1").addClassName("add");
}

</script>

Fotiman

7:45 pm on Nov 13, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In general, I avoid using inline event handlers for a couple of reasons.

1. They can be overwritten as there is only 1 event "handler", whereas you can have as many event "listeners" as you like:
<a id="A1" onclick="foo();">
<script type="text/javascript">
$('A1').onclick = function() {};
function foo() { alert('this will never happen');}

2. I don't like to muck up my HTML with behavioral stuff. When I need to modify some behavior, I need only look in the script file. Nice separation of content and behavior (unobtrusive JavaScript).

Also, if I *was* to use inline handlers, I would use all lower case (onmouseover instead of onMouseOver) in case I ever want to convert to XHTML (though that's not likely either). :) And lastly, I wouldn't use "javascript:" to prepend my event handlers as all browsers use JavaScript as the default scripting language anyway.

hOtTiGeR123

9:51 pm on Nov 13, 2008 (gmt 0)

10+ Year Member



Thanks a lot, just one other thing since you're so helpful :D

How would I do something like this?

(li.classname a#id), function { ... }

Fotiman

2:53 pm on Nov 14, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Using Prototype:

$$('li.classname a#id')

Note, this function is $$() vs. $(). This example is not a very good one, though, because you might as well just use getElementById or $() since it ends with an id value. Here's a more likely example:

$$('div#foo li.bar img')