Aaron Lee Aaron Lee - 2 months ago 11
HTML Question

jQuery addClass & animations

Great people of StackOverflow, save my ass please :)

I've been trying to get this to work for a while now, i've read the documentation repeatadly, tried lots of stupid things, and now the more I look at it and think my mind goes blank, so if someone could shed some light i'd be grateful. I'm trying to get the jQuery to animate the addClass command. It works fine, adds and removes the class to the element no problem, but I want it to fadeIn the class and then fadeOut the class, here's the code:

<script type="text/javascript">
function addingClasses(id,myClass) {
$(id).addClass(myClass).animate({
show: 'fadeIn',
speed: '2000',
hide: 'fadeOut'
});
}

function removingClasses(id,myClass) {
$(id).removeClass(myClass);
}
</script>

<div id="about" class="sittingPretty" onmouseover="addingClasses(this, 'aboutHover')" onmouseout="removingClasses(this, 'aboutHover')">
<p>About</p>
</div>


If someone could help, i'd be extremely grateful, thanks again guys :)

Answer

What you want to do is set a var and transform to that value.

a short example would be:

<script type="text/javascript">
    function addingClasses(id,myClass) {
        var newValue = { opacity : 100 }
        $(id).addClass(myClass).animate(newValue, 1000);  
    }
    function removingClasses(id,myClass) {
        var newValue = { opacity : 0 }
        $(id).removeClass(myClass).animate(newValue, 1000);
    }
</script>

This will gradually alter the opacity from whatever it currently is to the value you pass it.

Its not the best method but it will work :)

Comments