set new element class property value - javascript

How to add 10px to an css class property with javascript?
for example:
var bigger = document.getElementsByClassName("size200").style.width;
bigger + 10;

To achieve expected result ,use below option
let width = document.getElementsByClassName("size200")[0].clientWidth + 10;
document.getElementsByClassName("size200")[0].style.width = width + 'px'
codepen - https://codepen.io/nagasai/pen/roazyL
let width = document.getElementsByClassName("size200")[0].clientWidth + 10;
document.getElementsByClassName("size200")[0].style.width = width + 'px'
.size200{
width: 200px;
border: 1px solid black;
height: 20px
}
.size100{
width: 200px;
border: 1px solid black;
height: 20px
}
<div class="size200">
</div>
<div class="size200">
</div>
<div class="size100">
</div>
Above solution will change only first class , to apply for every element with same class
for(var i = 0; i < document.getElementsByClassName("size200").length; i++){
let width = document.getElementsByClassName("size200")[i].clientWidth + 10;
document.getElementsByClassName("size200")[i].style.width = width + 'px'
}
codepen - https://codepen.io/nagasai/pen/vvEJRz

setTimeout(() => {
// get width
let width = window.getComputedStyle(document.querySelector('.some-class')).width;
width = +width.substr(0,width.length-2);
let newWidth = `${width+100}px`;
// set style
Array(document.getElementsByClassName('some-class').length)
.fill()
.map((_, index) => {
document.getElementsByClassName('some-class')[index].style.width = newWidth;
});
}, 1000)
.some-class {
width: 200px;
height: 200px;
background-color: red;
transition: all .5s;
}
<div class="some-class"></div>
<p>
wait 1s
</p>
<div class="some-class"></div>

Related

I am trying to make an object resize based on the distance between the cursor and said object. The Y value I get is always naN

This is my js code, I always get a naN as a result of my Y variable
var elm = document.getElementById("qrcode");
elm.addEventListener("mousemove",getcordd , false)
function getcordd(ev){
var bdns = ev.target.getBoundingClientRect();
var x = ev.clientx - bdns.left;
var y = ev.clienty - bdns.top;
console.log (`${y}`);
}
I got carried away here, but reading that you wanted to know about changing an element's size based on mouse movements, I threw this thing together. Take a look and if you have any questions about it, let me know in a comment. Cheers
var elm = document.getElementById("qrcode");
document.getElementById("mousecapture").addEventListener("mousemove", getcordd, false)
function getcordd(ev) {
var bdns = ev.target.getBoundingClientRect();
// console.log(bdns)
var x = ev.clientX - bdns.left;
var y = ev.clientY - bdns.top;
// console.log(`${y}`, `${x}`, bdns.left, bdns.top);
// resize the div
//console.log(ev.clientX, ev.clientX/bdns.width,ev.clientY, ev.clientY/bdns.height)
let min = 10,
max = 200; // min width/height;
elm.style.width = Math.max(min, Math.min(max, Math.round(max * Math.abs(x / bdns.width)))) + "px";
elm.style.height = Math.max(min, Math.min(max, Math.round(max * Math.abs(y / bdns.height)))) + "px";
}
html,
body,
#container {
width: 100%;
height: 100%;
background: #f0f0f0;
}
#qrcode {
width: 50px;
height: 50px;
background: #f00;
color: #fff;
text-align: center;
display: inline-block;
}
#mousecapture {
width: 100px;
height: 100px;
border: 1px solid #ccc;
background: #fff;
float: right;
}
<div id='container'>
Move the mouse in the white box
<hr>
<div id='mousecapture'></div>
<div id='qrcode'></div>
</div>

Continually fade background box with each click of the fade button

