How to change size of button depending on div width - javascript

What I am trying to do is to my button size is 35% of my div width. I add dynamically elements to my div, and in JavaScript I add attributes. So here is my div in .js file:
var div2= document.createElement('div');
div2.className = "div2" ;
div2.id = "div2";
div2.style.color= ButtonColor;
div2.style.height = ButtonHeight;
div2.style.width = ButtonWidth;
div2.style.backgroundColor = BackgroundColor;
then I create elements and add on this way:
div2.appendChild(h2) + "\n";
div2.appendChild(linebreak);
div2.appendChild(pic) + "\n";
div2.appendChild(linebreak);
var parentDiv = document.getElementById("surveybot-button");
var sp2 = document.getElementById("surveybot-link");
parentDiv.insertBefore(div2,sp2);
div2.appendChild(linebreak);
div2.appendChild(sp2);
Then I do next in my index.php
<div id="surveybot-button">
<a id="surveybot-link" class="button-1" href="https://gosurveybot.com/liberty-moving-video-chat-estimate/">SCHEDULE VIRTUAL ESTIMATE USIGN SURVEYBOT</a><br>
</div>
<script id="buttons-script" src="button.js" button-variant="<img src='img/button-icons-2.png'>" button-color="green" button-width="600px" button-height="355px" background-color="#11ff11">
</script>
<script>
var divWidth = document.getElementById("div2").offsetWidth + "px";
var divHeight = document.getElementById("div2").offsetHeight + 'px';
alert(divWidth);
alert(divHeight);
document.getElementsByClassName("button-1").style.width = divWidth / 3.2 + "%";
//document.getElementsByClassName("button-1").style.width = divWidth - 100px;
So here is what I tried:
document.getElementsByClassName("button-1").style.width = divWidth / 3.2 + "%";<br>
document.getElementsByClassName("button-1").style.width = divWidth * 0.3;
And css on the end:
a.button-1 {
width: 300px;
height: 100px;
background: url(img/button-button-1.png) top center no-repeat;
background-size: 100% auto;
text-indent: -999999px;
color: transparent;
float: left;
cursor: pointer;
position: absolute;
}
So can someone tell me what I am doing wrong. So to repeat my goal is if div is 100 px button should be 35px(35% of div width) and picture90px(90% of div width).
All advice and solutions are welcome.
Thanks in advance.

i have read your code but i have not implemented it.apparently i can see 2 mistakes you are making.
1: var divWidth = document.getElementById("div2").offsetWidth + "px"; returns a string , lets say 100px and you can't divide a string with numeric value so
100px/3.2 returns undefined result.
2:document.getElementsByClassName("button-1").style doesn't work because document.getElementsByClassName returns to you an array of all the elements with specified class name. if you want to add the style onto these elements you have to loop through the array returned by this function.
You can alternatively use document.getElementById() instead and add the style to specific element.
for your first problem you could use the following approach
var divWidth = document.getElementById("div2").offsetWidth;
var btnWidth = divWidth * 0.35;
//alert(btnWidth);
document.getElementById("btn").style.width = btnWidth+"px";
Hope it helps.

I find out other solution so now I am using Element.getBoundingClientRect(); So if someone have same problem it can be fixed on this way.
Element.getBoundingClientRect() gives to you bot,height, left, right, top and width of certain element. So example = xxx.Element.getBoundingClientRect().width;

Related

Get scrollbar width

I removed the body scrollbar and then must compensate for its lack with padding. To do this, I try to calculate the width of the scrollbar of the div block that appears after removing the body scrollbar and pass the resulting value as padding. This works in Chrome, but does not work in other browsers. Here is my code:
element = document.getElementById('div');
var scrollBarWidth = element.offsetWidth - element.clientWidth;
document.body.style.paddingRight = scrollBarWidth + 'px';
I would really appreciate a suitable solution.
It seems to work, but maybe there is a simpler solution that works in all browsers?
// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);
// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.info(scrollbarWidth); // Mac: 15
// Delete the DIV
document.body.removeChild(scrollDiv);
.scrollbar-measure {
width: 100px;
height: 100px;
overflow: scroll;
position: absolute;
top: -9999px;
}
document.body.style.paddingRight = (scrollbarWidth) + 'px';

Using getComputedStyle with border-box should return height sans border and padding

