JavaScript
Article

jQuery get element with current focus

By Sam Deering

jQuery code snippet to get element with current focus and perform AJAX auto save once it looses focus.

//get active element of focus using js
$(document.activeElement)
//change focus when tabbed across into new item
$('.item :input').live('focus', function()
{
  var thisItem = $(this).parents('.item');
  var thisId = thisItem.attr('id');
  $('.item').removeClass('item-selected'); //remove all focus
  thisItem.addClass('item-selected');  //add focus to current item

  //save those items that have changed
  $.each($('.item-changed'), function(i,v)
  {
      var currItemId = $(this).attr('id');
      //exclude current item
      if (!_this.helpers.itemHasFocus(currItemId))
      {
         console.log('saving '+currItemId);
         _this.save.item(currItemId); /* AJAX auto save */
         $(this).removeClass('item-changed');
      }
  });
});

No Reader comments

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.