Brand new to coding. Trying to get "fade" button to fade a little more each time I click it.
I have used this code to grow and shrink the box and I was trying to do the same thing for the opacity:
document.getElementById("growbutton").addEventListener("click", function() {
var growVariable = 10;
var newValueHeight = parseInt(document.getElementById("box").style.height)
document.getElementById("box").style.height = newValueHeight + growVariable + "px";
var newValueWidth = parseInt(document.getElementById("box").style.width)
document.getElementById("box").style.width = newValueWidth + growVariable + "px";
});
document.getElementById("fadebutton").addEventListener("click", function() {
var opVariable = .2;
var newOpValue = parseInt(document.getElementById("box").style.opacity)
document.getElementById("box").style.opacity = newValueHeight - opVariable;
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px"></div>
<button id="fadebutton">Fade</button>
<button id="growbutton">Grow</button>
Can you tell me what I'm missing so the box fades .2 with each click?
Your existing code produces the error: Uncaught ReferenceError: newValueHeight is not defined. There were a few issues:
You were referencing newValueHeight instead of newOpValue by accident.
parseInt() will return an integer, i.e., if the current opacity is 0.8, parseInt(0.8) returns 1. You need to use parseFloat() to get a floating point back.
Initially, style.opacity is undefined because it has not been set yet. You should use opValue = ... || 1 so that it defaults to 1 if not yet set.
let box = document.getElementById('box'),
fadeBtn = document.getElementById('fadebutton'),
growBtn = document.getElementById('growbutton');
growBtn.addEventListener('click', function() {
let growVariable = 10,
boxHeight = parseInt(box.style.height),
boxWidth = parseInt(box.style.width);
box.style.height = boxHeight + growVariable + "px",
box.style.width = boxWidth + growVariable + "px";
});
fadeBtn.addEventListener("click", function() {
let opVariable = .2,
opValue = parseFloat(box.style.opacity) || 1;
box.style.opacity = opValue - opVariable;
});
<div id="box" style="height: 100px; max-height: 600px; min-height: 5px; width:100px; max-width: 600px; min-width: 5px; background-color:orange; margin:1rem"></div>
<button id="fadebutton">Fade</button>
<button id="growbutton">Grow</button>
You need to use parseFloat when dealing with non-whole numbers or with decimal points as parseInt returns an integer or a whole number
document.getElementById("fadebutton").addEventListener("click", function() {
//var opVariable = .2;
let box = document.getElementById("box")
let currentOpacity = parseFloat(box.style.opacity)
box.style.opacity = currentOpacity - .2
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px;opacity:1"></div>
<button id="fadebutton">
Fade
</button>
document.getElementById("fadebutton").addEventListener("click", function() {
//var opVariable = .2;
let box = document.getElementById("box")
let currentOpacity = parseFloat(box.style.opacity)
box.style.opacity = currentOpacity - .2
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px;opacity:1"></div>
<button id="fadebutton">
Fade
</button>
If you just want to fade the image onclick, you can simply decrement the style.opacity property. Something like this:
const box = document.querySelector('#box');
document.addEventListener('click', e => {
if (e.target.id === 'fadebutton') {
if (box.style.opacity > 0) {
box.style.opacity -= .2;
}
}
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px; opacity: 1"></div>
<button id="fadebutton">Fade</button>

how to make a box reach the edge of a bigger box

javascript beginner here! so i'm trying to do a box(that is inside a larger box) move from the top to the edge of the box. Here's the code:
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5);
function boxmove() {
if (loc == 320) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox">
<div id="boxcont"></div>
</div>
<button id="boxbtn">Move the box</button>
The problem is that the small box doesn't exactly ends up at the edge, it goes more to the right. I tried doing
boxcont.style.left = (loc - 0.5) + "px";
but doesn't work. pretty sure the solution is simple but as a newbie here it's confusing me :p. Oh and i also tried doing ++ to the 0.5 and Number(0.5) so it reads it as a decimal but still doesn't work!
the big gray box is not set to the correct height and width that corresponds with the small red box's movement. You have it going down 1 and to the right 1 every 5 however, your actually going across a rectangle, not a square. set your width and height the same for the gray box and slightly adjust the stopping point to a little bit less.
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5); // every five milliseconds
function boxmove() {
if (loc == 290) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox" style = "height: 320px; width: 320px">
<div id="boxcont" ></div>
</div>
<button id="boxbtn">Move the box</button>
if (loc == 270) {
instead of
if (loc == 320) {
Gets you there.
300px is the width of the containing div and the moving div is 30px wide so 300-30=270px
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5);
function boxmove() {
if (loc == 270) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox">
<div id="boxcont"></div>
</div>
<button id="boxbtn">Move the box</button>

JavaScript itareate over divs and create a new one if doesn't fits

Hello guys I hope you can help me with JavaScript, I'm trying to itarate over some divs, the issue is that when I iterate sometimes a div never change to the other divs, it suppose to be infinite, I will recive thousands of different divs with different height and it should create an other div container in the case it does not fits but I can not achieve it work's, I'm using Vanilla JavaScript because I'm lerning JavaScript Regards.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.big_container{
height: 600px;
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items{
background-color: gray;
height: 50px;
}
.new_container{
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
float: left;
margin-left: 5px;
}
</style>
</head>
<body>
<div class="big_container">
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
<div class="items">6</div>
<div class="items">7</div>
<div class="items">8</div>
<div class="items">9</div>
<div class="items">10</div>
<div class="items">11</div>
<div class="items">12</div>
<div class="items">13</div>
</div>
<div class="new_container">
</div>
</body>
<script>
number = 0
sum = 0
new_container = document.getElementsByClassName('new_container')[number].offsetHeight
divs = document.getElementsByClassName('items')
for ( var i = 0; i < divs.length; i++ ){
sum += this.document.getElementsByClassName( 'items' )[0].offsetHeight
if ( sum <= new_container ){
console.log(sum, "yes")
document.getElementsByClassName("new_container")[number].appendChild( this.document.getElementsByClassName( 'items' )[0] )
} else {
sum = 0
console.log(sum, "NO entra")
nuevo_contenedor = document.createElement('div'); // Creo un contenedor
nuevo_contenedor.className = "new_container";
nuevo_contenedor.setAttribute("style", "background-color: red;");
document.body.appendChild(nuevo_contenedor)
number += + 1
}
}
</script>
</html>
I really apreciate a hand.
I know that I'm late, but there is my approach how this can be done.
// generate items with different height
function generateItems(count) {
const arr = [];
for (let i = 0; i < count; i++) {
const div = document.createElement("DIV");
const height = Math.floor((Math.random() * 100) + 10);
div.setAttribute("style", `height: ${height}px`);
div.setAttribute("class", "items");
const t = document.createTextNode(i + 1);
div.appendChild(t);
arr.push(div);
}
return arr;
}
function createNewContainer(height) {
const new_container = document.createElement("DIV")
new_container.setAttribute("class", "new_container");
new_container.setAttribute("style", `height: ${height}px`)
document.body.appendChild(new_container);
return new_container;
}
function breakFrom(sourceContainerId, newContainerHeight) {
const srcContainer = document.getElementById(sourceContainerId);
const items = srcContainer.childNodes;
let new_container = createNewContainer(newContainerHeight);
let sumHeight = 0;
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (item.offsetHeight > newContainerHeight) {
// stop!!! this item too big to fill into new container
throw new Error("Item too big.");
}
if (sumHeight + item.offsetHeight < newContainerHeight) {
// add item to new container
sumHeight += item.offsetHeight;
new_container.appendChild(item.cloneNode(true));
} else {
// create new container
new_container = createNewContainer(newContainerHeight);
new_container.appendChild(item.cloneNode(true));
// don't forget to set sumHeight)
sumHeight = item.offsetHeight;
}
}
// if you want to remove items from big_container
// for (let i = items.length - 1; i >= 0; i--) {
// srcContainer.removeChild(items[i]);
// }
}
// create big container with divs
const big_container = document.getElementById("big_container");
const items = generateItems(13);
items.forEach((div, index) => {
big_container.appendChild(div);
});
breakFrom("big_container", 300);
#big_container {
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items {
background-color: gray;
border: 1px solid #000000;
text-align: center;
}
.new_container {
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
border: 1px solid red;
float: left;
margin-left: 5px;
}
<div id="big_container"></div>
This example gives you the ability to play with divs of random height. Hope, this will help you.

Div is not starting from a random position

First of all i have seen many answer in stakeoverflow but none of these helped me!!! I want to start my div from a random position and then it will move. Rather then it shows from a static position and then it comes to a random position and then it start to move. I tried to declare my top and left by javascript in
$( document ).ready(function()
but that does not help
HTML
<div class="ballarea" id="ballarea1">
<div class="circle type" id="ball"></div>
</div>
CSS
.circle{
border-radius: 50%;
border: thin;
border-color: blue;
}
.type {
width: 20px;
height: 20px;
border: 5px solid blue;
position: relative;
}
.ballarea{
width: 300px;
height: 400px;
border: solid black;
overflow: hidden;
position: relative;
}
JavaScript
var i=0;
var j=0;
function ballMove(){
var d=document.getElementById("ball");
var temp=i;
if(i<1)
{
i = Math.floor(Math.random() * (200));
j = Math.floor(Math.random() * (200));
}
for(;i<2+temp;i++,j++)
{
d.style.left=i+"px";
d.style.top=j+"px";
}
//document.getElementById('ball').style.display = 'block';
}
function timeChange()
{
setInterval( ballMove, 500);
}
Now at first it starts from a static position like the following and then it start from a random position. I want to show it from a random position not from a static position
Try hiding it at first, because your script run when your DOM is ready.
<div class="ballarea" id="ballarea1">
<div class="circle type" id="ball" style="display:none"></div>
</div>
Then when your script is running, show it
var i = 0;
var j = 0;
function randomBall(){
var d = document.getElementById("ball");
i = Math.floor(Math.random() * (200));
j = Math.floor(Math.random() * (200));
d.style.left = i+"px";
d.style.top = j+"px";
d.style.display = "block";
}
function ballMove(){
var d=document.getElementById("ball");
i += 2;
j += 2;
d.style.left = i+"px";
d.style.top = j+"px";
}
function timeChange()
{
randomBall();
setInterval( ballMove, 500);
}

Categories

Resources