How to create element with absolute position - javascript

I want Date to appear above Second section. plz guide how to achieve it
var sectionTwo = document.getElementById("sectionTwo");
var x = sectionTwo.getBoundingClientRect();
var b = document.createElement("div");
b.style.position = 'fixed';
b.innerHTML = new Date();
document.body.appendChild(b);
b.style.top = (x.top - b.style.height) + 'px';
enter image description here

One way to do it is like this:
HTML code:
<div id="sectionTwo">
</div>
JS code:
var sectionTwo = document.getElementById("sectionTwo");
var b = document.createElement("div");
b.innerHTML = new Date();
sectionTwo.insertAdjacentElement("beforebegin", b);
CSS code (just to for visualization):
#sectionTwo {
width: 80%;
height: 50px;
background-color: gray;
}

<div>
<div style="height:800px;"></div>
<div id="sectionOne">First Section</div>
<div id="sectionTwo">Second Section</div>
<button onclick="showDate();">toggle</button></div>
<script> function showDate() {
var sectionTwo = document.getElementById("sectionTwo");
var x = sectionTwo.getBoundingClientRect();
var b = document.createElement("div");
b.style.position = 'absolute';
b.innerHTML = new Date();
document.body.appendChild(b);
b.style.bottom = 0;
b.style.top = (x.top - b.offsetHeight) + 'px';
}</script>
enter image description here

Maybe this could help you better.
var sectionTwo = document.getElementById("sectionTwo");
var b = document.createElement("div");
b.innerHTML = new Date();
sectionTwo.insertAdjacentElement("beforebegin", b);
#sectionTwo {
height: 35px; width:35px;
background-color: pink;
}
<div id="sectionTwo">
</div>

Related

Trying to generate 100 boxes but only 2 boxes are displayed?

So I'm only using javascript, html, and css to generate 100 boxes in any random position, this works by using the div with the id container in the html file and then using the javascript file to generate the boxes through a loop making a div for each box then appending it to the container, but the problem is I can see two boxes appearing on screen? here is my code below:
//this is the javascript
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.setAttribute("id", "box");
container.appendChild(box);//o
var bx = document.getElementById("box");
var w=window.innerWidth;
var h=window.innerHeight;
bx.style.right = w * Math.random() + "px";
bx.style.top = h * Math.random() + "px";
}
}
//here is the css
#box
{
background-color: blue;
width: 50px;
height: 50px;
padding: 5px;
position: fixed;
}
//this is the html
<!DOCUTYPE html>
<html lang = "en">
<head>
<link href = "box.css" rel = "stylesheet" type="text/css">
<script src = "box.js" type="text/javascript"></script>
</head>
<body onload="myFunction()">
<div id="container">
</div>
</body>
</html>
Don't get a reference for the box again from the DOM
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.setAttribute("id", "box");
container.appendChild(box);//o
// var bx = document.getElementById("box"); <--- this line is redundant
var w=window.innerWidth;
var h=window.innerHeight;
box.style.right = w * Math.random() + "px";
box.style.top = h * Math.random() + "px";
}
}
ID's should be unique, instead use a class for each box
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.classList.add("box");
container.appendChild(box);//o
var w=window.innerWidth;
var h=window.innerHeight;
box.style.right = w * Math.random() + "px";
box.style.top = h * Math.random() + "px";
}
}
So your code in the end becomes:
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.classList.add("box");
container.appendChild(box);//o
var w=window.innerWidth;
var h=window.innerHeight;
box.style.right = w * Math.random() + "px";
box.style.top = h * Math.random() + "px";
}
}
.box
{
background-color: blue;
width: 50px;
height: 50px;
padding: 5px;
position: fixed;
}
<!DOCTYPE html>
<html lang = "en">
<head>
<link href = "box.css" rel = "stylesheet" type="text/css">
<script src = "box.js" type="text/javascript"></script>
</head>
<body onload="myFunction()">
<div id="container">
</div>
</body>
</html>
Use the name attribute and a data-id attribute to retrieve any elements with an unique id.
Construction:
let container = document.getElementById("container")
for(let count = 1; count < 100; ++count) {
let box = document.createElement("DIV")
box.setAttribute("name", "e")
box.dataset.id = count
container.appendChild(box)
}
HTML result :
<div name="e" data-id="1"></div>
<div name="e" data-id="2"></div>
<div name="e" data-id="3"></div>
<div name="e" data-id="4"></div>
Add a function to retrieve any element with the first occurence of a numbered id.
function getFormRef(name, id) {
let d = document.getElementsByName(name)
let x = Array.prototype.slice.call(d).filter(a => a.dataset.id == id)
return x[0]
}
let first = getFormRef("e", 1)

