Trevan Hetzel
Trevan Hetzel

Reputation: 1369

jQuery blur except certain element

I've set up a jsFiddle here, code below.

I just have a textarea that gets a class added to it on focus and on blur it gets removed. The class makes the textarea extend by setting a height css attribute, so when you click the button to submit the form I don't want it to remove the class because it just seems awkward.

HTML

<div class="comment_display">
    <form>
        <textarea class="addcomment"></textarea>
        <input class="tagbtn" type="submit" value="Comment" />
    </form>            
</div>​

CSS

.addcommentOn {
    height: 100px;
}​

Javascript

// Lengthen the Discussion input on click
  $(function lengthenInput() {
    $(".addcomment").focus(function() {
        $(this).addClass("addcommentOn");
    });

    $(".addcomment").blur(function() {
        if ($("input.comment").data('clicked') != true) {
            $(this).removeClass("addcommentOn");
        }
    });
  });​

Upvotes: 3

Views: 3902

Answers (3)

abc
abc

Reputation: 1

https://i.sstatic.net/2qfhd.jpg

That error is raising because of the event propagation caused from the child. Just prevent it. That error is raising because of the event propagation caused from the child. Just prevent it. That error is raising because of the event propagation caused from the child. Just prevent it.

Upvotes: -1

pmrotule
pmrotule

Reputation: 9692

Charlietfl's answer is good, but there are still two other ways a blur event can be called: if you go to another tab in your browser or if you hit tab to go to the next input. You can see my solution and code snippet here:

https://stackoverflow.com/a/32596535/1895428

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

Trying to fight with blur is not easy since it occurs prior to any mouse event on another element

Here's one concept that would need additional modification if you want the textarea to shrink when user leaves form. Replace blur handler with following:

$('form').on('click', function(evt) {
    var $tgt = $(evt.target);
     if ($tgt.is('input[type="submit"]') || $tgt.is('.addcommentOn')  ) {
          return;
      }else{
           $('.addcommentOn').not($tgt).removeClass("addcommentOn");
      }
})

EDIT: need to also modify focus handler a bit once more elements added to form:

 $(".addcomment").focus(function() {
    $('.addcommentOn').removeClass('addcommentOn');
    $(this).addClass("addcommentOn");

});

DEMO(updated): http://jsfiddle.net/GzmrS/38/

Upvotes: 3

Related Questions