Cannot apply style to dynamically created elements in javascript - javascript

I have the following code:
let dynel = document.createElement('div');
dynel.className = 'foo';
dynel.style.width = '5px';
dynel.style.height = '5px';
dynel.style.backgroundColor = 'blue';
document.body.appendChild(dynel);
This code works as I expect it to, after appending the dynamic element to the document, a 5 x 5 blue box appears. The problem starts when I try to access the element via its className to style it further:
var foo = document.getElementsByClassName('foo');
foo[0].style.top = '50px';
foo[0].style.left = '200px';
This code should position the box but it does nothing, what am I doing wrong? Preferably I'm looking for a pure JS solution so no JQuery.
Thanks in advance :)

Problem
The default value of the property position of a div is static. When you try to set left/right [..] on static element it has no effect on that element.
static : every element has a static position by default, so the
element will stick to the normal page flow. So if there is a
left/right/top/bottom/z-index set then there will be no effect on that
element. relative : an element's original position remains in the flow
of the document, just like the static value.
Solution
You have to set the position property in your created element to absolute, fixed or relative.
let dynel = document.createElement('div');
dynel.className = 'foo';
dynel.style.position = "absolute"
dynel.style.width = '5px';
dynel.style.height = '5px';
dynel.style.backgroundColor = 'blue';
document.body.appendChild(dynel);
var foo = document.getElementsByClassName('foo');
foo[0].style.top = '50px';
foo[0].style.left = '200px';

top, left, right, bottom works on those elements in which position property is not static. But either absolute or relative or fixed.
As per your requirement use any of the 3 values in your CSS and styles will start to apply. Something like this would work (But it depends how you want you implemention of the code)
var foo = document.getElementsByClassName('foo');
foo[0].style.position = "relative";
foo[0].style.top = '50px';
foo[0].style.left = '200px';
NOTE: position:fixed and position:absolute would get your element out of the normal code flow and you will have to adjust accordingly.

You need to ensure that foo[0] has the position: absolute; style set.

I was inspired by #Imran Rafiq Rather to give the details example for each situation:
relative
If you just want to adjust position a little bit relative to its default position, use key word "relative"
Default position is 'static' position
var foo = document.getElementsByClassName('foo');
foo[0].style.position = "relative"; // works almost the same as default or 'static', because 'relative' is relative to it's 'static' position.
foo[0].style.top = '50px';
foo[0].style.left = '200px';
https://codepen.io/hoogw/pen/QWqRdBY
absolute
we usually want to relative to its parent div, should use 'absolute'
var foo = document.getElementsByClassName('foo');
foo[0].style.position = 'absolute'; // relative to its parent div
foo[0].style.top = '50px';
foo[0].style.left = '200px';
https://codepen.io/hoogw/pen/GRMaWKB?editors=1100
fixed
If you want to relative to whole page, use 'fixed'
var foo = document.getElementsByClassName('foo');
foo[0].style.position = 'fixed'; // relative to whole page, whole html body document
foo[0].style.top = '50px';
foo[0].style.left = '200px';
https://codepen.io/hoogw/pen/yLzWMvJ
Here is link to document https://developer.mozilla.org/en-US/docs/Web/CSS/position

Related

Prevent two fixed components from overlapping

I have been struggling to make an element that I prepend to a page not overlap with the fixed component already existant on the page.
For example, you can execute the following in console on Stackoverflow :
const rootElement = document.createElement("div");
rootElement.id = "chrome-bar";
document.getElementsByTagName("body")[0].style["paddingTop"] = "40px";
document.getElementsByTagName("body")[0].style["position"] = "relative";
document.body.prepend(rootElement); rootElement.innerHTML="Hello World";rootElement.style="position:fixed;z-index:99999;top:0;background-color:black;width:100vw;color:white;"
As you can see, the black bar overrides the header tag, because of its position : fixed style. How could I have both of these bars (the one I create & the SO navbar) fixed and not overlap ? i.e. the behaviour that happens when you insert the same snippert on github (whose nav is not fixed)
Thanks a lot !
This is somewhat of a crude workaround, but you could create a div with a fixed height and displace the existing header element by the same amount.
const rootElement = document.createElement("div");
rootElement.id = "chrome-bar";
document.getElementsByTagName("body")[0].style["paddingTop"] = "40px";
document.getElementsByTagName("body")[0].style["position"] = "relative";
document.body.prepend(rootElement);
rootElement.innerHTML = "Hello World";
let divHeight = "30px"
rootElement.style = `position:fixed;z-index:99999;top:0;background-color:black;width:100vw;height:${divHeight};color:white;`
let header = document.querySelector("body > header")
header.style.setProperty("top", divHeight, "important")

Why aren't createjs DOMElements positioned correctly at top left of the canvas like all other objects?

