9

Hi i have a div of a form. i want that disable click event when mouse is out of the div. So i tried this but it is not working ot of div is still clickable. Any idea??

var flag = false;
$("#foo").live("mouseenter",function(){
    flag = true;
}).live("mouseleave",function(){
    flag = false;
})

$(document).click(function(){
    if(!flag)
         return false;
});
Sedat Başar
  • 3,740
  • 3
  • 25
  • 28

3 Answers3

6

You cannot prevent the click event being fired from the whole document. You can do it per element basis. You can probably block the whole screen using a absolute positioned transparent(low opacity) div and hide it again once the div is visible.

var $body = $(document.body);
var $div = $("<div id='dummyDiv'/>").hide().appendTo($body);
$div.css({position:"absolute", height: $body.height(), width: $body.width(), background: "#000", opacity: 0.5}).show(100);

//to hide it
$("#dummyDiv").hide(100);
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • You can prevent the click event being fired from the whole document: http://stackoverflow.com/a/8596014/931358 – Jurik Oct 02 '13 at 17:00
  • +1 for simplicity. Adding an overlay makes the problem of click event handling irrelevant. – Adriano Sep 10 '14 at 13:11
1
$("#foo").live("mouseenter",function(){
    $(document).bind('click', onDocumentClick);
}).live("mouseleave",function(){
    $(document.unbind('click');
});

function onDocumentClick(e){

};

I think you want the click on #foo instead of document, if so you can simply do this:

$('#foo').click(function(){

});

Since you have to be rolled over an element to click on it this will work fine.

locrizak
  • 12,192
  • 12
  • 60
  • 80
0

istead of using return false, use e.preventDefault http://css-tricks.com/6809-return-false-and-prevent-default/

Thiago
  • 1,547
  • 3
  • 25
  • 40
  • 3
    @locrizak - they do *not* do the same thing, not at all. One prevents the default action, one stops the event dead in it's tracks, stopping propagation as well. Saying they're the same is entirely incorrect. – Nick Craver Jul 12 '11 at 14:12