0

Here is my code below I'm trying to hide addstuff id div when clicked out of it. I tried body click event but it was useless. So I need a trigger event like blur. But It doesn't work for both blur and focusout events.

$(document).ready(function() {
            $('#addstuff').blur(function () { $('#addstuff').fadeOut() })
 })
chridam
  • 100,957
  • 23
  • 236
  • 235
Serhat Koroglu
  • 1,263
  • 4
  • 19
  • 41

4 Answers4

2

There is no blur event for div. You can create that effect using the click event of body.Note that you should exclude that div from the click event

$(document).ready(function () {
    $("body").not("#addstuff").click(function (e) {
        $("#addstuff").fadeOut();
    });
});

Fiddle

Edit

As @TrueBlueAussie suggested, it would be better to use document instead of 'body' for the click event handler:

   $(document).not("#addstuff").click(function (e) {
       $("#addstuff").fadeOut();
   });
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
  • You might want to attach click to `document` and not `'body'` as `body` can have weird side-effects with click (absolute position elements can cause a zero-height body that does not accept clicks on some browsers) – iCollect.it Ltd Jun 18 '14 at 08:40
  • @TrueBlueAussie Thanks for the suggetion. I'll edit the answer – Anoop Joshi P Jun 18 '14 at 08:41
1

There's no way you can use .blur with a div, it has to be with some input field.

You can always use mouse events like

$(document).ready(function(){
  $("#addstuff").mouseleave(function(){
    $(this).remove();
  });
});

http://jsfiddle.net/asrF2/

You can also use the HTML5 global attribute contenteditable (don't forget to set it true or false)

<div id="#addstuf" contenteditable="true">bla bla</div>

I don't recommend this that much, because of mobile browsers' compatibility.

Frondor
  • 3,466
  • 33
  • 45
0

divs have no focus and blur events, but you can add a contenteditable attribute so that you can type in that div, so the blur actually gets fired:

<div id="addstuff" contenteditable></div>        

Then your jquery code works.

You can add additional functions to prevent people from actually typing in that div.

Alternatively you can use the .mouseleave() or .mouseout() event.

Alex
  • 9,911
  • 5
  • 33
  • 52
0

div element cannot be focused on so the blur function of jquery cannot be applied to it. See existing answers from our Stack Exchange buddies below for elements that focus can be applied on.

Which HTML elements can receive focus?

Community
  • 1
  • 1