EDIT 3/Final: Th Computed Style problem/question is explained below but, for the benefit of others coming later, my real problem is solved with Flex Boxes and Vx measurements in conjunction with border-box. IMHO "display: flex;" is the answer to many questions and, although I'm struggling to get it to do what I want, stops you having to work against CSS!
EDIT 2: The following undoubtedly needs refactoring but if you can tell me that it does what I was asking for that'd be great. The change I had to make was to add clientTop in with offsetTop in the equation: -
function resizeContent()
{
var browserHeight = window.outerHeight;
var offesetHeight, offsetWidth;
var viewHeight = window.innerHeight;
var viewWidth = window.innerWidth;
var chromeFootPrint = browserHeight - viewHeight;
var tmpHeight = viewHeight;
if (window.matchMedia("(orientation: portrait)").matches) {
if (viewWidth > viewHeight) {
viewHeight = viewWidth - chromeFootPrint;
viewWidth = tmpHeight + chromeFootPrint;
}
} else {
if (viewWidth < viewHeight) {
viewHeight = viewWidth - chromeFootPrint;
viewWidth = tmpHeight + chromeFootPrint;
}
}
var dimTarget = logScroll;
var offsetTop = dimTarget.offsetTop + dimTarget.clientTop;
var offsetLeft = dimTarget.offsetLeft + dimTarget.clientLeft;
while (dimTarget = dimTarget.offsetParent) {
offsetTop += dimTarget.offsetTop + dimTarget.clientTop;
offsetLeft += dimTarget.offsetLeft + dimTarget.clientLeft;
}
logScrollHeight = viewHeight - (offsetTop + fireBreak);
logScroll.style.height = logScrollHeight + "px";
logScroll.style.width = getStyle(contentDiv).width;
logWindow.style.height = logScroll.style.height;
logWindow.style.width = logScroll.style.width;
logWindow.scrollTop = logWindow.scrollHeight - logScrollHeight;
contentDiv.style.visibility = "visible"; // Now we're presentable
}
and this is the fire-break calculation: -
var outerStyle = getStyle(wholeScreen);
fireBreak = Number(outerStyle.paddingBottom.match("[0-9.]*"))
+ Number(outerStyle.borderBottomWidth.match("[0-9.]*"))
;
resizeContent();
EDIT 1: Ok, let me re-phrase the question: - How to I find out the height of my DIVs content with: -
width: 250px;
border: 3px solid green;
padding: 0.5em;
box-sizing: border-box;
I am currently having to do this: -
logScrollHeight = viewHeight -
(offsetTop + Number(getStyle(headerDiv).paddingBottom.match("[0-9.]*")));
Original question: -
This is bound to be a duplicate but after nearly an hour of looking I have found many similar/identical questions but no real answer :-(
Why aren't the boundryWith and padding deducted from height?
Thankfully the boundryBottomWidth and PaddingBottom return have been converted to pixels (including the "px" string sadly) but doesn't the standard say that the usable height should be returned?
To get the height of an element, you don't use getComputedStyle.
getComputedStyle should only be used to get the parsed values that are currently applied from different style-sheets. In other words, you can see it as a live style-sheet, only targeted to a single element, with standardized units.
But in no way it should be used to get the current height or width of an element. Too many factors may interfere with the set value, and an element can even have an height without having any CSS height rule set.
So yes... when the height CSS rule is set to auto, you will get the computed value, which may coincide with the real height of the element, but it also may not be so.
So in order to get the displayed height of an element, without the border and padding, we will need to do some calculations ourself.
Element#getBoundingClientRect() will give us the real displayed dimensions of our element, transformations included. .offsetHeight will give us the untransformed height including the border-box, and .clientHeight will give us the untransformed height with the padding-box.
This means that we will first have to get all the border and padding computed values, then get the current scale of our element, and finally remove the scaled padding + border boxes from the values we get with getBoundingClientRect.
Here is an example, which will draw a new rectangle div atop the element's bounding-box without padding and border boxes.
let marker;
scale.onclick = e => {
element.classList.toggle('scaled');
drawRect();
}
boxSizing.onclick = e => {
element.classList.toggle('boxSized');
drawRect();
}
function drawRect() {
// remove previous marker if any
if (marker && marker.parentNode) {
marker.remove();
marker = null;
}
// first get the border and padding values
let computed = getComputedStyle(element);
let borderLeft = parseFloat(computed.borderLeftWidth);
let borderWidth = borderLeft + parseFloat(computed.borderRightWidth);
let borderTop = parseFloat(computed.borderTopWidth);
let borderHeight = borderTop + parseFloat(computed.borderBottomWidth);
let paddingLeft = parseFloat(computed.paddingLeft);
let paddingWidth = paddingLeft + parseFloat(computed.paddingRight)
let paddingTop = parseFloat(computed.paddingTop);
let paddingHeight = paddingTop + parseFloat(computed.paddingBottom);
// get the current bounding rect, including the border-box
let rect = element.getBoundingClientRect();
// we need to get the current scale since the computed values don't know about it...
let scale = 1 / (element.offsetHeight / rect.height);
// the real displayed height and width without border nor padding
let height = rect.height - ((borderHeight + paddingHeight) * scale);
let width = rect.width - ((borderWidth + paddingWidth) * scale);
// create our rectangle
marker = document.createElement('div');
marker.classList.add('marker');
marker.style.height = height + 'px';
marker.style.width = width + 'px';
// we need to scale border + padding again
marker.style.top = (rect.top + (borderTop + paddingTop) * scale) + 'px';
marker.style.left = (rect.left + (borderLeft + paddingLeft) * scale) + 'px';
document.body.append(marker);
}
#element {
width: 250px;
border: 0.5em solid green;
padding: 0.5em;
margin-top: 12px;
}
#element.scaled {
transform: scale(2);
transform-origin: top left;
}
#element.boxSized {
box-sizing: border-box;
}
.marker {
position: fixed;
width: 3px;
background: rgba(0, 0, 0, .3)
}
<label>scale
<input id="scale" type="checkbox">
</label>
<label>box-sizing
<input id="boxSizing" type="checkbox">
</label>
<div id="element">
Hello
<br> world
</div>
when you set box-sizing as border-box:
The width and height properties include the content, the padding and border, but not the margin
So when you use getComputedStyle to get a element's height, of course it includes the height of padding and border.
you can have a look at box-sizing property and css box model