CSS Font-size to maintain same word width

I'm trying to get the words "Hello", "Projects", "Social" and "Contact" to responsively adjust their font-size so that the words are all the same width rather than having to go in pixel by pixel.
I thought I was on to something with using viewport width but that isn't having the effect I'm after.
See image for the desired effect.
You may adjust font-size and also letter-spacing using vw unit
.title {
font-size: 15vw;
padding: 20px 0;
font-family: arial;
}
.title:first-child {
letter-spacing:5vw;
}
<div>
<div class="title">
Hello
</div>
<div class="title">
Projects
</div>
</div>
You can use JavaScript to wrap each letter in a span. Then you can use flexbox to distribute the spans evenly inside the p.
The words in the example below are inside a div with a fixed width in px. You can use other units as you need - %, vw etc
Example
const words = document.querySelectorAll('.tracking');
for (let i = 0; i < words.length; i++) {
const text = words[i].textContent.split('');
words[i].innerHTML = '';
text.forEach((letter, index) => {
const span = document.createElement('span');
const textnode = document.createTextNode(letter);
span.appendChild(textnode);
words[i].appendChild(span);
});
}
div {
width: 150px;
margin: 0 auto;
}
.tracking {
margin: 0;
padding: .5rem;
font-family: sans-serif;
font-weight: bold;
text-transform: uppercase;
color: #FFF;
display: flex;
justify-content: space-between;
}
div div:nth-of-type(1) {
background: red;
}
div div:nth-of-type(2) {
background: orange;
}
div div:nth-of-type(3) {
background: lightgrey;
}
div div:nth-of-type(4) {
background: black;
}
<div>
<div>
<p class="tracking">Hello</p>
</div>
<div>
<p class="tracking">Projects</p>
</div>
<div>
<p class="tracking">Social</p>
</div>
<div>
<p class="tracking">Contact</p>
</div>
</div>
var d = document.getElementById("master");
// set your margin... depends from font style
 var margin= 2;
 function font(){
var lett = document.getElementById("master").clientWidth;
setInterval(function(){font()},0)}
function getCount(matchResult) {
return matchResult ? matchResult.length : 0;
}
function alert(){
var pm = document.getElementById("master").querySelectorAll('*');
var num ;
for (num = 0; num < pm.length; num++){
var str = pm[num].textContent;
var countA = getCount(str.match(/A/g));
var countB = getCount(str.match(/B/g));
var countC = getCount(str.match(/C/g));
var countD = getCount(str.match(/D/g));
var countE = getCount(str.match(/E/g));
var countF = getCount(str.match(/F/g));
var countG = getCount(str.match(/G/g));
var countH = getCount(str.match(/H/g));
var countI = getCount(str.match(/I/g));
var countJ = getCount(str.match(/J/g));
var countK = getCount(str.match(/K/g));
var countL = getCount(str.match(/L/g));
var countM = getCount(str.match(/M/g));
var countN = getCount(str.match(/N/g));
var countO = getCount(str.match(/O/g));
var countP = getCount(str.match(/P/g));
var countQ = getCount(str.match(/Q/g));
var countR = getCount(str.match(/R/g));
var countS = getCount(str.match(/S/g));
var countT = getCount(str.match(/T/g));
var countU = getCount(str.match(/U/g));
var countV = getCount(str.match(/V/g));
var countW = getCount(str.match(/W/g));
var countX = getCount(str.match(/X/g));
var countY = getCount(str.match(/Y/g));
var countZ = getCount(str.match(/Z/g));
var counta = getCount(str.match(/a/g));
var countb = getCount(str.match(/b/g));
var countc = getCount(str.match(/c/g));
var countd = getCount(str.match(/d/g));
var counte = getCount(str.match(/e/g));
var countf = getCount(str.match(/f/g));
var countg = getCount(str.match(/g/g));
var counth = getCount(str.match(/h/g));
var counti = getCount(str.match(/i/g));
var countj = getCount(str.match(/j/g));
var countk = getCount(str.match(/k/g));
var countl = getCount(str.match(/l/g));
var countm = getCount(str.match(/m/g));
var countn = getCount(str.match(/n/g));
var counto = getCount(str.match(/o/g));
var countp = getCount(str.match(/p/g));
var countq = getCount(str.match(/q/g));
var countr = getCount(str.match(/r/g));
var counts = getCount(str.match(/s/g));
var countt = getCount(str.match(/t/g));
var countu = getCount(str.match(/u/g));
var countv = getCount(str.match(/v/g));
var countw = getCount(str.match(/w/g));
var countx = getCount(str.match(/x/g));
var county = getCount(str.match(/y/g));
var countz = getCount(str.match(/z/g));
var countspace = getCount(str.match(/ /g));
var groupa = 22*(counti+countj+countl);
var groupb = 28*(countI+countf+countt);
var groupc = 33*(countr);
var groupd = 50*(countJ+countc+countk+counts+countv+countx+county+countz);
var groupe = 56*(countL+counta+countb+countd+counte+countg+counth+countn+counto+countp+countq+countu);
var groupf = 61*(countF+countT+countZ);
var groupg = 67*(countA+countB+countE+countK+countP+countS+countV+countX+countY);
var grouph = 72*(countC+countD+countH+countN+countR+countU+countw);
var groupi = 78*(countG+countO+countQ);
var groupj = 83*(countM+countm);
var groupk = 94*(countW);
var groupl = 28*(countspace);
var totalsize = (groupa+groupb+groupc+groupd+groupe+groupf+groupg+grouph+groupi+groupj+groupk+groupl)/100;
var lett = pm[num].clientWidth;
var final = Math.floor(lett / totalsize) ;
pm[num].style.fontSize=final-margin+"px";
}
setInterval(function(){alert()},0)
}
window.onload = function(){
font();
alert();
}
div {text-align:center;
width:350px;
margin:0px;
padding:0px;}
p{
background-color:gray;
margin:0px;
padding:0px;
color:white}
.orange{
background-color:orange;}
.red{
background-color:red;}
<body>
<div id="master">
<p>Text using font-master.js </p>
<p>How simply is that </p>
<p class="orange">Hello</p>
<p class="red">Project</p>
</div>
</body>
you can use my js. plug in it is easy and free to use:
https://github.com/foxreaper/font-master
Text will fit to your div or sreen size... If you will have any issue let me know.

