How to dynamically resize 3 divs on window.resize? - javascript

I have the following HTML:
<div style="min-width:1024px;max-width:82%;margin:0 auto;overflow:auto">
<div style="height:344px;width:100%;float:left;margin-top:72px"></div>
<div style="width:100%;float:left;">
<div id="left" class="radius" style="height:700px;width:220px;background:#fff;float:left"></div>
<div id="middle" class="radius" style="width:760px;background:#fff;float:left;margin:0px 18px;">
<div style="height:700px;width:100%;float:left"></div>
</div>
<div id="right" class="radius" style="height:700px;width:280px;background:#fff;float:left"></div>
</div>
</div>
and script:
function scalling() {
var a = $(window).width();
if (a < '1300') {
var def = a * 82 / 100,
l = 22000 * def / 10,
m = 76000 * def / 10,
p = 28000 * def / 10;
$('#left').css('width', l);
$('#middle').css('width', m);
$('#right').css('width', p);
} else {
$('#left').css('width', '220px');
$('#middle').css('width', '760px');
$('#right').css('width', '280px');
}
}
scalling();
$(window).resize(function () {
scalling();
});
It works but add size to divs in oder way when window is scaling to be biger divs are smaler and when window is smaller the divs are bigger
Sorry for my bad anglish

You could simply use this CSS statement:
#media ( min-width :1300px){
selector{
width: constant-value;
}
}
#media ( max-width :1300px){
selector{
width: percent-value;
}
}

Related

HTML/CSS/JS Random Div Position without Overlap Not Working

