Creating an element and attaching it dynamically to the DOM - creating dynamic html

I'm Karsten and I want to help people learn German.
Buy me a coffee if you feel I did well.

Creating an element and appending it to the DOM - dynamic html - the principle

Scroll down to see the bar appear.

creating an element and appending it to the DOM, how to create a dynamic sliding bar

This is the first version of the bar. In it only a link is added dynamically. The most important code is this:

var timeout1 = setTimeout(function(){wider(dynamic,1)},10);
var timeout2 = setTimeout(function(){wider(dynamic,2)},20);
var timeout3 = setTimeout(function(){wider(dynamic,3)},30);
var timeout4 = setTimeout(function(){wider(dynamic,4)},40);
var timeout5 = setTimeout(function(){wider(dynamic,5)},50);
var timeout6 = setTimeout(function(){wider(dynamic,6)},60);
var timeout7 = setTimeout(function(){wider(dynamic,7)},70);
var timeout8 = setTimeout(function(){wider(dynamic,8)},80);
var timeout9 = setTimeout(function(){wider(dynamic,9)},90);
var timeout10 = setTimeout(function(){wider(dynamic,10)},90);

Because it was too long to write it down 49 times I looped it:

for (i = 1; i<=50; ++i){ eval ("var timeout"+i+"=setTimeout (function(){wider(dynamic,"+i+")},"+i*10+");"); }

I had the problem of having to define variables on the fly (dynamically). That is why I used eval. It is not supposed to be good style. But who cares about stylish coding when this is the one thing that does the dirty job? You pass a string to the eval command. The eval command then evaluates it, i.e. it turns text into code. Programming in plain text and eval-ing it makes it easy to create 49 variables, by just incrementing the variable "i" and appending it to the text ("+i+").

The whole code proceeds in the following fashion: First the user has to scroll to the middle of the page. If the user scrolls, the function "popup_while_happily_scrolling ()" is called. Then if the condition is met (user in middle of page) "popup_while_happily_scrolling ()" calls "say_hi ()". "say_hi ()" creates the dynamic element and tags it with the id="dynamic". Having given the tag (a div tag) an id, you can get hold of it to manipulate it. This is the job of the function "grow()", which is also called by "popup_while_happily_scrolling ()". The function "grow()" calls "wider (htmlid, factor)". To this function the div is passed as a DOM object together with the factor. Grow calls wider 49 times. The factor is the amount of pixels for the "top" attribute of the div, and in each call factor is incremented by 1 so that the bar grows. The timeouts create the illusion of a slide or ease-in effect.

submit to reddit

Sneak peek of the server side code