addEventListerner("click",function) - text will get appended to a div - but this does not work the second time around

Onclick dynamically created elements get added to list, but on the second click it does not work.
document.getElementById("add-comment").addEventListener("click",function(){
createComments();
});
function createComments(){
//append the new edit to comment list
var storeDiv = document.createElement("DIV");
var outerDiv = document.createElement("DIV");
var att = document.createAttribute("class");
att.value = "user-avatar-thumbnail left-position";
outerDiv.setAttributeNode(att);
var avatarImg = document.createElement("IMG");
avatarImg.src ="../1.jpg";
outerDiv.appendChild(avatarImg);
var attImg = document.createAttribute("class");
attImg.value = "left-position";
avatarImg.setAttributeNode(attImg);
var altAttr = document.createAttribute("alt");
altAttr.value = "avatar-thumbnail";
avatarImg.setAttributeNode(altAttr);
outerDiv.appendChild(avatarImg);
var avatarName = document.createElement("H5");
var avatarNameContent = document.createTextNode("Added newly");
var attImg = document.createAttribute("class");
attImg.value = "left-position";
avatarName.setAttributeNode(attImg);
avatarName.appendChild(avatarNameContent);
outerDiv.appendChild(avatarName);
var textRegion = document.createElement("TEXTAREA");
var textId = document.createAttribute("id");
textId.value = "comment-area";
textRegion.setAttributeNode(textId);
outerDiv.appendChild(textRegion);
var postCommentButton = document.createElement("BUTTON");
var postCommentButtonValue = document.createTextNode("Post");
postCommentButton.appendChild(postCommentButtonValue);
var createIDPost = document.createAttribute("id");
createIDPost.value="post-comment";
postCommentButton.setAttributeNode(createIDPost);
postCommentButton.appendChild(postCommentButtonValue);
postCommentButton.addEventListener("click",function(){
var commentsGiven = textRegion.value;
if (commentsGiven.length < 1){
alert("please enter your comment");
}
else {
document.getElementById("comment-section").appendChild(outerDiv);
document.getElementById("comment-section").style.display = "block";
document.getElementById("enter-comments").style.display = "none";
outerDiv.removeChild(cancelCommentButton);
outerDiv.removeChild(postCommentButton);
var commentPara = document.createElement("P");
commentPara.innerHTML = commentsGiven;
var attrComment = document.createAttribute("class");
attrComment.value = "left-position DescriptionExcerpt";
commentPara.setAttributeNode(attrComment);
outerDiv.appendChild(commentPara);
outerDiv.removeChild(textRegion);
}
});
outerDiv.appendChild(postCommentButton);
var cancelCommentButton = document.createElement("A");
cancelCommentButton.href = "#";
var createIDCancel = document.createAttribute("id");
createIDCancel.value="cancel-comment";
cancelCommentButton.setAttributeNode(createIDCancel);
var cancelCommentButtonValue = document.createTextNode("Cancel");
cancelCommentButton.appendChild(cancelCommentButtonValue);
outerDiv.appendChild(cancelCommentButton);
document.getElementById("enter-comments").appendChild(outerDiv);
};
#enter-comments, #comment-section {
border: dotted 1px #bfbfbf;
padding: 10px;
margin-top: 10px;
}
.user-avatar-thumbnail p{
background-color:#bfbfbf;
padding: 5px;
}
<div class="icon-details add-comments clearfix">
Add Comment...
</div>
<div id="enter-comments">
</div>
<div id="comment-section">
</div>
Here when you click the add comment the first time and enter some text in the text box and click on post button, that text will get appended to a div, but this does not work the second time around.

