2

I have a div with tabindex attribute set to '-1' so it can gain focus on mouse click.

<div tabindex='-1'></div>

.div:focus{//some style}

I want to do something with Jquery when the user clicks the div but only if it is selected (after second click).

$('div').click(function(){
if($(this).is(':focus')){
//do something
}
});

But it doesn't work, the action is immediately triggered.

EDIT: Code included.

olanod
  • 30,306
  • 7
  • 46
  • 75

2 Answers2

2

From what I've read, perhaps you can call the "click" action once you have focused on the DIV. First click focuses it, second click triggers the next block.

** EDIT ** After research you cannot use the focus handler on the DIV. What was I thinking!

*$('.double-click').focus(function(){
     alert("I'm now in focus");
     $(this).click(function(){
          alert("I'm now double clicked.");
     });
});*

** This is untested code.

I also looked around jQuery's API and noticed a dblclick() function you can see here... http://api.jquery.com/dblclick/

wwwroth
  • 434
  • 1
  • 5
  • 21
  • Scratch that. It turns out you cannot "focus" on DIV's. Try working with the dblclick() function. – wwwroth Dec 31 '11 at 18:25
2

I would check the 2nd click with a flag, see my answer here

  1. I used a flag isClicked to determine if it the 1st click or 2nd. If it is 1st click, set the flag to true and return ((i.e) do nothing). Next time, the flag is checked for true which means it is 2nd click, and the add code below to do what you want.

    var isClicked = false;
    
     $('div#myTest').click(function(){
    
     //do nothing on 1st click
     if (isClicked == false) {
        alert('Clicked 1st time');     
        isClicked = true;
        return;
     }
    
     //do whatever u want on second click    
     alert('Clicked 2nd time');     
    
     });
    
  2. Reset the flag when it is clicked outside the div, the below code does that...

    // to check it is clicked outside div
     $(document).click(function(e){
      if($(e.target).is('#myTest'))return;    
    
      //reset to
      isClicked = false;
    
     });
    
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134