I am attempting to make a webpage that randomly positions divs across the page on loading without them overlapping. I found code online that does exactly what I want it to, (Linked Here) but I am having issues with the code...
I copied all of the components from the above link into a pre-existing site, but it does not work. All of the divs appear to be overlapping in the top right corner of the page. A commenter said it worked for them, but I don't see why it wouldn't work on my computer.
I would appreciate any help in making this feature work, as I would love to use it on a website I am working on. Below is a photo of what the page looks like on load...
https://imgur.com/lnby2gw
;(() => {
"use strict";
const TRIES_PER_BOX = 50;
const randUint = range => Math.random() * range | 0;
const placing = [...document.querySelectorAll(".random")].map(el => Bounds(el, 5));
const fitted = [];
const areaToFit = Bounds();
var maxTries = TRIES_PER_BOX * placing.length;
while (placing.length && maxTries > 0) {
let i = 0;
while (i < placing.length) {
const box = placing[i];
box.moveTo(randUint(areaToFit.w - box.w), randUint(areaToFit.h - box.h));
if (fitted.every(placed => !placed.overlaps(box))) {
fitted.push(placing.splice(i--, 1)[0].placeElement());
} else { maxTries-- }
i++;
}
}
function Bounds(el, pad = 0) {
const box = el?.getBoundingClientRect() ?? {
left: 0, top: 0,
right: innerWidth, bottom: innerHeight,
width: innerWidth, height: innerHeight
};
return {
l: box.left - pad,
t: box.top - pad,
r: box.right + pad,
b: box.bottom + pad,
w: box.width + pad * 2,
h: box.height + pad * 2,
overlaps(bounds) {
return !(
this.l > bounds.r ||
this.r < bounds.l ||
this.t > bounds.b ||
this.b < bounds.t
);
},
moveTo(x, y) {
this.r = (this.l = x) + this.w;
this.b = (this.t = y) + this.h;
return this;
},
placeElement() {
if (el) {
el.style.top = (this.t + pad) + "px";
el.style.left = (this.l + pad) + "px";
el.classList.add("placed");
}
return this;
}
};
}
})();
.random {
position: absolute;
margin: 2;
border: 1px solid black;
font-size: xx-large;
top: 0px;
left: 0pc;
}
.placed {
color: red;
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<link rel="stylesheet" href="assets/css/style.css">
<script src="assets/js/script.js"></script>
<script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="random">Div 1</div>
<div class="random">Div 2</div>
<div class="random">Div 3</div>
<div class="random">Div 4</div>
<div class="random">Div 5</div>
<div class="random">Div 6</div>
<div class="random">Div 7</div>
<div class="random">Div 8</div>
<div class="random">Div 9</div>
<div class="random">Div 10</div>
<div class="random">Div 11</div>
<div class="random">Div 12</div>
</body>
</html>

comper div A to div B height & only if A is higher add height to div b

im trying to compare 2 divs height and just in case div A is higher add height to div B ( I have a few divs that some of the height is not heeded any adjustment
and im trying to achieve it using js but any other idea is as good
`<div class="row">
<div class="well">
<div class="col-md-1 Acomp">
<button class="btn">If this on is higher Make this one equal </button >
</div>
<div class="col-md-10 Acomp">
<p>most of the time this one height if higher no need to adjust </p>
</div>
</div>
</div>`
var elements = document.querySelectorAll(".Acomp"),
heights = [];
console.log(heights);
[].forEach.call(elements,
function(each) {
heights[heights.length] = getComputedStyle(each, null).getPropertyValue("height");
});
heights.sort(function(a, b) {
return parseFloat(b) - parseFloat(a);
newFunction(a, b);
}));
function newFunction(a, b) {
if (a < b) {
[].forEach.call(elements,
function(each) {
each.style.height = heights[0];
}); }; }
`
I think you're making the problem more complex than it really is.
Here's my solution for two divs:
/* ------------THE FIRST SOLUTION: BEGIN------------ */
const elements = document.querySelectorAll(".Acomp")
if (elements[1].clientHeight < elements[0].clientHeight) {
elements[1].style.height = elements[0].clientHeight + "px"
}
/* -------------THE FIRST SOLUTION: END------------- */
// here're two additional functions - not nicely written, but show that
// you don't just add a number to height, because that's a string
document.getElementsByClassName('addHeightB')[0].addEventListener('click', function(e) {
elements[1].style.height = parseInt(elements[1].style.height, 10) + 30 + "px"
})
document.getElementsByClassName('subtractHeightB')[0].addEventListener('click', function(e) {
elements[1].style.height = parseInt(elements[1].style.height, 10) - 30 + "px"
})
// here's the reset function for the first button
document.getElementsByClassName('setHeightToA')[0].addEventListener('click', function(e) {
elements[1].style.height = elements[0].clientHeight + "px"
})
<div class="row">
<div class="well">
<div class="col-md-1 Acomp">
<button class="btn setHeightToA">If this on is higher Make this one equal </button>
</div>
<div class="col-md-10 Acomp" style="background-color: gray; color: white;">
<p>most of the time this one height if higher no need to adjust </p>
</div>
</div>
</div>
<button class="btn addHeightB">Add 30px height to B</button>
<button class="btn subtractHeightB">Subtract 30px height from B</button>
Here's the solution for n divs:
(actually two solutions)
const elements = document.querySelectorAll(".Acomp")
let heights = []
for (let element of Object.values(elements)) {
heights.push(element.clientHeight)
}
/* ------------THE SECOND SOLUTION: BEGIN----------- */
// if the first element is the highest, then all elements should have the same height
if (elements[0].clientHeight === Math.max.apply(null, heights)) {
for (let element of Object.values(elements)) {
element.style.height = elements[0].clientHeight + "px"
}
}
/* -------------THE SECOND SOLUTION: END------------ */
/* ------------THE THIRD SOLUTION: BEGIN------------ */
// make all elements as high as the highest
heights = heights.sort().reverse()
for (let element of Object.values(elements)) {
element.style.height = heights[0] + "px"
}
/* -------------THE THIRD SOLUTION: END------------- */
/* ------------THE THIRD B SOLUTION: BEGIN------------ */
// make all elements as high as the highest
const maxHeight = Math.max.apply(null, heights)
for (let element of Object.values(elements)) {
element.style.height = maxHeight + "px"
}
/* -------------THE THIRD B SOLUTION: END------------- */
<div class="row">
<div class="well">
<div class="col-md-1 Acomp">
<button class="btn setHeightToA">If this on is higher Make this one equal </button>
</div>
<div class="col-md-10 Acomp" style="background-color: gray; color: white;">
<p>most of the time this one height if higher no need to adjust </p>
</div>
</div>
</div>
<button class="btn addHeightB">Add 30px height to B</button>
<button class="btn subtractHeightB">Subtract 30px height from B</button>

Change CSS of inner div when scroll reaches that div

I am attempting to implement a scroll function where the CSS of the inner div's change when it reaches a certain height from the top.
var $container = $(".inner-div");
var containerTop = $container.offset().top;
var documentTop = $(document).scrollTop();
var wHeight = $(window).height();
var minMaskHeight = 0;
var descriptionMax = 200;
var logoMin = -200;
var maskDelta = descriptionMax - minMaskHeight;
var $jobOverview = $container.find(".right");
var $jobLogo = $container.find(".left");
var curPlacementPer = ((containerTop - documentTop) / wHeight) * 100;
var topMax = 85;
var center = 20;
var bottomMax = -15;
//console.log("Placement: " + curPlacementPer);
function applyChanges(perOpen) {
var maskHeightChange = maskDelta * (perOpen / 100);
var opacityPer = perOpen / 100;
var newDescriptionLeft = descriptionMax - maskHeightChange;
var newLogoLeft = logoMin + maskHeightChange;
if (newDescriptionLeft <= 0) newDescriptionLeft = 0;
if (newLogoLeft >= 0) newLogoLeft = 0;
if (opacityPer >= 1) opacityPer = 1;
$jobOverview.css({
transform: "translate(" + newDescriptionLeft + "%,-50%)",
opacity: opacityPer
});
$jobLogo.css({
transform: "translate(" + newLogoLeft + "%,-50%)",
opacity: opacityPer
});
}
if (window.innerWidth > 640) {
$container.removeClass("mobile");
// console.log("Placement: " + curPlacementPer);
if (curPlacementPer <= topMax /*&& curPlacementPer >= center*/ ) {
var perOpen = ((topMax - curPlacementPer) / 25) * 100;
applyChanges(perOpen);
} else if (curPlacementPer < center /*&& curPlacementPer >= bottomMax*/ ) {
var perOpen = (((bottomMax - curPlacementPer) * -1) / 25) * 100;
applyChanges(perOpen);
} else {
$jobOverview.css({
transform: "translate(200%,-50%)",
opacity: "0"
});
$jobLogo.css({
transform: "translate(-300%,-50%)",
opacity: "0"
});
}
<div class="outer-div">
<div class="inner-div first">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div second">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div third">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div fourth">
<div class="left"></div>
<div class="right"></div>
</div>
</div>
Currently, all of the inner div's gets changed at the same time.
I noticed that when I change the $container class to equal '.first' and specify it more, it works.
Is there any way to make the inner div's change separately, relative to its height from the top? Any way I can iterate the scroll function so I can add more inner div's in the future and not have to worry about changing my scroll function?
In raw JavaScript, this is my answer:
// Define the element -- The '#fooBar' can be changed to anything else.
var element = document.querySelector("#fooBar");
// Define how much of the element is shown before something happens.
var scrollClipHeight = 0 /* Whatever number value you want... */;
// Function to change an element's CSS when it is scrolled in.
const doSomething = function doSomething() {
/** When the window vertical scroll position plus the
* window's inner height has reached the
* top position of your element.
*/
if (
(window.innerHeight + window.scrollY) - (scrollClipHeight || 0) >=
element.getBoundingClientRect().top
)
// Generally, something is meant to happen here.
element.style = "/* Yay, some CSS! */"
};
// Call the function without an event occurring.
doSomething();
// Call the function when the 'window' scrolls.
addEventListener("scroll", doSomething, false)
This is the method I use. If there are other methods, I'd love to see them as well but this is my answer for now.
consider using 3rd party jQuery plugin for easier job, like one of these:
https://github.com/xobotyi/jquery.viewport
or
https://github.com/zeusdeux/isInViewport
then you can have additional element selector e.g.: ":in-viewport"
so you can:
$(window).on('scroll',function() {
$('div').not(':in-viewport').html('');
$('div:in-viewport').html('hello');
});
Check if current scroll offset from top is bigger than the element offset from the top:
$(window).scroll(function() {
var height = $(window).scrollTop();
var element = $('#changethis'); //change this to your element you want to add the css to
if(height > element.offset().top) {
element.addClass('black'); //add css class black (change according to own css)
}
});
Html:
<div id="changethis">Test</div>
Css:
body
{
height:2000px;
}
.black
{
background-color:black;
color:white;
padding:20px;
}
Demo:
https://codepen.io/anon/pen/WZdEap
You could easily implement this in your existing code.
Below is the sample snippet code, Hope it'll work for you:
$(document).ready(function(){
topMax = 100;
topMin = 25;
$(document).scroll(function(){
$('.inner-div').each(function(){
if($(this).offset().top-$(window).scrollTop()<=topMax && $(this).offset().top-$(window).scrollTop()>=topMin){
$(this).css({'background':'#c7c7c7'});
}else{
$(this).css({'background':'inherit'});
}
});
});
});
div{
width:100%;
border:1px solid red;
padding:5px;
}
div.inner-div{
border: 1px dashed green;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer-div">
<div class="inner-div first">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div second">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div third">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div fourth">
<div class="left"></div>
<div class="right"></div>
</div>
</div>
Happy to help you! :)

jquery : Text on moving div (infinite wall)

I need to make an infinite wall which will pull text from database and show it on the wall. I have written this code -
$(function() {
var x = 0;
var y = 100.0;
var z=0;
setInterval(function() {
x -= 0.1;
y -= 0.1;
z++;
if (x <= -100.0){
$("#h1d1").html("loop div 1 :" + z);
x = 0;
}
if (y <= 0){
$("#h1d2").html("loop div 2 :" + z);
y = 100.0;
}
$('#movimg1').css('left', x + "%");
$('#movimg2').css('left', y + "%");
}, 10);
$("#stopbutton").click(function() {
$('#movimg1').stop();
});
})
But the text are not behaving as I wanted it to behave. It changes in the middle of the screen which I don't want. I need the text to change when it is out of view.
https://jsfiddle.net/oa0wdxcx/2/
A couple more things- I want to add a play/pause button. Any advice on how I could achieve that would be much appreciated. Also I want the divs to be inside #wrap div, but if I change the position attribute to relative, the divs don't remain together.
Thanks in advance.
The problem was in the conditions.
if (x <= -100.0) {
z++;
$("#h1d1").html("loop div 1 :" + z);
x = 100; /* change this line */
}
if (y <= -100.0) { /* change this line */
w++;
$("#h1d2").html("loop div 2 :" + w);
y = 100;
}
the conditions says that if any of these two divs reaches left:-100% then the element must place at the end of queue at left:100%.
And one other thing you can combine these if statements and only use x to do the transition.
For start and stop button to work, you should kill the simulation to stop by using clearInterval() function, and call doSimulate() to start again:
var started = true;
$("#stopbutton").click(function () {
if(started) {
clearInterval(sim);
$(this).html('Start');
started = false;
}else{
doSimulate();
$(this).html('Stop');
started = true;
}
});
Here is jsFiddle With Start/Stop Working.
Look at this JSFiddle, i added one more to get a smooth transition back to start.. The third should contain same message as first.
HTML
<body>
<div class="row">
<div class="col-xs-1"></div>
<div id="wrap" class="col-xs-10">
<div class="movimg message1" id="movimg1">
<h1 class="header">start div 1</h1>
</div>
<div class="movimg message2" id="movimg2">
<h1 class="header">start div 2</h2>
</div>
<div class="movimg message1" id="movimg3">
<h1 class="header">start div 1</h1>
</div>
</div>
<div class="col-xs-1"></div>
</div>
<div class="row">
<button class="button" id="startbutton" style="display:none;">Start</button>
<button class="button" id="stopbutton">Stop</button>
</div>
</body>
JavaScript
$(function () {
var x = 200.0;
var interval;
function start(){
interval = setInterval(function () {
x -= 0.1;
if (x <= 0.0) {
x = 200;
}
$('#movimg1').css('left', (x-200) + "%");
$('#movimg2').css('left', (x-100) + "%");
$('#movimg3').css('left', x + "%");
}, 10);
}
start();
$("#stopbutton").click(function () {
window.clearInterval(interval);
$(this).hide();
$("#startbutton").show();
});
$("#startbutton").click(function () {
start();
$(this).hide();
$("#stopbutton").show();
});
})
CSS
body {
overflow: hidden;
}
#wrap {
width: 80%;
left: 10%;
}
.movimg{
position: absolute;
height: 600px;
width: 100%;
background-image: url('https://s-media-cache-ak0.pinimg.com/736x/89/ed/e5/89ede56bcc8243787e55676ab28f287f.jpg');
}
#movimg1 {
left: 0%;
}
#movimg2 {
left: 100%;
}
#movimg3 {
left: 200%;
}
.header {
text-align: center;
}
.button{
top: 600px;
position: relative;
}
UPDATE
Now with Stop and Start buttons: JSFiddle

Dynamically place Unicode characters in a div with background image

I have an image that represents a weight-lifting bar:
I want to put the Full Block Unicode character (e.g. representing plates) on both the left and the right sides of the bar.
I'm trying to do this with 3 divs:
Barbell left: plates that go on the left side of the bar, right-justified
Barbell middle: nothing left blank
Barbell right: plates that go on the right side of the bar, left-justified
Here is a professional representation of the divs with a plate:
I thought I could do this with floats and percentages on div widths, but I'm not having any luck.
Here is my most recent attempt on js fiddle.
UPDATE
I got the answer I wanted, but based on the comment, I discovered that using Canvas was the better route.
I was able to achieve a better result with this html:
<div data-role="page" id="p1">
<div data-role="header"><h1>Header Page 1</h1></div>
<div data-role="content">
<div class="bar-canvas">
<canvas id="_barCanvas"></canvas>
</div>
</div>
</div>
<div data-role="footer"><h4>Footer</h4></div>
</div>
and this js:
var WIDTH_FACTOR = .8; //80% of screen size
var HEIGHT_FACTOR = .1; //10% of height size
var WEIGHT_SPACER = 2;
var ctx = $("#_barCanvas")[0].getContext("2d");
ctx.canvas.width = (window.innerWidth * WIDTH_FACTOR);
ctx.canvas.height = (window.innerHeight * HEIGHT_FACTOR);
var bar_width = ctx.canvas.width * .8;
var bar_height = ctx.canvas.height * .1;
var bar_x = (ctx.canvas.width - bar_width)
var bar_y = (ctx.canvas.height * .5)
var plate_stop_width = bar_width * .01;
var plate_stop_height = bar_height * 4;
var plate_stop_y = bar_y - ((plate_stop_height - (bar_y / 2)));
var rubber_plate_height = bar_height * 8;
var rubber_plate_y = (ctx.canvas.height / 2) - (rubber_plate_height/2) + (bar_height/2);
var small_plate_height = plate_stop_height;
var small_plate_y = plate_stop_y;
var left_plate_stop_x = bar_x + (bar_width * .3);
var right_plate_stop_x = bar_x + (bar_width * .7);
//Draw Bar
ctx.fillStyle = "black";
ctx.fillRect (bar_x, bar_y, bar_width, bar_height);
//Draw Plate stop left
ctx.fillStyle = "black";
ctx.fillRect (left_plate_stop_x, plate_stop_y, plate_stop_width, plate_stop_height);
//Draw Plate stop right
ctx.fillStyle = "black";
ctx.fillRect (right_plate_stop_x, plate_stop_y, plate_stop_width, plate_stop_height);
//Draw 45 lb Plates
var plate_width = bar_width * .04;
var current_plate_height = 0;
ctx.fillStyle = 'red';
ctx.fillRect(left_plate_stop_x - plate_width, rubber_plate_y, plate_width, rubber_plate_height);
ctx.fillStyle = 'red';
ctx.fillRect(right_plate_stop_x + plate_stop_width, rubber_plate_y, plate_width, rubber_plate_height);
I did it changing a bit your markup and css.
Demo (tested on Chrome 22 only)
HTML:
<div data-role="page" id="p1">
<div data-role="header"><h1>Header Page 1</h1></div>
<div data-role="content">
<div class="barbell-background">
<div class="barbell-left">█</div>
<div class="barbell-right">█</div>
</div>
</div>
<div data-role="footer"><h4>Footer</h4></div>
</div>
CSS:
.barbell-background
{
font-size:3em;
line-height:1.4em;
height:1.4em;
position:relative;
background-image:url('http://i.stack.imgur.com/ZmFY4.png');
background-repeat: no-repeat;
background-position: center;
}
.barbell-left, .barbell-right
{
position:absolute;
color:red;
}
.barbell-left
{
right:50%;
margin-right:146px;
}
.barbell-right
{
left:50%;
margin-left:145px;
}​
As Joachim Sauer said, it's probably easier and more consistent to just use divs for the red squares...
Another demo
HTML:
<div data-role="page" id="p1">
<div data-role="header"><h1>Header Page 1</h1></div>
<div data-role="content">
<div class="barbell-background">
<div class="barbell-left"></div>
<div class="barbell-right"></div>
</div>
</div>
<div data-role="footer"><h4>Footer</h4></div>
</div>
CSS:
.barbell-background
{
font-size:3em;
line-height:1.3em;
height:1.3em;
position:relative;
background-image:url('http://i.stack.imgur.com/ZmFY4.png');
background-repeat: no-repeat;
background-position: center;
}
.barbell-left, .barbell-right
{
position:absolute;
background:red;
width:0.5em;
height:100%;
}
.barbell-left
{
right:50%;
margin-right:146px;
}
.barbell-right
{
left:50%;
margin-left:144px;
}​
In both demos you'll see that a pixel "wobbles". Knowing the contents of the red square i could try to fix it.

Categories