Write text in random location

I am fairly new to javascript and I am trying to create an interface where multiple users input a string of text into a form, and after submitting, the text appears randomly on the page along with the previous users input. Is there a way to do this with javascript? I am mostly having issues with finding a way to write text to a specific location on the screen.
The idea is that you create a new element each time, and set the following CSS on it so as to be able to position it manually:
position: absolute;
left: _px;
top: _px;
where _ can be generated through Math.random(). This function returns a decimal value between 0 and 1, so stretch and round it appropriately to get random integer pixel coordinates on the screen: http://jsfiddle.net/6eTcD/2/.
​document.querySelector("form").addEventListener("submit", function(e) {
e.preventDefault();
var fullWidth = window.innerWidth;
var fullHeight = window.innerHeight;
var text = this.querySelector("input[type='text']").value;
var elem = document.createElement("div");
elem.textContent = text;
elem.style.position = "absolute";
elem.style.left = Math.round(Math.random() * fullWidth) + "px";
elem.style.top = Math.round(Math.random() * fullHeight) + "px";
document.body.appendChild(elem);
});
You can try a div with absoloute positioning like this:
in your html code:
my text
In you CSS
#mydiv {
position:absolute;
top:0;
right:0;
width:200px;
}
You can position your div with jquery
$('div.example').css('top', 100);
References:
Div Style
jQuery change style

Using Zigfu (kinect) in canvas element of HTML5

I went through the initial tutorial for making a user radar on Zigfu's website. I am having trouble getting this radar to work in the canvas element.
I want to using the drawing methods in canvas, so I don't want it in the container.
Here is my code so far taken directly from the tutorial. Thanks so much for reading!
function loaded() {
var radardiv = document.getElementById('container');
var radar = {
onuserfound: function (user) {
var userdiv = document.createElement('div');
userdiv.className = 'user';
user.radarelement = userdiv;
radardiv.appendChild(user.radarelement);
},
onuserlost: function (user) {
radardiv.removeChild(user.radarelement);
},
ondataupdate: function (zigdata){
for (var userid in zigdata.users){
var user = zigdata.users[userid];
var pos = user.position;
//console.log(pos);
var el = user.radarelement;
var parentElement = el.parentNode;
var zrange = 2000;
var xrange = 700;
var pixelwidth = parentElement.offsetWidth;
var pixelheight = parentElement.offsetHeight;
var heightscale = pixelheight / zrange;
var widthscale = pixelwidth / xrange;
el.style.left = (((pos[0] / xrange) + 0.5) * pixelwidth - (el.offsetWidth / 2)) + "px";
el.style.top = ((pos[2] / zrange) * pixelheight - (el.offsetHeight / 2)) - 150 + "px";
}
}
};
zig.addListener(radar);
}
document.addEventListener('DOMContentLoaded', loaded, false);
<body>
<div id = 'container'></div>
</body>
</html>
<style>
div#container {
width: 800px;
height: 600px;
border: 1px solid black;
overflow: hidden;
}
div.user {
position: relative;
width: 10px;
height: 10px;
background-color: red;
}
It seems you are missing tags around the javascript, as well as some css for the users radar. Also - your 'container' div is missing a >
Try copying the code from the bottom of http://zigfu.com/en/zdk/tutorials/, or - check out http://zigfu.com/en/zdk/recipes/#omercy16 for a cleaner implementation of the users radar.
The radar used in the tutorial makes use of DOM div placement and positioning.
Unfortunately this can't be used inside the canvas element.
There are ways to overlay over the canvas and other workarounds. See: Placing a <div> within a <canvas>
You can also take the data directly from the plugin and draw to the canvas yourself.
Here is a demo using three.js and zigfu to draw the skeleton onto a canvas:
http://blog.kinect.tonkworks.com/post/30569123887/kinect-online-app-javascript-dev-tutorial-1

Can I assign offsetHeight to style.top?

In javascript, can I assign like this:
var tempHeight = document.getElementById("header").offsetHeight;
document.getElementById("content").style.top = tempHeight;
After running above script, will the div "content" have "top" propery = tempHeight?
I tried but it does not work, any suggestions?
Thanks!
You just need a unit
document.getElementById("content").style.top = String(tempHeight) + "px";
The top CSS property expects a unit along with the value. Adding px should work:
document.getElementById("content").style.top = tempHeight + "px";
You have to add + 'px' or some unit to the end of the style.top statement.
Also, #content must have the position style set
http://jsfiddle.net/BshuC/
CSS
#header {
height: 200px;
}
#content { position: absolute; }
JS
var tempHeight = document.getElementById("header").offsetHeight;
document.getElementById("content").style.top = tempHeight + 'px';

Categories

Resources