Using JS to modify a style element with math operations - javascript

I am trying to use a JS sheet to make a button that when pressed, grows a square by 50 pixels (both height and width). I want to do this by a math operator (addition) and not by declaring a new value, so the button can be depressed multiple times.
This is for an exercise in combining multiple coding languages. I am allowed to change the HTML as needed to make it work. Also, the original exercise is just to make the button only work once (so setting a new pixel size works easily for that)
Here is the HTML and JavaScript I am working with:
document.getElementById("button1").addEventListener("click", growByFifty);
function growByFifty() {
document.getElementById("box").style.height += 50 + "px";
document.getElementById("box").style.width += 50 + "px";
};
<div id="box" style="height:150px; width: 150px; background-color:orange; margin:25px"></div>
<button id="button1">Grow</button>
When the button is clicked, nothing happens.

Using the "offsetHeight" you can get the height of the element.
Try this:
document.getElementById("box").style.height = document.getElementById("box").offsetHeight +50+'px'

The problem is style.height and style.width don't return the element's dimensions. You need to use offsetHeight and offsetWidth for that. I corrected your JavaScript code:
document.getElementById("button1").addEventListener("click", growByFifty);
function growByFifty() {
let currentHeight = document.getElementById("box").offsetHeight,
currentWidth = document.getElementById("box").offsetWidth;
document.getElementById("box").style.height = (currentHeight + 50) + "px";
document.getElementById("box").style.width = (currentWidth + 50) + "px";
};

Related

Position image randomly after each onclick event (image must be in div tag)

So I am very new (as I am sure my code shows :P) and I must create code that contains an image in a div tag. It must be this way. Once the document is opened the image(div) is to be displayed at a random position. Each time the image(div) is clicked, the image alone moves to another random position. It does not replicate itself. Just moves. I have had other "better" attempts but with all my editing and changing all I get is the image in the top left corner.
I tried numerous things that all failed to work. Obviously failed because the code was terrible.
I have tried a variation of onclick events etc...I know many errors are visible. This is not one of those instances where I believe the logic is sound and it should work. This is a "what am I at" instance
<script>
function fpos () {
var img = document.getElementById('myImage') //is this needed at all?
var x = Math.floor(Math.random()*600);
var y = Math.floor(Math.random()*600);
var z = Math.floor(Math.random()*600);
}
function rmove() {
img.style.top = x + 'px';
img.style.left = y + 'px';
}
</script>
</head>
<body onload="fpos">
<div style = position:absolute; onclick="rmove" >
<img id="myImage" src='images/iasip.jpeg'> </img>
</div>
</body>
So, first, don't take this the wrong way my man but you gotta post some code to show us what you're working with. Makes all the difference for troubleshooting.
That said, you're gonna need to do with with JS. First target the image element. Can use querySelector to hit either the class or id or just getElementById.
Then add an event listener to render it at a random coordinate. Like this.
<div id="imageContainer">
<img src="your-image-source" alt="your-image-description">
</div>
<script>
// get the image container element
var imageContainer = document.getElementById("imageContainer");
// set the initial random position for the image container
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
// when the image container is clicked, set a new random position
imageContainer.addEventListener("click", function() {
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
});
</script>
Can either do that inline like in the example or add it to your script file.
Here is a working example I just threw together.
Basically you need to create a function that moves the image each time by calculating a random number for the height and width and then multiplying by the size of the window so that number can span the full width/length of the screen.
Then you can add 'px' to the end of the calculation to use pixels as the unit and set that to the left and top properties of the image to move it that far from the left and top of the screen using absolute position (coordinates).
window.onload = function() {
move()
}
function move() {
let img = document.getElementById('logo')
img.style.left = Math.floor(Math.random() * window.innerWidth) + "px"
img.style.top = Math.floor(Math.random() * window.innerHeight) + "px"
}
#logo {
height: 100px;
position: absolute;
}
<div>
<img onclick='move()' id='logo' src='https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/LEGO_logo.svg/2048px-LEGO_logo.svg.png' />
</div>
Don't worry, try to isolate some code so we can review it.
Once the document is opened the image(div) is to be displayed at a
random position.
By inspecting an element's properties with Right Click > Inspect > Property you'll find all javascript properties that you have access to once you select the element with a selector (document.querySelector for example)
Try something with that, i think that the easiest way is to use
element.style.transform = "translate(x,y)"
like x.style.transform = "translate(10px, 20px)";

Foundation 6: How to set .is-open-right translateX value with JavaScript

