Reputation: 5175
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?
Upvotes: 6
Views: 16099
Reputation: 1074188
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.
Upvotes: 1
Reputation: 332
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.
Upvotes: 1
Reputation:
Code:
document.getElementById("someSpan").onmouseover = function()
{
//New code
};//Do not forget the semicolon
Upvotes: 0
Reputation: 101330
Sure.
document.getElementById('someSpan').onmouseover =
function() {
this.className='newactive';
};
Upvotes: 5
Reputation: 83011
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.
Upvotes: 1