Tag - javascript

Entries feed

Thursday 26 August 2010

Allow the insertion of tabulations in a textarea

When you press tab in a textarea of a web page, it looses focus and no actual tabulation is inserted. You can bypass this behavior with some Javascript. It is very useful for typing code for instance.

Let's say your textarea is identified with an id :

1
2
3
<form>
<textarea id="textarea"></textarea>
</form>

I took the following script from Wikini, hence it is licensed under GNU GPL. The original script had a very annoying bug : when you typed a tab, it was inserted, but the textarea scrolled the text to its top. I corrected it by storing the scroll position before the insertion and by restoring it after.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* Original code taken from Wikini <http://www.wikini.net/>, licensed under GNU GPL */
 
document.getElementById("textarea").onkeydown=textareaKeyDown;
 
function textareaKeyDown(e) {
  if (e == null) e = event;
    if (e.keyCode == 9) {
 
      var scrollTop = this.scrollTop;
      var scrollLeft = this.scrollLeft;
 
      if (typeof(document["selection"]) != "undefined") { // ie
        e.returnValue = false;
        document.selection.createRange().text = String.fromCharCode(9);
      } else if (typeof(this["setSelectionRange"]) != "undefined") {  // other
        var start = this.selectionStart;
        this.value = this.value.substring(0, start) + String.fromCharCode(9)
         + this.value.substring(this.selectionEnd);
        this.setSelectionRange(start + 1, start + 1);
      }
 
      this.scrollTop = scrollTop;
      this.scrollLeft = scrollLeft;
 
      return false;
    }
    return true;
  }
}

Friday 30 July 2010

Google API v3 fit map zoom and bounds to all markers

Here is a code snippet to make Google maps API v3 to fit the view to all your markers. There is a lot of similar functions on the Internet, but they're all for the old API v2 which is sensibly different.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//set up the map
function initMap()
{
  var myOptions = {
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("mapCanvas"), myOptions);
}
 
//set up your markers
function initMarkers()
{
  //...
}
 
var map;
var bound = new google.maps.LatLngBounds();
var markers = new Array();
 
//jQuery style entry point, change if necessary
$(document).ready(function(){
  initMap();
  initMarkers();
 
  for(var i in markers)
  {
    bound.extend(markers[i].getPosition());
  }
  map.fitBounds(bound);
});