-2

How to stop the Jquery effect when i move my mouse or pressing a key from Keyboard any suggestions will be appreciated.

function dream(){
    //calculating random color of dream
    var color = 'rgb(' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ')';

    //calculating random X position
    var x = Math.floor(Math.random() * $(window).width());

    //calculating random Y position
    var y = Math.floor(Math.random() * $(window).height());

    //creating the dream and hide
    drawingpix = $('<span>').attr({ class: 'drawingpix' }).hide();

    //appending it to body
    $(document.body).append(drawingpix);

    //styling dream.. filling colors.. positioning.. showing.. growing..fading
    drawingpix.css({
        'background-color':color,
        'border-radius':'100px',
        '-moz-border-radius': '100px',
        '-webkit-border-radius': '100px',
        top: y-14,    //offsets
        left: x-14 //offsets
    }).show().animate({
        height:'500px',
        width:'500px',
        'border-radius':'500px',
        '-moz-border-radius': '500px',
        '-webkit-border-radius': '500px',
        opacity: 0.1,
        top: y-250,    //offsets
        left: x-250
    }, 3000).fadeOut(2000);

    //Every dream's end starts a new dream
    window.setTimeout('dream()',200);
}

$(document).ready(function() {  
    //calling the first dream
    dream();
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

3

stop says that it stops the propogation of animation on the matched elements.

If you want to stop the animation then find it and call stop() on it like this:

$("span").on("keypress", function() {
    $(this).stop(true, true);
});

Add a second event capture for the mouse and you should see the animations stop.

You will have to play with the selector to capture exactly which objects are being animated. I'm not sure if the keypress will be captured on the span or if you'll need to be more generic / broad in your specific situation.

To stop generating new instances of the dream, you'll need to call clearTimeout(). Here is a great explanation for how that is used.

Update: Here is a jsfiddle that displays some of these ideas when concerning mouseover. Hovering over the circle that is created dynamically (which is why you have to capture the event by using on) will stop the current animation and clear the setTimeout that was created. You should be able to take these ideas and manipulate them to generate the behavior you're looking for.

Community
  • 1
  • 1
veeTrain
  • 2,915
  • 2
  • 26
  • 43