Scrolling to page element in JavaScript

One major issue i found in user experience is putting focus onto a new area, popped out almost out of nowhere, without bulling the user, but in the mean time letting him now an event occurred.

I needed to do this when inserting a new row in a large table, somewhere way bellow or on top of the visible area of the table. I had to let the user know he inserted a new row and also point that row to him (it was actually about inserting a manual invoice in a large list of invoices).

We need to do 2 things:

  1. Compute the position of the element we want to focus
  2. Smooth and easily scroll to that element and why not change the style (background-color, font-weight) for 3 seconds or so. Maybe blink it, just maybe. Don’t want to get too Vegas-style 😀

jquery_elem_list is a list of jQuery nodes, as resulted by applying a selector. This could be rewritten as a jQuery plugin.

blink = function(jquery_elem_list, scroll_to_it){
  if (scroll_to_it == undefined)
    scroll_to_it = false;
  var blink_times = [0, 500, 1000, 1500, 2000, 2500];
  var effect = function(){jquery_elem_list.addClass('hover');};
  var noEffect = function(){jquery_elem_list.removeClass('hover');};
 
  var i;
  for(i in blink_times){
    if (i%2)
      window.setTimeout(noEffect, blink_times[i]);
    else
      window.setTimeout(effect, blink_times[i]);
  }
 
  // Scroll to first element if not in window port:
  if (scroll_to_it){
    var top = jQuery(window).scrollTop();
    var bottom = top + jQuery(window).height();
    var x = jQuery(jquery_elem_list[0]).position()['top'];
    if (x > bottom || x < top){
      jQuery("html, body").animate({'scrollTop': (x + (bottom - top)/2)}, 1000);
    }
  }
};

I’m open to discussion and other solutions.