Ok, thanks to everybody for comments. Actually trying to add the example to jsfiddle helped to find the problem. The page was running ok on jsfiddle and when comparing the jsfiddle source code with the original, I found the problem

The code snippets posted above are ok, the problem was in the (missing) first row. After adding 

    "<!DOCTYPE html>" 

in the beginning of the page, the mysterious behavoiur ended.