Search code examples
jquerytextareaparentaddclasstoggleclass

Add class to parent div when textarea clicked or focused?


How to add a class to the textarea's parent div when clicked or focused?

$(document).ready(function () {  
$('textarea').toggleClass(function() {
  if ($(this).parent().is('.expandingArea')) {
    return $(this).parent().addClass('open');
  } else {
    return $(this).parent().removeClass('open');
  }
});
});

Solution

  • You can just use focus and blur to get this functionality.

    $('textarea').focus( function() {
      $(this).parent().addClass('open');
    });
    
    $('textarea').blur( function() {
     $(this).parent().removeClass('open');
    });
    

    DEMO

    Another One