I know little about JavaScript but, as with everything I do, I'm throwing myself headfirst into some complex code (at least I think it's complex).
The code is basically designed to fit as many (approx.) 300x200 images into a div called "supercontainer".
A div called "container" is supposed to be created and then this is supposed to be populated with images.
The images will be resized slightly to make them fit in more aesthetically and nr of rows and columns are calculated also.
I'm not so concerned about how the logic of calculating number, or size, or position of images (or boxes) works, because I think this is sound.
I'm more concerned with my syntax and use of javascript language itself because literally nothing is displayed at the moment.
The 'setupboxes' function is called within my 'index.php' and I'm pretty sure I couldn't have got that wrong.
See below the .js code:
function setupboxes() {
var stdbw=300; //standard box width
var stdbh=200; //standard box height
var w=document.getElementById("containerparent").clientWidth; //get width of containerparent
var h=document.getElementById("containerparent").clientHeight; //get height of containerparent
var b=10; //set containerparent padding
var p=b; //set box padding
if(w>999) {
b=20; //set containerparent padding to 20px if screen width over 999px
p=b; //set box padding to 20px if screen width over 999px
}
var nrcols=Math.round((w-2*b)/(stdbw+2*p)); //set integer for nr of columns
var nrrows=Math.round((h-2*b)/(stdbh+2*p)); //set integer for nr of rows
var nrboxes=nrcols*nrrows; //calculate nr of boxes
var bh=(((h-2*b)/nrrows)-2*p); //set box height
var bw=(((w-s*b)/nrcols)-2*p); //set box width
var top=(h-(nrcols*(bh+2*p))); //set distance of container from top of containerparent
var left=(w-(nrrows*(bw+2*p))); //set distance of container from left of containerparent
var conth=((nrcols*(bh+2*p))+2*b); //set height of container
var contw=((nrrows*(bw+2*p))+2*b); //set width of container
var divcont=document.getElementById('containerparent').insertAdjacentHTML('afterbegin', '<div id="container"></div>'); //create container
divcont.style.position = 'relative';
divcont.style.top = top;
divcont.style.left = left;
divcont.style.border = 'red 1px solid';
var nrboxesit=nrboxes;
var boxnr=1;
while(nrboxesit>0){ //create boxes
document.getElementById('container').insertAdjacentHTML('beforeend', '<img src="images/0000001.jpg">');
img.style.padding = p;
img.style.height = bh;
img.style.width = bw;
boxnr=boxnr+1;
nrboxesit=nrboxesit-1;
}
}
Like I say I'm new to JavaScript so please don't assume I would have known to try some simple fixes!
Thanks in advance.
I made the minimum number of changes to get images to display. Specifically I didn't know what 's' stood for, so I set it equal to 10.
divcont is assigned to the element before attempting to insert HTML to it.
img near the end is undefined, I assigned an id and used that for a reference. Perhaps you won't want to wastefully assign ids like that.
function setupboxes() {
var stdbw = 300; //standard box width
var stdbh = 200; //standard box height
var w = document.getElementById("containerparent").clientWidth; //get width of containerparent
var h = document.getElementById("containerparent").clientHeight; //get height of containerparent
var b = 10; //set containerparent padding
var p = b; //set box padding
// FIXME
var s = 10;
if (w > 999) {
b = 20; //set containerparent padding to 20px if screen width over 999px
p = b; //set box padding to 20px if screen width over 999px
}
var nrcols = Math.round((w - 2 * b) / (stdbw + 2 * p)); //set integer for nr of columns
var nrrows = Math.round((h - 2 * b) / (stdbh + 2 * p)); //set integer for nr of rows
var nrboxes = nrcols * nrrows; //calculate nr of boxes
var bh = (((h - 2 * b) / nrrows) - 2 * p); //set box height
var bw = (((w - s * b) / nrcols) - 2 * p); //set box width
var top = (h - (nrcols * (bh + 2 * p))); //set distance of container from top of containerparent
var left = (w - (nrrows * (bw + 2 * p))); //set distance of container from left of containerparent
var conth = ((nrcols * (bh + 2 * p)) + 2 * b); //set height of container
var contw = ((nrrows * (bw + 2 * p)) + 2 * b); //set width of container
// FIXME
var divcont = document.getElementById('containerparent');
divcont.insertAdjacentHTML('afterbegin', '<div id="container"></div>'); //create container
divcont.style.position = 'relative';
divcont.style.top = top;
divcont.style.left = left;
divcont.style.border = 'red 1px solid';
var nrboxesit = nrboxes;
var boxnr = 1;
while (nrboxesit > 0) { //create boxes
// USED PLACEHOLDER IMAGE HERE
document.getElementById('container').insertAdjacentHTML('beforeend', '<img id="myBox' + nrboxesit + '" src="http://lorempixel.com/300/200/">');
// FIXME img is undefined. I just added an id based on
// current iteration of box number
var img = document.getElementById('myBox' + nrboxesit);
img.style.padding = p;
img.style.height = bh;
img.style.width = bw;
boxnr = boxnr + 1;
nrboxesit = nrboxesit - 1;
}
}
setupboxes();
<div style="display: inline-block; width: 600px; height: 600px;" id="containerparent">
<div style="display: inline-block; width: 600px; height: 600px;" id="container">
</div>
</div>
Related
How can I change an element with a fixed width in px when i resize the window? I need to use an absolute unit, i can not use relative units like % or vw.Every time the window is resized with 1 px i need to decrease the element width by 0.2px.
I tried to use the window resize eventListener but i don't know what calculations needs to be done.
What you want can be achieved by using javascript. I've created a logic to do that :
<script>
function myFunction() {
var initialscreenwidth = window.innerWidth; //Set Initial Screen Width
setInterval(function() { //looping the script
var screenwidth = window.innerWidth;
var difference = initialscreenwidth - screenwidth; //Calculating the change in screen-size
if (difference != 0) { //Checking if there is a change in width
var element = document.getElementById('demo');
var style = window.getComputedStyle(element, null).getPropertyValue('font-size'); //Getting default font-size of the element
var initialfontsize = parseFloat(style);
var fontdifference = -(parseFloat(difference) / 5); //1px change in screen-size = 0.2px change in font-size
var newfontsize = initialfontsize + fontdifference;
var newfontsizepx = newfontsize + "px";
if (newfontsize > 1) {
document.getElementById("demo").style.fontSize = newfontsizepx;
}
}
initialscreenwidth = window.innerWidth;
}, 300); //reloads in every 300ms
}
myFunction();
</script>
Paste this at the end of your body section, somehow using this in the head section is not working.
I am trying to get a div to expand div to always fill the viewport;
at the moment i calculate the if the div is left ,rigth above or below the center of the viewport and expand accordingly.
I would prefer if the div would expand to center in the viewport if possible. atm the moment i am just adjusting the margin to allow the div to expand sideways. but if the expanded div is big it can expand passed the viewport on a side while having enough space on the otherside.
this has to be in vannilla javascript. My current code follows:
function calculateExpandDir(el) {
var ele = el.getBoundingClientRect();
var windowH = window.innerHeight;
var windowW = window.innerWidth;
var expandDir = {}
if (ele.left + (ele.width / 2) >= window.innerWidth / 2) { expandDir.horizontal = "left" } else { expandDir.horizontal = "right" }
if (ele.top + (ele.height / 2) >= window.innerHeight / 2) { expandDir.vertical = "up" } else { expandDir.vertical = "down" }
return expandDir
}
function expandEl(el) {
var expandedHeight = parseFloat(el.getAttribute('data-height'));
var expandedWidth = parseFloat(el.getAttribute('data-width'));
var originalWidth = parseFloat(el.getAttribute('data-orig-width'));
var originalHeight = parseFloat(el.getAttribute('data-orig-height'));
var marginTop = 0;
var marginRight = 0;
var marginBottom = 0;
var marginLeft = 0;
var dir = calculateExpandDir(el)
console.log("expand to " + dir.vertical + dir.horizontal)
if (dir.horizontal == "right") {
}
if (dir.horizontal == "left") {
marginLeft = -(expandedWidth - originalWidth);
}
if (dir.vertical == "up") {
marginTop = -(expandedHeight - originalHeight)
}
if (dir.vertical == "down") {
};
el.style.position = "absolute";
el.style.height = expandedHeight+"px";
el.style.width = expandedWidth + "px";
el.style.transition = "all 0.5s ease-in-out";
el.style.marginTop = marginTop+"px";
el.style.marginBottom = marginBottom+"px";
el.style.marginLeft = marginLeft+"px";
el.style.marginRight = marginRight+"px";
}
I figured i have to calculate the ammount of space on each side of the div and expand the div proportionally to the ammount of space available so it will become centered but i am stuck on how to do this at the moment
EDIT:
https://codepen.io/sereal_killer/pen/eGZaNo
in this example the divs expand depending on their position. the center div is a cheat as it has the data attribute to tell it to expand in both directions.
i want the divs to expand to fill the screen depending on the available room (they have a max height and width).
if i have a centered div like in the example i want it to know it has equal room on both sides and expand equally left and right.
if it is a bit more to the right i want it to expand to still be centered.
the caveat is that it cannot leave where it originated. it cant pop out and just appear in the center. If i have time i will draw a picture aswell
I want to append a div as a child of an other div without changing its position (from a user point of view).
The "futur" parent is rotated of -30° the element that will become a child is rotated of -30°.
how to compute the right (left, top) position of the futur child ?
I tried to cancel the rotation of the futur parent
transform:rotate(0°)
and do the same for the futur child
transform:rotate(60°)
but with a transform-origin set to the transform-origin of the futur parent that means
Left(futur child)-tranform-originx (parent)
top(futur child)-transform-originy (parent)
but it does not seem to run
any idea ?
HTML :
<div id="futurParentFrame" style="z-index:1000;position:absolute;left:100px;top:100px;background-color:red;border:black 6px dashed;width:800px;height:500px;transform:rotate(-30deg)">
</div>
<div id="futurChildDiv" style="z-index:1002;position:absolute;left:493px;top:192px;background-color:gray;border-left:blue 4px dashed;border-right:blue 2px dashed;width:250px;height:150px;transform:rotate(30deg);"></div>
The math is somehow complex. I have tried to done it in the most simple way possible.
Click on the button to create the new child. The old one is semitransparent so that you can see them overlapping
function createChild () {
var parent = document.getElementById("futurParentFrame");
var child = document.getElementById("futurChildDiv");
var parentCoor = getCoor (parent);
var childCoor = getCoor (child);
var newChild = child.cloneNode(true);
newChild.id = "newChild";
newChild.style.transform = "rotate(60deg)";
var r = Math.hypot (parentCoor.x - childCoor.x, parentCoor.y - childCoor.y);
var alpha = -30 * Math.PI / 180;
var relativeX = childCoor.x - parentCoor.x;
var relativeY = childCoor.y - parentCoor.y;
var rotatedX = relativeX * Math.cos(alpha) + relativeY * Math.sin(alpha);
var rotatedY = relativeX * -Math.sin(alpha) + relativeY * Math.cos(alpha);
var left = (parentCoor.width * 0.5) - parentCoor.borderLeft - (childCoor.width * 0.5) + rotatedX;
var top = (parentCoor.height * 0.5) - parentCoor.borderTop - (childCoor.height * 0.5) + rotatedY;
newChild.style.left = left + "px";
newChild.style.top = top + "px";
parent.appendChild(newChild);
}
function getCoor (element) {
var left = element.offsetLeft;
var top = element.offsetTop;
var width = element.offsetWidth;
var height = element.offsetHeight;
var centerX = left + width * 0.5;
var centerY = top + height * 0.5;
var borderLeft = parseInt (element.style.borderLeftWidth);
var borderTop = parseInt (element.style.borderTopWidth);
return {left: left,
top: top,
width: width,
height: height,
x: centerX,
y: centerY,
borderLeft: borderLeft,
borderTop: borderTop};
}
#futurChildDiv {
opacity: 0.5;
}
<div id="futurParentFrame" style="z-index:1000;position:absolute;left:100px;top:100px;background-color:red;border:black 6px dashed;width:800px;height:500px;transform:rotate(-30deg)">
</div>
<div id="futurChildDiv" style="z-index:1002;position:absolute;left:493px;top:192px;background-color:gray;border-left:blue 4px dashed;border-right:blue 2px dashed;width:250px;height:150px;transform:rotate(30deg);"></div>
<button onclick="createChild();">run</button>
Here is a simple text on a web site, I would like to know what is the My First Heading length and height in how many pixel and at which position... How can I detect it via javascript? Thanks.
var header = document.getElementById("yourHeadingId");
var w = header.offsetWidth; //Width
var h = header.offsetHeight; //Height
var x = header.offsetLeft; //Top left corner x position.
var y = header.offsetTop; //Top left corner y position.
To change the header's content:
while(header.firstChild) {
header.removeChild(header.firstChild);
}
header.appendChild(document.createTextNode("some new content"));
you can create a temporary h1 element with display: inline style... and than get the offsetWidth.
try this:
<script type="text/javascript">
var domId = 'dom-id' + Math.random();
var temp = document.createElement('div');
var body = document.getElementsByTagName('body')[0];
body.appendChild(temp);
var text = document.getElementsByTagName('h1')[0].innerHTML;
var width = null;
var tempH1 = null;
temp.innerHTML = '<h1 style="display: inline" id="' + domId + '">' + text + '</h1>';
tempH1 = document.getElementById(domId);
width = tempH1.offsetWidth;
body.removeChild(temp);
alert(width);
</script>
element.offsetWidth/element.offsetHeight for the element dimensions.
element.offsetTop/element.offsetLeft for the top left corner location (relative to its offsetParent).
You can use clientHeight and clientWidth to calculate the values. Like
document.getElementById("DOMID").clientWidth
I am opening a pop up window using window.open function
window.open('some_page.htm','','width=950,height=500');
Now what I want is when user tries to resize the window, the aspect ratio should be maintained i.e., if width is reduced then accordingly height should also get reduced and vice versa. I just want to calculate the new dimensions. So far I have tried this
function ResizeWindow()
{
var iOrignalWidth = 950;
var iOrignalHeight = 500;
var iOuterHeight = window.outerHeight;
var iOuterWidth = window.outerWidth;
var iNewOuterWidth = Math.round((iOrignalWidth / iOrignalHeight) * iOuterHeight);
var iNewOuterHeight = Math.round((iOrignalHeight / iOrignalWidth) * iNewOuterWidth);
alert("New Width: "+ iNewOuterWidth + "\t" + "New Height" + iNewOuterHeight);
}
I know that there's something wrong up there since I am not getting desired results. ANy solution on this ?
You'll want to either adjust the width to the height or visa versa, not both.
In this code, I assumed you want the width adjusted to the height:
function ResizeWindow()
{
var iOrignalWidth = 1000;
var iOrignalHeight = 500;
var iOrginalRatio = iOrignalWidth/iOrignalHeight; // 2
var iOuterWidth = window.outerWidth; // example: 1083
var iOuterHeight = window.outerHeight; //example: 600
var iNewOuterHeight = iOuterHeight; // 600
var iNewOuterWidth = Math.round(iNewOuterHeight*iOrginalRatio); //600 * 2 = 1200
alert("New Width: "+ iNewOuterWidth + "\t" + "New Height" + iNewOuterHeight);
}
I changed to original width to 1000 for the example, but you can change that back in your actual code.
You should do to accoording to one resize for maintain the aspect ratio. For example:
function ResizeWindow()
{
var iOrignalWidth = 950;
var iOrignalHeight = 500;
var iOuterHeight = window.outerHeight;
var iOuterWidth = window.outerWidth;
var w = (window.outerWidth - iOrignalWidth) / iOrignalWidth; // for exam: (1280-950) / 950= 0.34
var h = (window.outerHeight - iOrignalHeight) / iOrignalHeight; // for exam : (800 - 500) / 500= 0.60
var newWidth;
var newHeight;
if (w<h)
{
// If percentage of width is less than percentage of height, Resize should be according to percentage of width.
newWidth = iOrignalWidth * w * 100;
newHeight = iOrignalHeight * w *100;
}
else
{
// If percentage of height is less than percentage of width, Resize should be according to percentage of height.
newWidth = iOrignalWidth * h * 100;
newHeight = iOrignalHeight * h *100;
}
alert("New Width: "+ newWidth + "\t" + "New Height" + newHeight );
}
So that maintain the aspect ratio is always preserved.