in function below i'm trying to add div block, but i can't set left position. alert function show message '600px'. on my screen this block has another position.
function show(){
if(document.getElementById('div1') == null){
var div1 = document.createElement('div');
div1.style.left = '600px';
document.body.appendChild(div1);
alert(div1.style.left);
}
}
my first question here. so i don't know how to add code style
You're not going to see anything visual on the page with your example for a couple reasons. First, your div does not contain anything, so it has no height or width. And second, you cannot position an element in the manner you are trying because it does not have display attribute absolute or relative. Try something like this:
function show(){
if(document.getElementById('div1') == null){
var div1 = document.createElement('div');
div1.innerHTML = 'hi there';
div1.style.left = '600px';
div1.style.position = 'absolute';
document.body.appendChild(div1);
}
}
The left property only applies to elements which are positioned. For an element to be positioned, it must have a position property with a value other than static (which is the default).
Set it to relative, fixed or absolute as per your needs.
Your div will have 0 height/width as there is no child content. Use textContent or innerHTML to add content to the div.
Also, the left property will not apply unless you set the positioning to relative or absolute. This also goes for the other sides (right, top and bottom).
Related
I'm working on a hobby project similar to markup.io where you can load in any website and annotate it. I can't figure out how to add an annotation that behaves like it does in markup.io:
Doesn't interrupt the styling or layout of the website you are annotating
The annotation keeps the correct position when scrolling and resizing the window
From what I can see they place an absolute positioned div inside the element that you clicked on. From my understanding by reading the docs that div would position itself based on the closest positioned ancestor. How would you calculate the correct top and left values to position the annotation to where the user clicked? Is there a better way to do this?
I'm using React if that matters.
Things that I have tried:
Append the following bit of html to the element that was clicked:
<div style="width:0px; height:0px; position:relative;">
<div style="width:50px;height:50px;position:absolute; ">this is the annotation </div>
</div>
Problem: This would mess with the page layout because of the relative positioned div that is not ignored by the document flow.
Create fixed overlay over the entire page. Get the css selector of the clicked element. Draw annotation on the fixed overlay at the x,y position of the element.
Problem: Whenever the user would scroll or resize the window the annotation would need to be redrawn at the new position of the element. I used getBoundintClientRect to get the new position and this would cause a reflow and caused the whole website to have severe perfomance issues when dealing with 100+ annotations.
Hopefully someone can point me in the right direction!
The general idea is as follows:
Find the parent of the element that you clicked on
Check if they are positioned (anything other than static)
If it is static search for the closest element that is positioned.
Set the new badge/annotation top and left position to that of the mouse minus the top and left of the element that you're going to append it to (in this case called parent).
Also account for the width and height by subtracting half of each to perfectly center your annotation.
// In my case I put the webpage in an Iframe. If this is your own page
// you can just use document.
iframe.contentWindow.document.addEventListener(
'click',
(e: MouseEvent) => {
// step 1: find the parent.
let parent = e.target.parentElement;
let computedStyle = window.getComputedStyle(parent);
// step 2 & 3: Look up the first positioned element and make this the
// the element that you're going to append your badge/annotation to.
while (
computedStyle.position === 'static' &&
parent.parentElement !== null
) {
parent = parent.parentElement;
computedStyle = window.getComputedStyle(parent);
}
// style the annotation the way you want to
const badge = document.createElement('div');
const { top, left } = parent.getBoundingClientRect();
badge.style.position = 'absolute';
// step 4 and 5 get the mouse position through e.clientX and Y and
// subtract the appropriate value like below to place it exactly at the mouse position
badge.style.top = `${e.clientY - top - 5}px`;
badge.style.left = `${e.clientX - left - 5}px`;
badge.style.backgroundColor = 'red';
badge.style.width = '10px';
badge.style.height = '10px';
badge.style.borderRadius = '50%';
badge.style.zIndex = '9999';
parent.appendChild(badge);
}
);
Some background: I have a div in which elements of different height will be added to and I'm in need of achieving the following:
The div has a max-height property, when the different elements that are added to the Div overlap such height, I can't have the div "overflowing (putting a scrollbar on it)". Instead, I need to detect when this happens, so I can create ANOTHER div in which I could put the rest of the elements. Attached is an image that I hope illustrates what I'm trying to do.
Use jQuery:
var maxHeight = $(".someElement").css("max-height");
var height = 0;
$(".elements").each(function(){
height += $(this).height();
if(height >= maxHeight){
//create new div here and put the rest of the elements there
height = 0; //so you can continue with the loop and creating more divs.
}
});
I have a pseudo function below that I think could get you started on the right track. You will have to fill in the appropriate information for it.
$(elements).each(function() {
var currentDiv = $(currentDiv);
if($(currentDiv ).height() > MAX_HEIGHT)
{
$(currentDiv).insertAfter(newDiv);
currentDiv = $(newDiv);
}
$(currentDiv).append(element);
});
You'll have to keep track of the current div you are adding info to. Just add info like normal but when it overflows you should insertAfter it a new div and change the current div variable to be that one and then continue appending again.
To test if a div is currently overflowing, compare it's scrollHeight to its height.
With jQuery
if ($(obj)[0].scrollHeight > $(obj).height()) {
// do stuff
}
In this case though, you'll probably want to test against the css max-height before adding content. To do this (again in jQuery) load the content you plan to add into a variable so you can check its height before adding it to the document.
var content = // your content here
if ($(container).height() + content.height() > parseInt($(container).css("max-height"), 10)) {
// this means it would overflow, so do stuff
} else {
// no overflow here
$(container).append(content);
}
Here's a quick fiddle. http://jsfiddle.net/k0g47xdr/2/
edit:
the parseInt call around .css("max-height") is to convert from the text format it comes in to a regular number. As written it assumes the value is in px, not em or percent.
I wanted to write a code which should find whether an element exists on screen or not.
As per my requirement it should also support for an element which is inside a div that has inner scrolling.
Assumptions are
1.that only one level of inner scrolling should be supported.
2.only visibility in context of vertical scrolling is checked.
The main problem is the following usecase as depicted on this link.
An element A ($("#innerele")) is present inside the DIV ($("#outerdiv")) which is scrollable. First you have to find out whether the DIV itself is present on screen and second then test that whether A is visible. For e.g A may be at a the top position inside DIV and thus visible, but if DIV itself is not visible then it should return false.
I could write the following code which is jquery plugin which takes care of the above requirements. The context is the DIV which has inner scrolling inside it.
$.fn.isonscreen = function(context){
//Subtract the offset of the parent container.
//Will be 0 in case cont is undefined
var tominus=0,
//Add the scrollTop position incase no cont is undefined.
toadd=0;
if(context){
//Find if the div is itself visible
if(!context.isonscreen()){
return false;
};
tominus = context.offset().top;
}else{
context = $(window);
toadd = context.scrollTop();
}
if($(this).offset().top - tominus <= (toadd + context.height())){
return true;
};
return false;
}
For the above link the code to find if A is on screen or not -
$("#innerele").isonscreen($("#outerdiv"))
Will this work everytime or there is some usecase where it will fail?.
I want to create a div element manually and later add some CSS styling to it using JavaScript. I created a div element and changed it's style with JavaScript. The problem is, some CSS styles do not work.
this is the fiddle preview
(color, background, width, height) those properties worked fine but the (zIndex, top, left) properties do not work. I want to know why this happens and how to correct it.
this is my JavaScript code:
function css()
{
var element = document.createElement('div');
element.id = "someID";
document.body.appendChild(element);
element.appendChild(document.createTextNode
('hello this javascript works'));
// these properties work
document.getElementById('someID').style.zIndex='3';
document.getElementById('someID').style.color='rgb(255,255,0)';
document.getElementById('someID').style.background='rgb(0,102,153)';
document.getElementById('someID').style.width='700px';
document.getElementById('someID').style.height='200px';
//these do not work
document.getElementById('someID').style.left='500px';
document.getElementById('someID').style.top='90px';
}
this is my relevant html code
<input type="submit" name="cssandcreate" id="cssandcreate" value="css" onclick="css();"/>
The left, and top CSS style settings aren't working because you must first set the position property. If the position property is not set, setting the left and top styles will have no affect. The position property has these settings:
static
absolute
fixed
relative
initial
inherit
So, try setting the position property before setting left and top:
object.style.position="absolute"
The differences between the position properties affect how subsequent settings position your elements.
document.getElementById('someID').style.position='absolute';
document.getElementById('someID').style.left='500px';
document.getElementById('someID').style.top='90px';
I added the first line of code to your code, following the suggestions by Sandy Good. He said to simply setup the 'position' paramenter BEFORE using the 'left' and 'top' ones. So I did. And it works!
I hope this is what you are looking for :
function css(){
var element = document.createElement('div');
element.className = "someID";
document.body.appendChild(element);
element.appendChild(document.createTextNode
('hello this is javascript work'));
// this properties are work
var a = document.getElementsByClassName('someID');
for(var i in a ){
a[i].style.zIndex='3';
a[i].style.color='rgb(255,255,0)';
a[i].style.background='rgb(0,102,153)';
a[i].style.width='700px';
a[i].style.height='200px';
a[i].style.left='500px';
a[i].style.top='90px';
}
}
I'm having issues with an absolutely positioned custom drop down, in IE7 the div is sitting behind a normal textbox which is not position in any special way.
I've already read this topic: IE7 puts absolutely positioned div underneath, ignores z-index but the solutions didn't help me.
The difference between my code and the person who asked the above question is that my div is being created through javascript using document.write and adding it through appendChild
addEvent(document.getElementById("storeDown"), "click", showRegions);
var showRegions = function(e) {
var dd = getTarget(e);
if(document.getElementById("regionOptions")) {
dd.parentNode.removeChild(document.getElementById("regionOptions"));
regionsShowing = false;
} else {
var ddNode = document.createElement("div");
ddNode.id = "regionOptions";
ddNode.style.backgroundColor = offColor;
var optNode;
for(var region in storeList) {
optNode = document.createElement("div");
optNode.innerHTML = region;
ddNode.appendChild(optNode);
}
dd.parentNode.appendChild(ddNode);
regionsShowing = true;
}
cancelEvent(e);
}
My parent div has a z-index of 500 and is positioned relative and regionOptions is positioned absolute and I tried to also add a z-index to it but it didn't make a difference.
Okay finally figured it out, I changed where it appends so it's appended in a div at the bottom of the page after all the textboxes (in my case, a buttons div), so instead of dd.parentNode.appendChild(ddNode), it's now document.getElementbyId("buttons").appendChild(ddNode), but also had to change the CSS so it's absolute positioned in relative to the page wrapper rather than the specific div, and it seems to have fixed it.