(As per the title)
If you create an HTML button and place it on the canvas with createjs:
var html = document.createElement('input');
html.type = 'button';
html.id = 'testing button';
html.value = 'test';
var DOMElement = new createjs.DOMElement(html);
var target = document.getElementById(<name of a div in your HTML>);
target.appendChild(html);
//returns the first canvas element seen in the page
var canvas = document.getElementsByTagName('canvas')[0];
var stage = new createjs.Stage(canvas);
createjs.Ticker.addEventListener("tick", function(event) {
stage.update(event);
});
stage.addChild(DOMElement);
stage.update();
The button will appear outside of the canvas. This is mostly likely an artifact of the HTML and CSS (I don't have the background to say why this is); Instead of at the default position on the stage (0, 0), the top left, like all other createjs DisplayObjects.
The answer appears to be related to CSS styling. As a simple addition of two styling options has the default position of the button set at the top left (0, 0) as we expect:
var html = document.createElement('input');
html.type = 'button';
html.id = 'testing button';
html.value = 'test';
html.style.top = 0; // <--
html.style.left = 0; // <--
These properties according to MDN, determine position relative to the top and left margins:
For absolutely positioned elements (those with position: absolute or
position: fixed), it specifies the distance between the top / left
margin edge of the element and the top / left edge of its containing
block.
Source: Top & Left.
If someone could chime in for the reason as to this behavior and a little more detail that would be great, as I said I simple don't have the background in CSS or HTML to say why.

Positioning div off-screen to the right using jQuery

Strictly using JavaScript, I'd like to position the following div element right outside the window, to the right, so that no horizontal scrollbar is present.
How do I do this?
HTML:
<div id = "content">
<header>
<h2>Welcome!</h2>
</header>
</div>
I was thinking something like
$( "#content" ).offset({ left: 1345});
but that unfortunately results in a scrollbar, and it isn't responsive, causing the div to be located far outside the right edge of the window when in mobile view.
If you take the window.innerWidth; value and set that as the left position value it'll hang out right outside of the viewports width.
You'd need to set either your wrapper or body to overflow: hidden; to get rid of the horizontal scroll though.
var hiddenDiv = document.getElementById('content');
var docWidth = window.innerWidth;
hiddenDiv.style.position = 'relative'; // Or absolute, depending on what you want
hiddenDiv.style.display = 'inline-block';
hiddenDiv.style.left = docWidth+'px';
http://jsfiddle.net/c62sqvdk/ <-- JsFiddle for visual example.
Why not just hide it? You can easily do it with javascript with
var link = document.getElementById('content');
link.style.display = 'none';
link.style.visibility = 'hidden';
Depends on what you need it for.
Also, check this https://daneden.github.io/animate.css/
Try
document.body.style.overflow = "hidden";
var content = document.getElementById("content");
content.style.position = "absolute";
content.style.left = window.innerWidth + "px";
jquery
$(function() {
$("body").css("overflow", "hidden")
.find("#content").css({
"position" : "absolute",
"left" : window.innerWidth
});
});
jsfiddle http://jsfiddle.net/guest271314/9zhy2xax/

need 100% div without setting a fixed height on container div

Here is a link to a JSFiddle http://jsfiddle.net/9NYcn/11/ i put together with what i would like to do, but i need to do this with pure css.
function expand(){
var sect = document.getElementById("sect");
var body = document.getElementById("main");
var panes = document.getElementById("panes");
var newHeight = 40 + "px";
var newHeight2 = 120 + "px";
var topVal = 120 + "px";
sect.style.display = "block";
sect.style.height = newHeight;
body.style.height = newHeight2;
panes.style.top = topVal;
}
In the above function i had to set the "top" property of panes in order to get this to work. i need to get it so that the panes section will work like it currently does without using javascript to change the "top" property of "panes". When the user clicks the "expand" button the div with the class "body" will expand and not stick behind or overlap the "panes" div.
I know im doing a terrible job explaining i apologize for that.
Remove the absolute positioning of .panes: http://jsfiddle.net/rHTM8/
It will make it naturally flow after the middle div.

JavaScript absolute position of element on images

I have created a new div and adding it to all images on the page as follows:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
var divLink = document.createElement("div");
divLink.style.position = "absolute"; divLink.style.top = "10px"; divLink.style.right = "10px"; divLink.style.zIndex="1"; divLink.style.fontSize = "20px"; divLink.style.backgroundColor = "black"; divLink.style.color = 'white';
divLink.innerHTML = linkCount;
images[i].parentNode.insertBefore(divLink, images[i] );
}
This is working well for all images except images contained in a <ul>. For these images, each divLink is moved to the right of the <ul> and stacked on top of one another. If I remove the divLink.style.right = "10px"; the divLink moves by default to the left of the image.
How can I position the divLink to the top-right corner of the image, for all images including those in the <ul>.
Use relative position instead of absolute
divLink.style.position = "relative";
There seems no need to give position:absolute to the images.
You can simply append the images without giving the position attribute and move the images using the margin property.
divLink.style.margin-top = "10px";
divLink.style.margin-right= "10px";
If you add poistion:absolute and mention top/left/right/bottom , the elements tends to stack on each other .
There are 2 ways to do this :
1> Do not assign any position.Let it remain "STATIC". Move the "images" using the margin properties.
Eg:
divLink.style.margin-top = "10px";
divLink.style.margin-right= "10px";
OR
2> Make just the position:absolute without mentioning top/left/right/bottom properties, this way they will not stack on each other. Unless you don't want to move the "images" explicitly using top/left, that is of no use.

Categories

Resources