Tuesday, April 3, 2012

DOM Introduction Slides

Today we covered javascript DOM in the class, here is the slide we used today.

Monday, April 2, 2012

jQuery how to scroll to particular line in textarea

Recently I was working with outputting formatted source code in a textarea, and the requirement is you have a control "sidebar", which is a list, that allow user to click on and the textarea will scroll to particular line accordingly.

In jQuery, when you use the below. the textarea will scroll to the top

$('.my_class_for_this_textarea').animate({ scrollTop: 0 });

However, in my case, the sidebar list only tells you the code is in line 100 for example.  How to make sure you tell jQuery to scroll to the correct line every time??

scrollTop  takes "pixels", and you need to find out your pixel of each line is. And the following is the formular.

$('.my_class_for_this_textarea').animate({
  scrollTop: my_relative_line_number * LINE_PIXEL
}); 

The correct way to get mouse coordinates

I still saw some developers try to use different formular / ways to find out the mouse coordinates.  Well, according to the documentation, there is always only one correct cross-browser way to find out the real mouse coordinates   relative to the browser.   (  Note: mouse coordinates relative to your computer screen is not very useful for most of our cases, so the below is mouse coordinates relative to browser. )

Here is how the recommended implementation looks like :)
function myCallBack(e) {
 var posx = 0;
 var posy = 0;
 if (!e) var e = window.event;
 if (e.pageX || e.pageY)  {
  posx = e.pageX;
  posy = e.pageY;
 }
 else if (e.clientX || e.clientY)  {
  posx = e.clientX + document.body.scrollLeft
   + document.documentElement.scrollLeft;
  posy = e.clientY + document.body.scrollTop
   + document.documentElement.scrollTop;
 }
 // posx and posy contain the mouse position relative to the document
}