Valentincognito Valentincognito - 7 months ago 22
Javascript Question

jQuery prevent onmouseover events

I have been searching for a while now but no results yet.. I have multiple mouseover events with animations. So I would like to be able to disable mouseover events to occur if there are still other animations running..

I have been playing with

jQuery.stop()
a lot but impossible to make it work. I am actually not sure where to put this code within my function..

Here is my html with a map:

<img src="assets/menu588x588.png" alt="" usemap="#map" />
<map id="map" name="map">
<area onmouseover="driveTo(330);" shape="poly" coords="93, 264, 2, 270, 7" />
<area onmouseover="driveTo(300);" shape="poly" coords="122, 336, 101, 390" />
<area onmouseover="driveTo(230);" shape="poly" coords="370, 335, 446, 388, 3574" />
</map>


And my JS function with some timeout and animation:

function driveTo(new_position){
$(function() {
var pre_position = Number(document.getElementById("pre-position").value);
var goal = 360 - pre_position + new_position;
var $elem = $(".car-box"), degree = pre_position, timer;

rotate(goal);

function rotate(goal) {
$elem.css({ 'transform': 'rotate(' + degree + 'deg)'});

if(new_position < pre_position){
if(goal > 0){
timer = setTimeout(function() {
--goal;
++degree;
rotate(goal);
},5);
}
if(goal === 0){
document.getElementById("pre-position").value = new_position;
}
}
}
});
}


I'm afraid to be a bit lost inside all those inner functions..

Thank you very much in advance for any piece of advice !

Answer

Try this one:

var inProgress = false;
function driveTo(new_position){

    if(inProgress){
        return;
    }


    $(function() {
        inProgress = true;

        var pre_position   = Number(document.getElementById("pre-position").value);
        var goal           = 360 - pre_position + new_position;
        var $elem          = $(".car-box"), degree = pre_position, timer;

        rotate(goal);

        function rotate(goal) {
            $elem.css({ 'transform': 'rotate(' + degree + 'deg)'});

            if(new_position < pre_position){

                if(goal > 0){
                    timer = setTimeout(function() {
                        --goal;
                        ++degree;
                        rotate(goal);
                    },5);
                }
                if(goal === 0){
                    document.getElementById("pre-position").value = new_position;
                    inProgress = false;
                }
            }
        }
    });
}