Frage

My Problem is when mousedown event occurs in right button i need to check whether there is any div if not then my flag global variable becomes false but i am not getting that condition.

My jQuery script is as follow.

var flag = true;
   $(document).mousedown(function(event){
            if( event.button == 2 ) {
                if ($(event.target).parent().is('.draggable')){
                    $el = $(event.target).parent();
                    flag = true;    
                }else{
                 flag = false;          
            }   
        }
    });

jsp code:

<div class="main">    
<div class="draggable" >
        <a href="#"><div class="inside"></div></a>

    </div>
</div>
War es hilfreich?

Lösung

Try with this I think there is need of one more parent. Hope it will work. Since I was stuck with same problem few months ago.

$(document).mousedown(function(event){
                if( event.button == 2 ) {
                    if ($(event.target).parent().parent().is('.draggable')){
                        $el = $(event.target).parent().parent();
                        flag = true;    
                    }else{
                     flag = false;          
                }   
            }
        });

Andere Tipps

I think what you need is using closest() method since the structure may be different sometimes

So your code could be like

$('mousedown',function(event){
    var $draggable;
    if( event.which == 2 ) {
        $dragable = $(event.target).closest('.draggable');
        if ($dragable.length){
            $el = $dragable;
            flag = true;    
         }else{
             flag = false;          
         }   
    }
});

Note that event.which also normalizes button presses (mousedown and mouseupevents), reporting 1 for left button, 2 for middle, and 3 for right. Use event.which instead of event.button

EDIT

Using parent method means that there will always exist exactly two ancestors in between. Relying on strict structures leads to rigidity and bug prone code. IMO, using closest method in place of parent for such a case is a better approach.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top