user299709
user299709

Reputation: 5412

jquery: stop infinite recursion?

How do I stop the infinite recursion here so that a mousedown event can be triggered just once? should it be in a separate method?

$(document).on('mouseover',function (e) {
            $(e.target).mousedown(function(e){
                e.stopPropagation();
                console.log('clicked');
                $(e.target).trigger('mousedown'); //use hello(e); instead?
                return;
            })
});

$(document).on('mousedown', 'a', function(e){
  hello(e);
});

function hello(e){
console.log('got it');
}

This seems to trigger a never ending loop. Basically I need to bind a mousedown handler on the currently element under the mouse, which will fire a mousedown event that another handler will be able to handle.

The reason I am doing this is because the mouseover works on dynamically generated element so when this happens I need to bind a handler again as the on handler is not able to catch the newly generated element.

Upvotes: 2

Views: 579

Answers (2)

agentpx
agentpx

Reputation: 1081

You are making it complicated. Imagine everytime a user move his mouse an event will be added dynamically?

Why not design your element with class names and use it in your mousedown event? This way a sure call to mousedown will trigger always.

 $(".className").mousedown(function(e){
            console.log('clicked');
            return;
 })

--The reason I am doing this is because the mouseover works on dynamically generated element so when this happens I need to bind a handler again as the on handler is not able to catch the newly generated element.

If you say so then, add a className to your dynamically generated element to have your mousedown event bind to it.

Upvotes: 1

Suchit kumar
Suchit kumar

Reputation: 11859

try like this:

 $(document).on('mouseover',function (e) {
                $(e.target).trigger('mousedown'); //use hello(e); instead?
                return;
    
});

 $(document).on('mousedown','a', function(e){
	  hello(e);
	});

function hello(e){
alert('got it');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">hello</a>

Upvotes: 0

Related Questions