How to populate browser's entire window/document with rectangles

I want to populate the entire window with rectangles, no matter what size of window it is. eg. If rectangles are 250px wide, and window is 1000px wide, then it shold be 4 rec. in one row. I managed to fill just one row. Here is the code below
<!DOCTYPE HTML>
<html>
<head>
<style>
div {
width: 250px;
height: 150px;
border: 1px solid black;
border-collapse: collapse;
display: block;
position: fixed;
}
</style>
<script>
function ubaci_div() {
var sto = 0;
var ipsilon = "px";
for (var x = 0; sto < window.innerWidth; x++) {
var cet = sto + ipsilon;
var divovi = document.createElement("DIV");
document.getElementById("body").appendChild(divovi);
document.getElementsByTagName("DIV")[x].setAttribute("id", "id1");
document.getElementsByTagName("DIV")[x].style.left = cet;
sto += 250;
}
}
</script>
</head>
<body id="body">
<p id="p" onclick="ubaci_div()">Klikni</p>
</body>
</html>
I think you are asking for something like this?
https://jsfiddle.net/DIRTY_SMITH/cfckvvzw/9/
function ubaci_div() {
var i = 0;
var h = window.innerHeight;
var num = (h / 150);
for (i = 0; i < num; i++) {
alert(num);
loop();
var br = document.createElement('br');
}
}
function loop() {
var sto = 0;
var ipsilon = "px";
for (var x = 0; sto < window.innerWidth - 250; x++) {
var cet = sto + ipsilon;
var divovi = document.createElement("DIV");
document.getElementById("body").appendChild(divovi);
document.getElementsByTagName("DIV")[x].setAttribute("id", "id1");
document.getElementsByTagName("DIV")[x].style.left = cet;
sto += 250;
}
}
Something like this?
JSFiddle: https://jsfiddle.net/vc7w608m/
var rectangleWidth = 250;
var rectangleHeight = 100;
var columnCount = Math.ceil(window.innerWidth / rectangleWidth);
var rowCount = Math.ceil(window.innerHeight / rectangleHeight);
console.log(columnCount, rowCount)
for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
var rowDiv = document.createElement("div");
rowDiv.style.height = rectangleHeight + "px";
rowDiv.style["white-space"] = "nowrap";
rowDiv.style["overflow"] = "hidden";
document.body.appendChild(rowDiv);
for (var columnIndex = 0; columnIndex < columnCount; columnIndex++) {
var rectangle = document.createElement("div");
rectangle.style.height = rectangleHeight + "px";
rectangle.style.width = rectangleWidth + "px";
rectangle.style.display = "inline-block";
rectangle.style["background-color"] = "rgb(" + (Math.floor(Math.random()*256)) + ", " + (Math.floor(Math.random()*256)) + ", " + (Math.floor(Math.random()*256)) + ")";
rowDiv.appendChild(rectangle);
}
}