I am building a website with Foundation 6 using CSS instead of SCSS. I'm using the responsive off-canvas drill-down menu on small screens, and by default, the off-canvas menu width is 250px.
Problem: I would like this to be the full width of the browser window instead.
Setting the Width
I have used JavaScript to dynamically set the .off-canvas.position-right width to the width of the window, and right to the negative width of the window. I've also set the .off-canvas .drilldown max-width to the width of the window.
This works well, and here's how I did it:
function setOffCanvasWidth() {
var windowWidth = window.innerWidth,
offCanvasRight = document.querySelector( '.off-canvas.position-right' ),
isDrilldown = document.querySelector( '.off-canvas .is-drilldown' );
offCanvasRight.style.width = windowWidth + "px";
offCanvasRight.style.right = "-" + windowWidth + "px";
isDrilldown.style.maxWidth = windowWidth + "px";
}
setOffCanvasWidth();
I'm happy with this part, but it only solves half of the problem.
Moving the Off-Canvas
In addition to dealing with the width of the menu, .is-open-right is moving everything over by -250px using transform: translateX().
I tried including these lines in my function to set the transform: translateX() value to the negative width of the window:
var offCanvasWrapperInner = document.querySelector( '.off-canvas-wrapper-inner.is-off-canvas-open.is-open-right' );
offCanvasWrapperInner.style.transform = "translateX(-" + windowWidth + "px)";
But this didn't work. I think it has to do with the fact that .off-canvas-wrapper-inner doesn't have the class .is-open-right when the window loads. That class is added dynamically after clicking the hamburger toggle button, which has a class of .menu-icon. So I tried adding a click event listener, but it still doesn't work.
Here is my JS code in its entirety:
function setOffCanvasWidth() {
var windowWidth = window.innerWidth,
offCanvasRight = document.querySelector( '.off-canvas.position-right' ),
isDrilldown = document.querySelector( '.off-canvas .is-drilldown' ),
menuIcon = docuemnt.querySelector( '.menu-icon' ),
offCanvasWrapperInner = document.querySelector( '.off-canvas-wrapper-inner.is-off-canvas-open.is-open-right' );
offCanvasRight.style.width = windowWidth + "px";
offCanvasRight.style.right = "-" + windowWidth + "px";
isDrilldown.style.maxWidth = windowWidth + "px";
menuIcon.addEventListener( 'click', function() {
offCanvasWrapperInner.style.transform = "translateX(-" + windowWidth + "px)";
} );
}
setOffCanvasWidth();
Where Am I Going Wrong?
I'm not looking for anyone to code the solution for me, necessarily, but any feedback and direction on how I might set the .is-open-right translateX value would be very helpful.
Here is the entire project code: https://github.com/paulshryock/paulshryock/releases/tag/v0.0.1
Here is a live demo: https://paulshryock.github.io/paulshryock/
Use a translateX value of -100%. Percentage transformations are based on the element's dimensions, so 100% would be equal the element's width. At this point no JavaScript would be needed.
On that note, I would recommend setting the menu's left to 100% instead of setting right to the negative width.

Calculating width of scrollbar and using result in calc() css

I want to calculate the width of the scrollbar so that I use the result in a CSS calc() declaration.
At the moment, I assume that the width of the scrollbar is always 17px, like this:
body {
width:calc(100vw - 17px);
}
.container {
max-width:calc(100vw - 17px);
}
The problem with this is when you choose a different browser zoom %, the width of the scrollbar changes. So I want to use the result of the calculation to do something along these lines:
body {
width:calc(100vw - CALCULATED SCROLL-BAR WIDTH);
}
.container {
max-width:calc(100vw - CALCULATED SCROLL-BAR WIDTH);
}
EDIT: I've now solved the problem with the help of this question
The JavaScript used to calculate the scrollbar width (though, I have found you require an interval to get it to autoupdate):
function getScrollbarWidth() {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
My code (which is used to embed the result of the function into a CSS calc() declaration).
$('body').css({
'width':'calc(100vw - ' + getScrollbarWidth() + 'px)'
});
$('.container').css({
'max-width':'calc(100vw - ' + getScrollbarWidth() + 'px)'
});
Actually, you can get the scrollbar width just with css and custom properties (and completely without javascript):
body {
--scrollbar-width: calc(100vw - 100%);
}
Then you can use this variable in a child element like this:
.container {
max-width: calc(100vw - var(--scrollbar-width));
}
This is because 100vw is always the inner width of the view, but the 100% of the body does not include the scrollbar.
Expanding jonas_jonas's answer, it can work but if .container must have the same width as the body.
If that's not the case, even so you can make it work with vanilla JS, defining a CSS property like this
document.body.style.setProperty(
"--scrollbar-width",
`${window.innerWidth - document.body.clientWidth}px`
);
And then you can use it in CSS
.container {
max-width: calc(100vw - var(--scrollbar-width));
}
Why you need so much code to do that?
The easy way with plain javascript it's:
$('body').css({
'width':'calc(100vw - ' + (window.innerWidth - document.body.clientWidth) + 'px)'
});

setting min-height via jquery

This is the code I'm trying to use in order to set the height of a background div to always cover at least the background of the maindiv + the footer I have set up.
var bgheight = $('.maindiv').css("height");
$('#background').css('min-height', bgheight+'75px');
For some reason the code won't even apply to the #background div and I'm starting to run out of ideas.
When I do something like this
var bgheight = $('.maindiv').height();
$('#background').css({'min-height':beheight+'75px'});
The style is applied but the min-height is gigantic, like almost 50000px tall.
Any ideas?
You are making a string concatenation, not a sum.
Try this:
var bgheight = $('.maindiv').height();
$('#background').css({'min-height': (beheight + 75) + 'px'});
To ensure you are not concatenating strings, you can set Number() function.
var bgheight = Number($('.maindiv').height());
$('#background').css({'min-height': (beheight + 75) + 'px'});
OR (two parameters instead of object)
$('#background').css('min-height', (beheight + 75) + 'px');

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.

Categories

Resources