Serhat Koroglu
Serhat Koroglu

Reputation: 1259

Blur event not works for div

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() })
 })

Upvotes: 0

Views: 1471

Answers (4)

CCCanafranca
CCCanafranca

Reputation: 26

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?

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

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();
   });

Upvotes: 2

Frondor
Frondor

Reputation: 3466

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.

Upvotes: 1

Alex
Alex

Reputation: 10216

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.

Upvotes: 0

Related Questions