tags:

views:

414

answers:

5

I have an HTML span which changes it's class onmouseover and onmouseout:

<span id="someSpan" class="static" onmouseover="this.className='active'" onmouseout="this.className='static'">Some Text</span>

I want to be able to enable and disable (change) the onmouseover and onmouseout events using a Javascript function called elsewhere on the page. Is this Possible?

+2  A: 

The safe way is to use a Javascript toolkit like Prototype or JQuery.

They all can do things like this easily but it works cross-browser.

For example, here is how you do it in JQuery.

Jason Cohen
+1  A: 

Sure.

document.getElementById('someSpan').onmouseover = 
     function() { 
         this.className='newactive'; 
     };
Tom Ritter
Thanks, I'd like to accept this answer and Jason's. This works as desired for my prototype but I'll be looking at how to do this using JQuery later on.
Troyzor
A: 

Code:

document.getElementById("someSpan").onmouseover = function()
{
    //New code
};//Do not forget the semicolon
Time Machine
A: 

I would agree jQuery would be easier, but if you would like to stick to JavaScript, I believe this should work:

document.getElementById("elementId").onMouseOut=functionName;

Additionally, jQuery is about 20Kb in size (size of production framework file), so it might slow down the loading of your page. Something to consider if you're just using it for a few things that may be done in JavaScript.

raptors
+1  A: 

Yes, you can do that simply by assigning to the onmouseover and onmouseout properties of the Element instance for the span, e.g.:

// Define your handler somewhere
function myNewHandler()
{
    // ...new logic...
}

// And where you want to swap it in:
document.getElementById('someSpan').onmouseover = myNewHandler;

...but this is a fairly old-fashioned way to do this. A more modern approach uses addEventListener or attachEvent (depending on whether you're doing standard or IE) to hook up event handlers. Libraries like Prototype, jQuery, and about a dozen others can help.

T.J. Crowder