‹div› and ‹span› in JavaScript

In JavaScript, neither dynamic HTML nor document.write() does work with string of entire ‹div› section. However, it is essential part of Dynamic HTML.

How to dynamically create a Div section in JavaScript? Follow is the codes from Toolbox for IT, edited by Smifis:

var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
if (width) {
newdiv.style.width = 300;
}
if (height) {
newdiv.style.height = 300;
}
if ((left || top) || (left && top)) {
newdiv.style.position = "absolute";
if (left) {
newdiv.style.left = left;
}
if (top) {
newdiv.style.top = top;
}
}
newdiv.style.background = "#00C";
newdiv.style.border = "4px solid #000";
if (html) {
newdiv.innerHTML = html;
} else {
newdiv.innerHTML = "nothing";
}
document.body.appendChild(newdiv);

Actually, there are two parts of it. The first part as listed above, which more or less like an defination. And the second part is to present the result. Esential scripts in 2nd part are:

; var painting = document.getElementById(id)
; painting.style.visibility = 'visible'
; if (content) painting.innerHTML = content

In addtion, you can move these arguable variable from first part to second part for dynamic purpose, such like x, y, width, height, background etc. What is suggested is to separate them into two functions:

; function drawFrame(frameId, posiType, borderPro, rightPro, bottomPro, bgc, classNam)
{ ; var newdiv = document.createElement('div')
; newdiv.setAttribute('id', frameId)
; newdiv.style.position = posiType
; if (bgc) newdiv.style.background = bgc
; if (borderPro) newdiv.style.border = borderPro
else
{ ; if (rightPro) newdiv.style.borderRight = rightPro
; if (bottomPro) newdiv.style.borderBottom = bottomPro
}
; newdiv.style.visibility = 'hidden'
; if (classNam) newdiv.setAttribute("class", classNam)
; document.body.appendChild(newdiv)
}

; function showFrame(frameId, wid, hei, xPos, yPos, content)
{ ; var painting = document.getElementById(frameId)
; if (0!=wid) painting.style.width = wid + 'px'
; if (0!=hei) painting.style.height = hei + 'px'
; painting.style.left = xPos + 'px'
; painting.style.top = yPos + 'px'
; painting.style.visibility = 'visible'
; if (content) painting.innerHTML = content
; return painting
}

Beware, you will need a "canvas" to draw the div section, such as body of HTML, or wondow.onload in JavaScript file.


http://it.toolbox.com/wiki/index.php/Dynamically_Creating_a_Div_in_Javascript

No comments:

Post a Comment

Labels