I am trying to add circles when the event mousedown is generated into the square-one (grey square) only. If the mouse hovers outside of the square-one, it should not insert any circles anywhere else such as square-two(green square).
Question: How can I set the limits for the circles such that they are only inserted within the square-one boundaries? Thank you for your help.
***********
JavaScript
***********
let count = 1
let greySquare = document.getElementById("square-one")
let mousePosition;
let circlesArray = []
document.addEventListener('mousedown', (event)=>{
let circle = document.createElement('div')
let circleHeight = 40
let circleWidth = 40
mousePosition = {
x: event.clientX,
y: event.clientY
}
circle.style.height = `${circleHeight}px`
circle.style.width = `${circleWidth}px`;
circle.style.borderRadius = "50%"
circle.style.backgroundColor = `#F0B27A`
circle.style.position = "absolute"
circle.style.left = (mousePosition.x - (circleWidth/2)) + "px"
circle.style.top = (mousePosition.y - (circleHeight/2)) + "px"
circle.style.lineHeight = `${circleHeight}px`
circle.style.display = 'flex';
circle.style.cursor = 'pointer'
circle.style.justifyContent = 'center';
circle.style.border = 'none'
circle.textContent = count++
greySquare.appendChild(circle)
circlesArray.push(circle)
})
********
HTML
********
<body>
<div class="container">
<div id="square-one"></div>
<div id="square-two"></div>
</div>
<script src="script.js"></script>
</body>
******
CSS
******
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
position: relative;
}
.container{
position: relative;
width: 100%;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
#square-one{
position: relative;
width: 300px;
height: 300px;
background-color: grey;
margin-right: 100px;
}
#square-two{
position: relative;
width: 300px;
height: 300px;
background-color: green;
}
When I use your code, the circles aren't being put where I actually click.
That is because you're using the mouse's position (which is relative to the page) to detect where you will put the circles, but then you append them to the
graySquare, which doesn't start at (0,0). If you append them to the .contaner instead, you'll be ok.
document.querySelector(".container").appendChild(circle)
Then regarding the set the limits for the circles such that they are only inserted within the square-one boundaries, you need to get the position (x and y), width and height of the squareOne and only proceed if the click occurs within those.
document.addEventListener('mousedown', (event)=>{
mousePosition = {
x: event.clientX,
y: event.clientY
}
let greySquarePosition = greySquare.getBoundingClientRect();
if(!(mousePosition.x>=greySquarePosition.left + window.scrollX&&
mousePosition.x<=greySquarePosition.left + window.scrollX + greySquarePosition.width&&
mousePosition.y>=greySquarePosition.top + window.scrollY&&
mousePosition.y<=greySquarePosition.top + window.scrollY + greySquarePosition.height))
return;
// ...
I used this to get the position of the div, and this to get its width and height (although they ended up being the same solution).
EDIT!
I kept thinking about this and there's a more obvious, more elegant solution (to me at least). You add the event listener to the graySquare and not the whole document.
greySquare.addEventListener('mousedown', (event)=> ...
Then you don't need the ugly part where you check if the mouse is within the limits.
You can even bind the same function to different squares. Check the updated snippet.
let count = 1
let greySquare = document.getElementById("square-one")
let greenSquare = document.getElementById("square-two")
let mousePosition;
let circlesArray = []
greySquare.addEventListener('mousedown', paintCircles.bind(null, '#F0B27A'), false);
greenSquare.addEventListener('mousedown', paintCircles.bind(null, '#fa0123'), false);
function paintCircles(color, event){
mousePosition = {
x: event.clientX,
y: event.clientY
}
let circle = document.createElement('div')
let circleHeight = 40
let circleWidth = 40
circle.style.height = `${circleHeight}px`
circle.style.width = `${circleWidth}px`;
circle.style.borderRadius = "50%"
circle.style.backgroundColor = `${color}`
circle.style.position = "absolute"
circle.style.left = (mousePosition.x - (circleWidth/2)) + "px"
circle.style.top = (mousePosition.y - (circleHeight/2)) + "px"
circle.style.lineHeight = `${circleHeight}px`
circle.style.display = 'flex';
circle.style.cursor = 'pointer'
circle.style.justifyContent = 'center';
circle.style.border = 'none'
circle.textContent = count++;
document.querySelector(".container").appendChild(circle)
circlesArray.push(circle)
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
position: relative;
}
.container{
position: relative;
width: 100%;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
#square-one{
position: relative;
width: 300px;
height: 300px;
background-color: grey;
margin-right: 100px;
}
#square-two{
position: relative;
width: 300px;
height: 300px;
background-color: green;
}
<body>
<div class="container">
<div id="square-one"></div>
<div id="square-two"></div>
</div>
</body>
Related
I made a basic javascript code so you can poke divs with you mouse.
Unfortunately I have to add them manualy but i wanna add so much of them with a pattern.
First i decided to use grid but i guessed it wont work because divs (which i call them squares from now on :D) can change their position.
So I was about to ask, how can I create a javascript code that i can spawn them until they fill the screen.
Also i have another question which is realted to this project, How can i make these squares just decors. I mean by decors i dont want them to effect the webside at all, when the blocks goes out of the screen the body starts to expend, is there any way to avoid that?
(Also it will be better if you make the snippet full screen!)
EDIT: I put the refresh-button on the top left on the main div so you can draw squares by clicking it!
let mouse = {
speedX: 0,
speedY: 0,
posX: 0,
posY: 0,
movement: 0,
speed: 0
}
//on mousemove update the moouse object
document.onmousemove = function(e) {
mouse.speedX = e.movementX;
mouse.speedY = e.movementY
mouse.posX = e.pageX;
mouse.posY = e.pageY;
}
//refresh the mouse movement and speed every 100ms
setInterval(() => {
mouse.movement =
Math.sqrt(Math.pow(mouse.speedX, 2) + Math.pow(mouse.speedY, 2));
mouse.speed = mouse.movement * 10;
}, 100);
//add a square div in parent element
function addSquare(parent) {
const newDiv = document.createElement("div");
newDiv.classList.add("square")
parent.appendChild(newDiv)
return newDiv;
}
//add squares in the parent element filling the available size
//gap is the space between squares, size is the edge of the square
//if skipbefore is false it will begin to draw the next square also if it won't fit entirely
function addSquares(parent, gap, size, skipbefore = true) {
const squares = [];
let rect = parent.getBoundingClientRect();
const availableWidth = rect.width;
const availableHeight = rect.height;
let top = 100;
while (top < availableHeight) {
let left = 0;
if (skipbefore && top + size > availableHeight)
break;
while (left < availableWidth) {
if (skipbefore && left + size > availableWidth)
break;
const square = addSquare(parent);
square.style.left = `${left}px`;
square.style.top = `${top}px`;
squares.push(square);
left += gap + size;
}
top += gap + size;
}
return squares;
}
//onmoveover event handler
const squareOnMouseOver = (event) => {
const element = event.target;
const y = mouse.speedY;
const x = mouse.speedX;
const rad = Math.atan2(y, x);
yAxis = mouse.movement * Math.sin(rad);
xAxis = mouse.movement * Math.cos(rad);
const rect = element.getBoundingClientRect();
const left = Math.round(rect.x + xAxis * 3);
const top = Math.round(rect.y + yAxis * 3);
element.style.left = `${left}px`;
element.style.top = `${top}px`;
const o = rad * (180 / Math.PI);
element.style.transform = `rotate(${o}deg)`;
}
//resets the .target parent and redraw the squares inside it
function drawSquares() {
const parent = document.querySelector('.target');
parent.innerHTML = '';
const squares = addSquares(parent, 25, 75);
const colors = [
'lightcoral',
'bisque',
'aquamarine',
'cadetblue',
'greenyellow',
'yellowgreen'
];
squares.forEach(square => {
const iColor = Math.floor(Math.random() * (colors.length - 1));
const color = colors[iColor];
square.style.background = color;
square.addEventListener('mouseover', squareOnMouseOver);
});
}
body{
margin: 0;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: rgb(242, 239, 231);
color: rgb(10, 10, 9);
}
.square{
background-color: lightcoral;
width: 75px;
height: 75px;
position: absolute;
transform: rotate(0deg);
transition: all ease-out 0.5s;
}
.background {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.container .row .col > * {
display: inline-block;
}
.target {
display: block;
width: 100%;
height: 100%;
}
#draw {
font-size: 20px;
padding: .2em 1em;
cursor: pointer;
}
.name{
font-size: 40px;
}
#main-container{
position: absolute;
padding: 35px 45px;
width: 950px;
height: 285px;
box-shadow: 0px 2px 5px 2px rgb(191, 188, 182);
}
.links{
display: flex;
justify-content: center;
align-items: center;
}
.icons{
width: 55px;
height: auto;
margin: 0px 25px;
padding: 10px;
border-radius: 5px;
transition: all ease-in 0.2s;
}
.icons:hover{
background-color: rgb(144, 144, 144);
}
.refresh{
position: absolute;
}
.refresh-button{
width: 25px;
height: auto;
}
.btn:hover{
background-color: rgb(144, 144, 144);
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="css.css">
<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>Document</title>
</head>
<body>
<div class="background">
<div class="target"></div>
<div class="container text-center" id="main-container">
<div class="">
<div class="refresh">
<button class="btn" id="draw" onclick="drawSquares()"><img class="refresh-button" src="SVG/arrow-clockwise.svg"></button>
</div>
<div class="name">Berk Efe Keskin</div>
<br>
<i>This website is working in progress right now...</i>
<br>
<i>Here is some useful links.</i>
<br>
<br>
<div class="links">
<img class="icons" src="SVG/github.svg">
<img class="icons" src="SVG/linkedin.svg">
<img class="icons" src="SVG/stack-overflow.svg">
</div>
</div>
</div>
</div>
<script type="text/javascript" src = "javascript.js"></script>
</body>
</html>
You may have a function that given a container will be filled with how many squares can fit inside as long as there is still avaiable width and available height in the target.
Here in this demo I better factored your code and added a main function called drawSquares that gets called when the button reDRAW is clicked. Each time the squares are redrawn, the target content is emptied.
I'm using a button to trigger the box drawing because the available space depends on the size of the area when the action is fired. For example you can expand the snippet and decide to redraw the squares to have the whole new area filled again.
You may decide to call the action on document ready or when the window gets resized.
let mouse = {
speedX: 0,
speedY: 0,
posX: 0,
posY: 0,
movement: 0,
speed: 0
}
//on mousemove update the moouse object
document.onmousemove = function(e) {
mouse.speedX = e.movementX;
mouse.speedY = e.movementY
mouse.posX = e.pageX;
mouse.posY = e.pageY;
}
//refresh the mouse movement and speed every 100ms
setInterval(() => {
mouse.movement =
Math.sqrt(Math.pow(mouse.speedX, 2) + Math.pow(mouse.speedY, 2));
mouse.speed = mouse.movement * 10;
}, 100);
//add a square div in parent element
function addSquare(parent) {
const newDiv = document.createElement("div");
newDiv.classList.add("square")
parent.appendChild(newDiv)
return newDiv;
}
//add squares in the parent element filling the available size
//gap is the space between squares, size is the edge of the square
//if skipbefore is false it will begin to draw the next square also if it won't fit entirely
function addSquares(parent, gap, size, skipbefore = true) {
const squares = [];
let rect = parent.getBoundingClientRect();
const availableWidth = rect.width;
const availableHeight = rect.height;
let top = 100;
while (top < availableHeight) {
let left = 0;
if (skipbefore && top + size > availableHeight)
break;
while (left < availableWidth) {
if (skipbefore && left + size > availableWidth)
break;
const square = addSquare(parent);
square.style.left = `${left}px`;
square.style.top = `${top}px`;
squares.push(square);
left += gap + size;
}
top += gap + size;
}
return squares;
}
//onmoveover event handler
const squareOnMouseOver = (event) => {
const element = event.target;
const y = mouse.speedY;
const x = mouse.speedX;
const rad = Math.atan2(y, x);
yAxis = mouse.movement * Math.sin(rad);
xAxis = mouse.movement * Math.cos(rad);
const rect = element.getBoundingClientRect();
const left = Math.round(rect.x + xAxis * 3);
const top = Math.round(rect.y + yAxis * 3);
element.style.left = `${left}px`;
element.style.top = `${top}px`;
const o = rad * (180 / Math.PI);
element.style.transform = `rotate(${o}deg)`;
}
//resets the .target parent and redraw the squares inside it
function drawSquares() {
const parent = document.querySelector('.target');
parent.innerHTML = '';
const squares = addSquares(parent, 25, 75);
const colors = [
'lightcoral',
'bisque',
'aquamarine',
'cadetblue',
'greenyellow',
'yellowgreen'
];
squares.forEach(square => {
const iColor = Math.floor(Math.random() * (colors.length - 1));
const color = colors[iColor];
square.style.background = color;
square.addEventListener('mouseover', squareOnMouseOver);
});
}
body {
margin: 0;
width: 100vw;
height: 100vh;
display: flex;
}
.square {
background-color: lightcoral;
width: 75px;
height: 75px;
position: absolute;
transform: rotate(0deg);
transition: all ease-out 0.5s;
}
#Header {
font-size: italic;
}
.background {
width: 100%;
height: 100%;
}
.target {
position: relative;
display: block;
width: 100%;
height: 100%;
z-index: -1;
}
#draw {
font-size: 20px;
padding: .2em 1em;
cursor: pointer;
}
.container .row .col > * {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link el="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<body>
<div class="background">
<span>Work in progress...</span>
<div class="container text-center">
<div class="row">
<div class="col">
<h1 id="Header">Work in progress...</h1>
<button id="draw" onclick="drawSquares()">reDRAW</button>
</div>
</div>
</div>
<div class="target"></div>
</div>
</body>
I have some Javascript drawing random square elements in the DOM. I have a gif (Image) I want these elements to appear over but they keep appearing underneath the gif. I tried defining z-depth and layout parameters to move these elements on top of the image here, but this produced no difference.
Any assistance in achieving the result (drawing elements onclick, on top of this gif) would be much appreciated.
I ultimately want to draw various other images over this image onclick, restricted to this particular area on top of the gif. If someone can suggest a solution to this as well I would be very much grateful!
(Code features some unused elements from my past attempts)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="div.css" />
</head>
<body>
<div style="cursor: pointer;" id="boxy" >
<img src="bg.gif" alt="unfinished bingo card" onclick="create()" />
</div>
</div>
<script>
var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement("canvas");
canvas.height = 1300;
canvas.width = 1300;
var context = canvas.getContext("2d");
body.appendChild(canvas);
var rects = [];
function create() {
// Opacity
context.globalAlpha = 0.7;
var color = '#' + Math.round(0xffffff * Math.random()).toString(16);
context.fillStyle = color;
//Each rectangle's size is (20 ~ 100, 20 ~ 100)
var coordx = Math.random() * canvas.width;
var coordy = Math.random() * canvas.width;
var width = Math.random() * 80 + 20;
var height = Math.random() * 80 + 20;
var rect = {
x: coordx,
y: coordy,
w: width,
h: height
}
var ok = true;
rects.forEach(function (item) {
if (isCollide(rect, item)) {
console.log("collide");
ok = false;
} else {
console.log("no collision");
}
})
if (ok) {
context.fillRect(coordx, coordy, width, height);
rects.push(rect);
} else {
console.log('rect dropped');
}
console.log(rects);
}
function isCollide(a, b) {
return !(
((a.y + a.h) < (b.y)) ||
(a.y > (b.y + b.h)) ||
((a.x + a.w) < b.x) ||
(a.x > (b.x + b.w))
);
}
document.getElementById('boxy').addEventListener('click', create);
document.getElementById('canvas').style.position = "relative";
document.getElementById('canvas').style.zIndex = "10";
</script>
</body>
</html>
#my-div {
width: 1300x;
height: 1300px;
z-index: -1;
}
a.fill-div {
display: block;
height: 100%;
width: 100%;
text-decoration: none;
}
#boxy {
display: inline-block;
height: 100%;
width: 100%;
text-decoration: none;
z-index: -1;
}
.canvas {
display: inline-block;
height: 100%;
width: 100%;
text-decoration: none;
z-index: 10;
}
You have to use position:absolute; to take it out of the html flow.
Now anything added after the image will be placed like the image was never there.
img {
width: 100vw;
height: 100vh;
position: absolute;
top: 0;
left: 0;
z-index: -10;
}
div {
font-size: 2rem;
color: white;
}
<img src="https://images.unsplash.com/photo-1664273107076-b6d1fbfb973b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1171&q=80">
<div>Hello i am on top of the image
</div>
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>
I am working on a Javascript code for checking if element is in viewport.
But now I have a code that returns only true if the element is 100% in the viewport.
Is there a way for example if there are 10 pixels returns true or if a percentage... of the element is in the viewport return true?
My code for so far
<script type="text/javascript">
var elem = document.getElementById("result");
var bounding = elem.getBoundingClientRect();
if (bounding.top >= 0 && bounding.left >= 0 && bounding.right <= window.innerWidth && bounding.bottom <= window.innerHeight) {
alert('in viewport');
}
</script>
Based on #Jorg's code, here's the same with the Intersection Observer API, which is a newer way of checking for intersections. This will work on all modern browsers ~ 93.5% according to Can I Use
This is set up to make it consider anything that's 50% within the viewport as within the threshold. I made it such a large value so it's easy to see how it works.
As you'll notice with this, the callback is only called at the threshold (after the initial check). So, if you want an accurate intersection percentage, you'll probably want to increase the number of thresholds checked.
let callback = (entries, observer) => {
entries.forEach(entry => {
entry.target.style.backgroundColor = entry.isIntersecting ? 'green' : 'red';
entry.target.innerHTML = entry.intersectionRatio;
})
}
let observer = new IntersectionObserver(callback, {
threshold: [0.5] // If 50% of the element is in the screen, we count it!
// Can change the thresholds based on your needs. The default is 0 - it'll run only when the element first comes into view
});
['div1', 'div2', 'div3', 'div4'].forEach(d => {
const div = document.getElementById(d);
if (div) observer.observe(div);
})
html,
body {
padding: 0;
margin: 0;
}
body {
height: 200vh;
width: 200vw;
}
#div1 {
position: absolute;
left: calc(100vw - 60px - 10px);
top: 10px;
height: 100px;
width: 60px;
background-color: red;
color: white;
}
#div2 {
position: absolute;
left: 20px;
top: 10px;
height: 50px;
width: 60px;
background-color: blue;
color: white;
}
#div3 {
position: absolute;
left: calc(100vw - 260px + 50px);
top: max(calc(100vh - 350px + 120px), 120px);
height: 350px;
width: 260px;
background-color: green;
color: white;
text-align: left;
}
#div4 {
position: absolute;
height: 9000px;
width: 9000px;
color: black;
background-color: yellow;
}
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<!-- enable this div to see an example of a div LARGER than your viewport. -->
<!-- <div id="div4"></div> -->
I guess what you're looking for is the intersection between the element and the viewport? Meaning, find out how much of the div overlaps with the viewport.
Using the function below should tell you, between 0 and 1, how much of the DIV fits inside the viewport. Be aware though, that the div could also just be larger than the viewport this way, in which case the overlapping area is also less than 1.
Here is a working example
const intersection = (r1, r2) => {
const xOverlap = Math.max(0, Math.min(r1.x + r1.w, r2.x + r2.w) - Math.max(r1.x, r2.x));
const yOverlap = Math.max(0, Math.min(r1.y + r1.h, r2.y + r2.h) - Math.max(r1.y, r2.y));
const overlapArea = xOverlap * yOverlap;
return overlapArea;
}
const percentInView = (div) => {
const rect = div.getBoundingClientRect();
const dimension = { x: rect.x, y: rect.y, w: rect.width, h: rect.height };
const viewport = { x: 0, y: 0, w: window.innerWidth, h: window.innerHeight };
const divsize = dimension.w * dimension.h;
const overlap = intersection(dimension, viewport);
return overlap / divsize;
}
I wanted a vertical dragBar for resizing two divs. I have created an example for the same but I am facing an issue.
Actual : As and when I resize the the upper div and move the slider down, the area of parent div increases and hence a scroll bar is given.
Expected: When Resizing, if the slider is moved down, it should only show the data contained in the upper div and when slider is moved up, it should show the content of lower div and should not increase the over all length of the parent div.
var handler = document.querySelector('.handler');
var wrapper = handler.closest('.wrapper');
var boxA = wrapper.querySelector('.box1');
var boxB = wrapper.querySelector('.box2');
var isHandlerDragging = false;
document.addEventListener('mousedown', function(e) {
// If mousedown event is fired from .handler, toggle flag to true
if (e.target === handler) {
isHandlerDragging = true;
}
});
document.addEventListener('mousemove', function(e) {
// Don't do anything if dragging flag is false
if (!isHandlerDragging) {
return false;
}
// Get offset
var containerOffsetTop= wrapper.offsetTop;
var containerOffsetBottom= wrapper.offsetBottom;
// Get x-coordinate of pointer relative to container
var pointerRelativeXpos = e.clientY - containerOffsetTop;
var pointerRelativeXpos2 = e.clientY - e.offsetTop + e.offsetHeight;
var boxAminWidth = 30;
boxA.style.height = (Math.max(boxAminWidth, pointerRelativeXpos - 2)) + 'px';
boxA.style.flexGrow = 0;
boxB.style.height = (Math.max(boxAminWidth, pointerRelativeXpos2 - 8)) + 'px';
boxB.style.flexGrow = 0;
});
document.addEventListener('mouseup', function(e) {
// Turn off dragging flag when user mouse is up
isHandlerDragging = false;
});
body {
margin: 40px;
}
.wrapper {
background-color: #fff;
color: #444;
/* Use flexbox */
}
.box1, .box2 {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
margin-top:2%;
/* Use box-sizing so that element's outerwidth will match width property */
box-sizing: border-box;
/* Allow box to grow and shrink, and ensure they are all equally sized */
}
.handler {
width: 20px;
height:7px;
padding: 0;
cursor: ns-resize;
}
.handler::before {
content: '';
display: block;
width: 100px;
height: 100%;
background: red;
margin: 0 auto;
}
<div class="wrapper">
<div class="box1">A</div>
<div class="handler"></div>
<div class="box2">B</div>
</div>
Hope I was clear in explaining the issue I am facing in my project. Any help is appreciated.
It looks like your on the right track. You just need to make the wrapper a flexbox with the flex direction column and assign it a height. Also box 2 needs to have a flex of 1 so it can grow and shrink as needed. Finally I needed to remove the code that set the flex grow to 0 in the JavaScript. Here is the result.
var handler = document.querySelector('.handler');
var wrapper = handler.closest('.wrapper');
var boxA = wrapper.querySelector('.box1');
var boxB = wrapper.querySelector('.box2');
var isHandlerDragging = false;
document.addEventListener('mousedown', function(e) {
// If mousedown event is fired from .handler, toggle flag to true
if (e.target === handler) {
isHandlerDragging = true;
}
});
document.addEventListener('mousemove', function(e) {
// Don't do anything if dragging flag is false
if (!isHandlerDragging) {
return false;
}
e.preventDefault();
// Get offset
var containerOffsetTop= wrapper.offsetTop;
var containerOffsetBottom= wrapper.offsetBottom;
// Get x-coordinate of pointer relative to container
var pointerRelativeXpos = e.clientY - containerOffsetTop;
var pointerRelativeXpos2 = e.clientY - e.offsetTop + e.offsetHeight;
var boxAminWidth = 30;
boxA.style.height = (Math.max(boxAminWidth, pointerRelativeXpos - 2)) + 'px';
boxB.style.height = (Math.max(boxAminWidth, pointerRelativeXpos2 - 8)) + 'px';
});
document.addEventListener('mouseup', function(e) {
// Turn off dragging flag when user mouse is up
isHandlerDragging = false;
});
body {
margin: 40px;
}
.wrapper {
background-color: #fff;
color: #444;
/* Use flexbox */
display: flex;
flex-direction: column;
height: 200px;
}
.box1, .box2 {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
margin-top:2%;
/* Use box-sizing so that element's outerwidth will match width property */
box-sizing: border-box;
/* Allow box to grow and shrink, and ensure they are all equally sized */
}
.box2 {
flex: 1;
}
.handler {
width: 20px;
height:7px;
padding: 0;
cursor: ns-resize;
}
.handler::before {
content: '';
display: block;
width: 100px;
height: 100%;
background: red;
margin: 0 auto;
}
<div class="wrapper">
<div class="box1">A</div>
<div class="handler"></div>
<div class="box2">B</div>
</div>