First of all, let me apologize if my question is not formulated correctly - I am not a professional coder, so my terminology can be strange. Hope my code is not too confusing :(
I have a method fade()that fades an image back and forth using a rollover mouse. I would like to use a wrapper object (I think this is the right term) to hold the image element and some required properties, but I don't know how to do this. fade()called from HTML and designed to be deleted on the page without additional configuration (so that I can easily add new fading images to any HTML code):
<div id="obj" onmouseover="fade('obj', 1);" onmouseout="fade('obj', 0);">
The method fade(obj, flag)launches SetInterval, which fades in the image, and when the pointer is removed, the interval is cleared and a new SetInterval is created to fade the image. To save the state of opacity, I added a few object properties: obj.opacity, obj.upTimerand obj.dnTimer.
Everything works fine, but I don’t like the idea of adding properties to HTML elements, because this may lead to a future situation when some other method overwrites these properties. Ideally, I think that a wrapper object should be involved, but I don’t know how to do this without adding code to create the object when the page loads. If anyone has any suggestions, I would really appreciate it!
Here is my fader method:
var DELTA = 0.05;
function fade(id, flag) {
var element = document.getElementById(id);
var setCmd = "newOpacity('" + id + "', " + flag + ")";
if (!element.upTimer) {
element.upTimer = "";
element.dnTimer = "";
}
if (flag) {
clearInterval(element.dnTimer);
element.upTimer = window.setInterval(setCmd, 10);
} else {
clearInterval(element.upTimer);
element.dnTimer = window.setInterval(setCmd, 10);
}
}
function newOpacity(id, flag) {
var element = document.getElementById(id);
if (!element.opacity) {
element.opacity = 0;
element.modifier = DELTA;
}
if (flag) {
clearInterval(element.dnTimer)
element.opacity += element.modifier;
element.modifier += DELTA;
if (element.opacity > 100) {
element.opacity = 100;
element.modifier = DELTA;
return;
}
element.opacity = Math.ceil(element.opacity);
} else {
clearInterval(element.upTimer)
element.opacity -= element.modifier;
element.modifier += DELTA;
if (element.opacity < 0) {
element.opacity = 0;
element.modifier = DELTA;
return;
}
element.opacity =
Math.floor(element.opacity);
}
setStyle(id);
}
function setStyle(id) {
var opacity = document.getElementById(id).opacity;
with (document.getElementById(id)) {
style.opacity = (opacity / 100);
style.MozOpacity = (opacity / 100);
style.KhtmlOpacity = (opacity / 100);
style.filter = "alpha(opacity=" + opacity + ")";
}
}
source
share