Dynamically set 'float:left' on the DOM node will not work in IE8

I create two DOM nodes elemA and elemB, and append them to the container node, before that, I set float style on elemA and elemB use js code, it turns out not working; at the other hand, if I remove elemA.style['float'] = 'left' and elemB.style['float'] = 'left', and use css to set float, it works, I can not figure out why?
var container = document.querySelector('#container');
var elemA = document.createElement('div');
var elemB = document.createElement('div');
elemA.className='elem-a';
elemA.style['float'] = 'left';
elemA.style['width'] = '45px';
elemA.style['height'] = '75px';
elemA.style['backgroundColor'] = 'green';
elemA.innerHTML = 'A';
elemB.className='elem-b'
elemB.style['float'] = 'left';
elemB.style['width'] = '45px';
elemB.style['height'] = '75px';
elemB.style['backgroundColor'] = 'blue';
elemB.style['marginLeft'] = '20px';
elemB.innerHTML = 'B';
container.appendChild(elemA);
container.appendChild(elemB);
.elem-a {
float: left;
}
.elem-b {
float: left;
}
<div id="container" style="width:200px;height:200px;border:1px solid red;">
</div>
As said in Comment about IE8 you should work with modern browser
IE expect styleFloat property whereas other browser use cssFloat so you should use both in your Code for support IE as you can see I have commented out in the code.
<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IT=edge,chrome=IE8">
<meta charset='utf-8'>
<body>
<div id="container" style="width:200px;height:200px;border:1px solid red;"></div>
<script type="text/javascript">
var container = document.querySelector('#container');
var elemA = document.createElement('div');
var elemB = document.createElement('div');
elemA.className='elem-a';
elemA.style.styleFloat = 'left';//For IE
elemA.style['float'] = 'left';
elemA.style['width'] = '45px';
elemA.style['height'] = '75px';
elemA.style['backgroundColor'] = 'green';
elemA.style['display']='block';
elemA.innerHTML = 'A';
elemB.className='elem-b'
elemB.style.styleFloat = 'left';//For IE
elemB.style['float'] = 'left';
elemB.style['width'] = '45px';
elemB.style['height'] = '75px';
elemB.style['backgroundColor'] = 'blue';
elemB.style['marginLeft'] = '20px';
elemB.style['display']='block';
elemB.innerHTML = 'B';
container.appendChild(elemA);
container.appendChild(elemB);
</script>
</body>
</html>

Categories

Resources