user1451032
user1451032

Reputation: 3

jQuery mousedown + mouseleave

i'm a begginer currently building a simple jQuery script where i'd like my action to happen when I drag out of its bounds. So i was thinking on detecting a mousedown and inside its function have a mouseleave.

But what happens is not what i'm expecting since everytime i pass my mouse over it - no need to click, the event gets triggered.

Here's the code i've put toghether.

 $(document).ready(function() {
   $(".box").mousedown(function() {
     $(".box").mouseleave(function() {
       alert("Hello world!");
     });
   });
 });

Help much appreciated, thanx!

Upvotes: 0

Views: 1220

Answers (3)

xPheRe
xPheRe

Reputation: 2343

Just unbind the event after it's triggered:

$(".box").mousedown(function() {
    $(this).mouseleave(function(){
        $(this).unbind('mouseleave');
        alert("Hello world!");
    })
})

Upvotes: 0

Jonathan Nicol
Jonathan Nicol

Reputation: 3298

Try this:

$(document).ready(function() {
    $(".box").mousedown(function() {
        $('.box').addClass('clicked');
    });
    $(".box").mouseleave(function() {
        if ($(this).hasClass('clicked')){
            $(this).removeClass('clicked');
            alert("Hello world!");
        }
     });
 });

The mouseleave will only continue if .box has the CSS class clicked, and will then remove the class, stopping the mouseleave from being triggered again.

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

   $(".box").mousedown(function() {
     alert('mousedown');
     $(this).addClass('imclicked');
   }).mouseleave(function() {
       if($(this).hasClass('imclicked')) {
         alert("Hello world!");
         $(this).removeClass('imclicked');
       }
   });;

Upvotes: 1

Related Questions