I'm trying to create a tile-like content carousel for a website I'm creating. Basically I need the ordinary content carousel functionality that comes in a lot of different jQuery plug-ins etc. - but instead of the slider being linear, I need the items to shift tiles in a circular manner like this:
Step 1:
Step 2:
Step 3:
I tried creating the setup using Flexbox and some simple jQuery:
$(document).ready(function () {
$(".item").each(function (index) {
$(this).css("order", index);
});
$(".prev").on("click", function () {
// Move all items one order back
$(".item").each(function (index) {
var currentOrder = parseInt($(this).css("order"));
if (currentOrder == undefined) {
currentOrder = index;
}
var newOrder = currentOrder - 1;
if (newOrder < 0) {
newOrder = 5;
}
$(this).css("order", newOrder);
});
});
$(".next").on("click", function () {
// Move all items one order forward
$(".item").each(function (index) {
var currentOrder = parseInt($(this).css("order"));
var newOrder = currentOrder + 1;
if (newOrder > 5) {
newOrder = 0;
}
$(this).css("order", newOrder);
});
});
});
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 500px;
}
.item {
width: 125px;
height: 75px;
color: white;
text-align: center;
font-size: 24px;
border: 1px solid white;
padding-top: 50px;
box-sizing: content-box;
background-color: rgb(42, 128, 185);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="prev">Prev</button>
<button class="next">Next</button>
<div class="container">
<div class="item one">1</div>
<div class="item two">2</div>
<div class="item three">3</div>
<div class="item four">4</div>
<div class="item five">5</div>
<div class="item six">6</div>
</div>
but this leaves me with some unresolved issues:
How do I animate the tiles when changing the order (when clicking next/prev)?
How do I fix the order so that the items move in a continuous line instead of wrapping to the start of next line (I'd like the order to be like displayed in step 2 -> 3)?
Any existing plug-in (I've looked but can't find any) or codepen etc. would be very much appreciated as I'm not sure if my approach is maintainable (or even doable).
Thanks a bunch :)
I've used absolute position formula from index to (top, left). Then i've used jQuery to animate that. That's lame but can be improved if that's an issue. It looks nice.
const containerBox = document.querySelector('#container')
let divs = [...containerBox.querySelectorAll('div')]
var size = 100
var margin = 2
function get_top_left(pos) {
if (pos < divs.length / 2) {
return {
left: pos * size + margin * (pos),
top: 0
}
} else {
return {
left: (divs.length - pos - 1) * size + margin * (divs.length - pos - 1),
top: size + margin
}
}
}
var offset = 0
function draw() {
divs.forEach(function(div, index) {
var len = divs.length
index = ((index + offset) % len + len) % len
var pos = get_top_left(index);
//div.style.left = pos.left + "px"
//div.style.top = pos.top + "px"
$(div).animate({
"left": pos.left + "px",
"top": pos.top + "px"
})
})
}
next.onclick = _ => {
offset += 1
draw()
}
prev.onclick = _ => {
offset -= 1
draw()
}
draw();
#container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 500px;
height: 260px;
margin: 10px;
position: relative;
}
#container>div {
width: 100px;
height: 66px;
color: white;
text-align: center;
font-size: 24px;
border: 1px solid white;
padding-top: 34px;
box-sizing: content-box;
background: #2a80b9;
position: absolute;
top: 0;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="prev">Prev</button>
<button id="next">Next</button>
<div id="container">
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
<div> 4 </div>
<div> 5 </div>
<div> 6 </div>
</div>
This kind of carousel ?
const
containerBox = document.querySelector('#container')
, nextOrder = [3,0,1,4,5,2]
, prevOrder = [1,2,5,0,3,4]
;
next.onclick =_=>
{
let divs = [...containerBox.querySelectorAll('div')]
nextOrder.forEach(n=> containerBox.appendChild( divs[n]) )
}
prev.onclick =_=>
{
let divs = [...containerBox.querySelectorAll('div')]
prevOrder.forEach(n=> containerBox.appendChild( divs[n]) )
}
#container {
display : flex;
flex-direction : row;
flex-wrap : wrap;
width : 500px;
margin : 20px;
}
#container > div {
width : 125px;
height : 75px;
color : white;
text-align : center;
font-size : 24px;
border : 1px solid white;
padding-top : 50px;
box-sizing : content-box;
background : #2a80b9;
}
<button id="prev">Prev</button>
<button id="next">Next</button>
<div id="container">
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
<div> 6 </div>
<div> 5 </div>
<div> 4 </div>
</div>
I'm trying to make a game of little rabbit's farm. My level of programming is a beginner.
Why is addRabbit() code starts to work after the page is loaded? I wrote it to work after click to "Buy Rabbit" button
Why rabbits are not shown at the page near the "Sell Rabbit" and "Buy Rabbit" buttons?
I know that I have a lot of issues here as far as I'm a beginner. Could I ask you to mention any of them?
// VARIABLES
// variables for modal of chosing rabbits
const chooseModal = document.querySelector(".choose-modal");
const selectRabbitBtn = document.querySelector(".choose-rabbit-btn");
const rabbitSelects = document.querySelectorAll("input[type=radio]");
let chosenRabbitUrl = "img/rabbit1.png";
// start screen
const startScreenDiv = document.querySelector(".story-modal");
const rabbit = document.querySelector("img.rabbit");
const buyRabbitBtn = document.querySelector(".buy-btn");
// EVENT LISTENERS
selectRabbitBtn.addEventListener("click", chooseTheRabbit);
// FUNCTIONS
function chooseTheRabbit(e){
e.preventDefault();
for (let rabbit of rabbitSelects) {
if (rabbit.checked) {
chosenRabbitUrl = `img/${rabbit.id}.png`;
break;
}
}
chooseModal.style.display = "none";
startScreen();
}
function startScreen() {
startScreenDiv.style.display = "block";
rabbit.src = chosenRabbitUrl;
}
class RabbitGame {
constructor() {
this.rabbitsCount = parseInt(document.querySelector(".rabbits-count").innerText, 10);
this.rabbitsCountSpan = document.querySelector(".rabbits-count");
this.rabbitsShowDiv = document.querySelector(".rabbits-count-show");
this.coinsCount = parseInt(document.querySelector(".coins-count").innerText, 10);
this.coinsCountSpan = document.querySelector(".coins-count");
this.sellRabbitBtn = document.querySelector(".sell-btn");
this.myRabbits = [{age: 0, src: chosenRabbitUrl, width: 50}];
};
// function, that shows rabbits on the page, that the owner have
// adult rabbits should be bigger, little rabbits smaller
showRabbits() {
// rabbit.src = chosenRabbitUrl
this.myRabbits.forEach((rabbit) => {
this.rabbitsShowDiv.innerHTML += `<img src="${rabbit.src}" width="${rabbit.width}">`});
};
// function that adds a rabbit, if the owner doesn't have any coin, rabbits eat him
addRabbit() {
console.log("Hello");
if (this.coinsCount > 1) {
// remove 1 coin
this.coinsCount -= 1
console.log(this.coinsCount);
// show 1 coin less
this.coinsCountSpan.innerText = this.coinsCount
// add 1 for rabbits age
// if the rabbit is older than 4, make him bigger on screen
this.myRabbits.forEach((rabbit) => {
rabbit.age +=1;
if (rabbit.age > 3) {
rabbit.width = 70
}
})
// add 1 more rabbit to array
this.myRabbits.push({age: 0, src: chosenRabbitUrl, width: 50});
// show 1 more rabbit
this.rabbitsShowDiv.innerHTML += `<img src="${rabbit.src}" width="${rabbit.width}">`
}
};
// функция, которая продает кролика, если он взрослый
// если нет взрослых кроликов, выводит предупреждение, что нет взрослых кроликов
}
const rabbitGame = new RabbitGame();
rabbitGame.showRabbits;
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit());
/* GENERAL */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
h3 {
background-color: rgb(108, 165, 55);
width: 400px;
height: 30px;
padding: 5px;
color: white;
text-align: center;
}
button {
padding: 5px 20px;
background-color: rgb(194, 89, 89);
color: white;
text-transform: uppercase;
border: none;
font-weight: bold;
}
button:hover {
background-color: rgb(172, 79, 84);
}
/* END OF GENERAL */
/* CHOOSE RABBIT MODAL & RULES MODAL */
.choose-modal,
.rules-modal {
display: flex;
justify-content: center;
margin-top: 20px;
}
.choose-modal > div {
display: flex;
flex-direction: column;
}
input[type="radio"] {
opacity: 0;
}
label > img:hover {
border-bottom: 1px solid rgb(199, 199, 199);
}
ul {
list-style: none;
margin: 10px;
}
li {
margin-bottom: 5px;
}
.button-div {
display: flex;
justify-content: center;
}
/* END OF CHOOSE RABBIT MODAL & RULES MODAL */
/* START SCREEN */
/* .story-modal {
display: none;
} */
.story-modal {
background-image: url("img/neighbour.jpg");
background-size: cover;
height: 100vh;
position: relative;
}
img.rabbit {
position: absolute;
height: 40%;
top: 60%;
left: 50%;
overflow: hidden;
}
.story-modal > h3 {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
top: 5%;
}
.img-overlay {
width: 100%;
height: 100%;
background: rgba(61, 61, 61, 0.3);
}
.story-modal > button {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
top: 13%;
}
/* END OF START SCREEN */
/* MAIN GAME */
.main-game {
display: flex;
}
/* END OF MAIN GAME */
<div class="choose-modal">
<div>
<div class="choose-modal-header">
<h3>Please, choose the rabbit</h3>
</div>
<div>
<label for="rabbit1"><input type="radio" id="rabbit1" name="rabbits" value="rabbit1"><img src="img/rabbit1.png" width="100" alt="rabbit1"></label>
<label for="rabbit2"><input type="radio" id="rabbit2" name="rabbits" value="rabbit2"><img src="img/rabbit2.png" width="100" alt="rabbit2"></label>
<label for="rabbit3"><input type="radio" id="rabbit3" name="rabbits" value="rabbit3"><img src="img/rabbit3.png" width="80" alt="rabbit3"></label>
</div>
<div class="button-div">
<button type="submit" value="Choose" class="choose-rabbit-btn">Choose</button>
</div>
</div>
</div>
<div class="story-modal">
<div class="img-overlay"></div>
<h3>Your pretty neighbour gave you a rabbit</h3>
<img alt="rabbit" src="#" class="rabbit">
<button>Rules</button>
</div>
<div class="rules-modal">
<div>
<h3>Rules of game</h3>
<div>
<ul>
<li>Buy grass to feed the rabbits</li>
<li>Sell adult rabbits</li>
<li>Buy new little rabbits</li>
</ul>
</div>
<div class="button-div">
<button>Play</button>
</div>
</div>
</div>
<div class="main-game">
<div class=" navbar">
<p><img src="img/coin.png" height="20"> Coins <span class="coins-count">10</span></p>
<p class="name-of-gamer">Anonymous</p>
<p><img src="img/rabbit.png" height="20"> Rabbits <span class="rabbits-count">3</span></p>
</div>
<div class="rabbits-count-show"></div>
<div>
<button class="sell-btn">Sell Rabbit</button>
<button class="buy-btn">Buy Rabbit</button>
</div>
</div>
Changing the line
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit());
to
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit);
(simply removing those parenthesis) should work. When you add the parenthesis, a function gets called, and that's not what you want. When the button is clicked the eventlistener call the your function itself. as of your second problem you have to add parenthesis to the function to get called thus executing the code inside it.
NOTE: Do not post unnecessary files to a question. Try find the location that error could possibly occur. BTW, CSS has no contributing factor to a error in js code. sometimes html does. I know as a beginner it's hard to find the areas causing the error but it gets easier over time.
strong text
I have a box in a few boxes and placed inside each box for an hour.
I want to sort by using the box clock named item.
This sorting has three modes, the first ascending, the second descending, the third without sorting.
strong text
<body>
<style>
body{margin: 0 auto;padding: 0 auto;background: skyblue;}
.full-item{width: 800px;height: 600px;margin: 50px auto;background: grey;}
.full-item .button-item{width: 100%;height: 80px;background: #B33771;}
.full-item .button-item button{margin: 30px 45%;}
.full-item .item-sort{width: 100%;height: 500px;background: white;margin-top: 10px;}
.full-item .item-sort:first-child{margin-top: 10px;}
.full-item .item-sort .item{width: 90%;height: 140px;background: red;margin: 10px auto;}
.item-sort .item .pic{width: 30%;height: 100%;background: #3B3B98;float: left;}
.item-sort .item .time{width: 70%;height: 100%;background: #1B9CFC;float: right;}
.item-sort .item .time span{color: white;text-align: center;display: block;line-height: 100px;}
</style>
<div class="full-item">
<div class="button-item">
<button id="Sort-item">Sort by</button>
</div>
<div class="item-sort">
<div class="item">
<div class="pic"></div>
<div class="time"><span>15:20</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>13:10</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>18:40</span></div>
</div>
</div>
</div>
</body>
If the data is coming from JSON or other source, as with akbansa's recommendation, you should perform the sorting on the data first; otherwise, see below for an example of how you could reorder your elements:
const button = document.querySelector('#Sort-item')
// add handler
button.addEventListener('click', clickHandler)
// handler definition
function clickHandler(){
let container = document.querySelector('.item-sort')
let items = Array.from(container.querySelectorAll('.item-sort .item'))
// sort based on time
items = items.sort((a,b)=>{
let a_time = a.querySelector('.time span').textContent
let b_time = b.querySelector('.time span').textContent
return a_time > b_time ? 1 : -1
})
// apply the order
for(let item of items)
container.appendChild(item)
}
body {
margin: 0 auto;
padding: 0 auto;
background: skyblue;
}
.full-item {
width: 800px;
height: 600px;
margin: 50px auto;
background: grey;
}
.full-item .button-item {
width: 100%;
height: 80px;
background: #B33771;
}
.full-item .button-item button {
margin: 30px 45%;
}
.full-item .item-sort {
width: 100%;
height: 500px;
background: white;
margin-top: 10px;
}
.full-item .item-sort:first-child {
margin-top: 10px;
}
.full-item .item-sort .item {
width: 90%;
height: 140px;
background: red;
margin: 10px auto;
}
.item-sort .item .pic {
width: 30%;
height: 100%;
background: #3B3B98;
float: left;
}
.item-sort .item .time {
width: 70%;
height: 100%;
background: #1B9CFC;
float: right;
}
.item-sort .item .time span {
color: white;
text-align: center;
display: block;
line-height: 100px;
}
<div class="full-item">
<div class="button-item">
<button id="Sort-item">Sort by</button>
</div>
<div class="item-sort">
<div class="item">
<div class="pic"></div>
<div class="time"><span>15:20</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>13:10</span></div>
</div>
<div class="item">
<div class="pic"></div>
<div class="time"><span>18:40</span></div>
</div>
</div>
</div>
Update your html inside "button-item" class
<div class="button-item">
<p>Sort By </p>
<button id="sort-asc" onclick="app.sortAsc()">Asc</button>
<button id="sort-desc" onclick="app.sortDesc()">Desc</button>
<button id="reset" onclick="app.reset()">Reset</button>
</div>
Add to your scripts
var app = (function (){
var originalArr = []
var timeArr = []
var sortedArr = []
var objArr = []
var timeElements = document.querySelectorAll('.time')
var itemSortElement = document.querySelector('.item-sort')
for ( let timeEl of timeElements) {
// retrieving text from individual span element
let timeText = timeEl.children[0].innerText;
// retrieving parent node of div with class "time"
let timeParent = timeEl.parentNode
let obj = { text: timeText, parent: timeParent }
objArr.push(obj)
timeArr.push(timeText)
}
// copying all elements/ texts from "timeArr" array to "originalArr" array
// to keep track of original order of texts
originalArr = timeArr.slice()
function sortAsc () {
// sorting the retrieved texts in ascending order
sortedArr = timeArr.sort();
while (itemSortElement.hasChildNodes()) {
// removing all child elements of class "item-sort"
itemSortElement.removeChild(itemSortElement.firstChild);
}
for ( let i = 0; i < sortedArr.length; i++) {
let filteredObj = objArr.filter((obj) => sortedArr[i] == obj.text)[0]
let node = filteredObj.parent
itemSortElement.appendChild(node)
}
}
function sortDesc () {
sortedArr = timeArr.sort().reverse();
while (itemSortElement.hasChildNodes()) {
itemSortElement.removeChild(itemSortElement.firstChild);
}
for ( let i = 0; i < sortedArr.length; i++) {
var filteredObj = objArr.filter((obj) => sortedArr[i] == obj.text)[0]
let node = filteredObj.parent
itemSortElement.appendChild(node)
}
}
function reset () {
while (itemSortElement.hasChildNodes()) {
itemSortElement.removeChild(itemSortElement.firstChild);
}
for ( let i = 0; i < originalArr.length; i++) {
var filteredObj = objArr.filter((obj) => originalArr[i] == obj.text)[0]
let node = filteredObj.parent
itemSortElement.appendChild(node)
}
}
return {
sortDesc,
sortAsc,
reset
}
})()
you can check it Demo
I have this calculator that I'd like for the results to auto update after the the user adds input.
I've tried the .keyup thing, but I don't understand it.
I'm kinda new to javascript.
Here's my codepen for the project.
http://codepen.io/Tristangre97/pen/zNvQON?editors=0010
HTML
<div class="card">
<div class="title">Input</div>
<br>
<div id="metalSpan"><input class="whiteinput" id="numMetal" type="number">
<div class="floater">Metal Quantity</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan"><input class="whiteinput" id="numForge" type=
"number">
<div class="floater">Forge Quantity</div></div>
<br>
<input checked id="rb1" name="fuel" type="radio" value="spark"> <label for=
"rb1">Sparkpowder</label> <input id="rb2" name="fuel" type="radio" value=
"wood"> <label for="rb2">Wood</label><br>
<br>
<button class="actionButton" id="submit" type="button">Calculate</button></div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div>
<br>
<div id="result"><span id="spreadMetal"></span> metal <span class=
"plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class=
"plural"></span> forge <span id="allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br></div>
</div>
</div>
JS
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("#submit").click(function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == '') {
$("#metalAlert").html("Please enter a value");
}
else if (forges == 0 || forges == '') {
$("#metalAlert").html('');
$("#forgeAlert").html("Please enter a value");
}
else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
}
else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
}
else {
$(".plural").html("in the");
}
$("#forgeAlert").html('');
if (metals % 2 == 0) {}
else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(((spread / 2) * 20) / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
}
else {
$("#allSpark").html(String(''));
}
$("#timeSpark").html(String((isWood) ? (sparks / 2) : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html((isWood) ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
To run the function whenever something is inputted in the field, try the
$("input").on('input', function() { .. });
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("input").on('input', function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == "") {
$("#metalAlert").html("Please enter a value");
} else if (forges == 0 || forges == "") {
$("#metalAlert").html("");
$("#forgeAlert").html("Please enter a value");
} else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
} else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
} else {
$(".plural").html("in the");
}
$("#forgeAlert").html("");
if (metals % 2 == 0) {
} else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(spread / 2 * 20 / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
} else {
$("#allSpark").html(String(""));
}
$("#timeSpark").html(String(isWood ? sparks / 2 : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html(isWood ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
body {
background-color:#316b6f;
font-family:Helvetica,sans-serif;
font-size:16px;
}
.whiteinput {
outline: none;
border-width: 0px;
margin: 0;
padding: .5em .6em;
border-radius: 2px;
font-size: 1em;
color: #316b6f;
}
.actionButton {
background-color: #316B6F;
color: #fff;
padding: .5em .6em;
border-radius: 3px;
border-width: 0px;
font-size: 1em;
cursor: pointer;
text-decoration: none;
-webkit-transition: all 250ms;
transition: all 250ms;
}
.actionButton:hover {
color: #fff;
}
.actionButton:active {
background: #BBFF77;
color: #316B6F;
-webkit-transition: all 550ms;
transition: all 550ms;
}
.card {
position: relative;
background: #4E8083;
color:#FFFFFF;
border-radius:3px;
padding:1.5em;
margin-bottom: 3px;
}
.title {
background: #76B167;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.title2 {
background: #2F3A54;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.floater {
padding: 3px;
}
.radiobtn {
background: red;
border-radius: 2px;
}
input[type=radio] + label:before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
vertical-align:middle;
margin-right: 8px;
background-color: #aaa;
margin-bottom: 6px;
border-radius: 2px;
-webkit-transition: all 450ms;
transition: all 450ms;
}
input[type=radio], input[type=checkbox] {
display:none;
}
input[type=radio]:checked + label:before {
content: "\2022"; /* Bullet */
color:white;
background-color: #fff;
font-size:1.8em;
text-align:center;
line-height:14px;
margin-right: 8px;
}
input[type=checkbox]:checked + label:before {
content:"\2714";
color:white;
background-color: #fff;
text-align:center;
line-height:15px;
}
*:focus {
outline: none;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="card">
<div class="title">Input</div><br>
<div id="metalSpan">
<input class="whiteinput" id="numMetal" type="number">
<div class="floater">
Metal Quantity
</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan">
<input class="whiteinput" id="numForge" type="number">
<div class="floater">
Forge Quantity
</div>
</div>
<br>
<input type="radio" id="rb1" name="fuel" value="spark" checked>
<label for="rb1">Sparkpowder</label>
<input type="radio" id="rb2" name="fuel" value="wood">
<label for="rb2">Wood</label><br><br>
<button class="actionButton" id="submit"
type="button">Calculate</button>
</div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div><br>
<div id="result">
<span id="spreadMetal"></span> metal <span class="plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class="plural"></span> forge <span id=
"allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br>
</div>
</div>
</div>
Codepen
It is triggering your errors because that is part of your function.
More info regarding the input method.
Look, you have two options:
Put all your algorithm of submit click into a function and call him into two binds: the submit click and input change (on('change')) or just remove your calculate button and rely the calculation into onchange of the inputs: each change of checks or inputs will trigger the calculation of metals. The second approach it's more interesting for me and removes the necessity to the user clicks to calculate (he already clicked into inputs and checks). Obviously you can add a filter to only allow to calculation function run after a certain minimum number of data filled, it's a good idea to avoid poor results resulted by lack of data.
In order to auto update calculation, we have to listen to users input on input elements. The easiest approach with minimum changes to existing code is to add input events and emit click on the button:
$("#numMetal, #numForge").on('input', function(){
$("#submit").click()
})
Better approach is to move calculation logic to separate function and call it on desirable events:
$("#numMetal, #numForge").on('input', function(){
calculate()
})
$("#submit").click(function(){
calculate()
})
This will keep the code structured and easier to follow.
Try this:
$( "#numMetal, #numForge" ).keyup(function(event) {
console.log('a key has been pressed');
// add code to handle inputs here
});
What happens here is that an event listener - the key up event - is bound to the two inputs you have on your page. When that happens the code inside will be run.
As suggested in other comments it would be a good idea to call a separate method with all the input processing code you have in the submit call, this way you will avoid code duplication.
You will also want to bind events to the checkboxs. This can be achieved with this:
$( "input[name=fuel]" ).on('change',function() {
console.log('checkbox change');
// call processing method here
});
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Is there a good technique to make a resizable split pane in HTML?
May it be done using CSS / jQuery / JavaScript or is there a good JavaScript library that have been used?
(An example of a split pane is the favorites bar in Internet Explorer which you may have docked to the left of your main browser window.)
I wanted a vanilla, lightweight (jQuery UI Layout weighs in at 185 KB), no dependency option (all existing libraries require jQuery), so I wrote Split.js.
It weights less than 2 KB and does not require any special markup. It supports older browsers back to Internet Explorer 9 (or Internet Explorer 8 with polyfills). For modern browsers, you can use it with Flexbox and grid layouts.
Simplest HTML + CSS accordion, with just CSS resize.
div {
resize: vertical;
overflow: auto;
border: 1px solid
}
.menu {
display: grid
/* Try height: 100% or height: 100vh */
}
<div class="menu">
<div>
Hello, World!
</div>
<div>
Hello, World!
</div>
<div>
Hello, World!
</div>
</div>
Simplest HTML + CSS vertical resizable panes:
div {
resize: horizontal;
overflow: auto;
border: 1px solid;
display: inline-flex;
height: 90vh
}
<div>
Hello, World!
</div>
<div>
Hello, World!
</div>
The plain HTML, details element!.
<details>
<summary>Morning</summary>
<p>Hello, World!</p>
</details>
<details>
<summary>Evening</summary>
<p>How sweat?</p>
</details>
Simplest HTML + CSS topbar foldable menu
div{
display: flex
}
summary,p{
margin: 0px 0 -1px 0px;
padding: 0 0 0 0.5rem;
border: 1px black solid
}
summary {
padding: 0 1rem 0 0.5rem
}
<div>
<details>
<summary>FILE</summary>
<p>Save</p>
<p>Save as</p>
</details>
<details>
<summary>EDIT</summary>
<p>Pump</p>
<p>Transfer</p>
<p>Review</p>
<p>Compile</p>
</details>
<details>
<summary>PREFERENCES</summary>
<p>How sweat?</p>
<p>Powered by HTML</p>
</details>
</div>
Fixed bottom menu bar, unfolding upward.
div{
display: flex;
position: fixed;
bottom: 0;
transform: rotate(180deg)
}
summary,p{
margin: 0px 0 -1px 0px;
padding: 0 0 0 0.5rem;
border: 1px black solid;
transform: rotate(180deg)
}
summary {
padding: 0 1rem 0 0.5rem;
}
<div>
<details>
<summary>FILE</summary>
<p>Save</p>
<p>Save as</p>
</details>
<details>
<summary>EDIT</summary>
<p>Pump</p>
<p>Transfer</p>
<p>Review</p>
<p>Compile</p>
</details>
<details>
<summary>PREF</summary>
<p>How?</p>
<p>Power</p>
</details>
</div>
Simplest HTML full-screen modal popup
.popup > p {
padding: 1rem;
margin: 0;
display: flex;
flex-direction: column;
width: 25vw
}
.popup summary {
padding: 1rem 0.5rem;
cursor: pointer;
max-height: 90vh;
overflow: auto
}
.popup[open] summary {
background: black;
color: white;
padding: 0.5rem;
}
.popup[open] {
position: fixed;
/* top: calc(50% - 25vw); */
left: calc(50% - 15vw);
outline: 5000px #00000090 solid;
border: 5px red solid;
border-radius: 0.5rem;
z-index: 1;
max-height: 90vh;
overflow-y: auto;
overflow-x: hidden
}
.popup[open] summary::after {
content: '❌';
float: right;
}
<details class="popup">
<summary>HTML popup</summary>
<p>
<span>Name</span>
<input value="HTML" />
<br>
<span>Difficulty</span>
<input type="number" value="3" />
<br>
<span>Coolness</span>
<input type="number" value="100" />
<br>
<p><span>Powered by HTML</span></p>
</p>
</details>
Simplest resizable pane, using JavaScript.
let ismdwn = 0
rpanrResize.addEventListener('mousedown', mD)
function mD(event) {
ismdwn = 1
document.body.addEventListener('mousemove', mV)
document.body.addEventListener('mouseup', end)
}
function mV(event) {
if (ismdwn === 1) {
pan1.style.flexBasis = event.clientX + "px"
} else {
end()
}
}
const end = (e) => {
ismdwn = 0
document.body.removeEventListener('mouseup', end)
rpanrResize.removeEventListener('mousemove', mV)
}
div {
display: flex;
border: 1px black solid;
width: 100%;
height: 200px;
}
#pan1 {
flex-grow: 1;
flex-shrink: 0;
flex-basis: 50%; /* initial status */
}
#pan2 {
flex-grow: 0;
flex-shrink: 1;
overflow-x: auto;
}
#rpanrResize {
flex-grow: 0;
flex-shrink: 0;
background: #1b1b51;
width: 0.2rem;
cursor: col-resize;
margin: 0 0 0 auto;
}
<div>
<div id="pan1">MENU</div>
<div id="rpanrResize"> </div>
<div id="pan2">BODY</div>
</div>
Improving on Reza's answer:
prevent the browser from interfering with a drag
prevent setting an element to a negative size
prevent drag getting out of sync with the mouse due to incremental delta interaction with element width saturation
<html><head><style>
.splitter {
width: 100%;
height: 100px;
display: flex;
}
#separator {
cursor: col-resize;
background-color: #aaa;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='30'><path d='M2 0 v30 M5 0 v30 M8 0 v30' fill='none' stroke='black'/></svg>");
background-repeat: no-repeat;
background-position: center;
width: 10px;
height: 100%;
/* Prevent the browser's built-in drag from interfering */
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#first {
background-color: #dde;
width: 20%;
height: 100%;
min-width: 10px;
}
#second {
background-color: #eee;
width: 80%;
height: 100%;
min-width: 10px;
}
</style></head><body>
<div class="splitter">
<div id="first"></div>
<div id="separator" ></div>
<div id="second" ></div>
</div>
<script>
// A function is used for dragging and moving
function dragElement(element, direction)
{
var md; // remember mouse down info
const first = document.getElementById("first");
const second = document.getElementById("second");
element.onmousedown = onMouseDown;
function onMouseDown(e)
{
//console.log("mouse down: " + e.clientX);
md = {e,
offsetLeft: element.offsetLeft,
offsetTop: element.offsetTop,
firstWidth: first.offsetWidth,
secondWidth: second.offsetWidth
};
document.onmousemove = onMouseMove;
document.onmouseup = () => {
//console.log("mouse up");
document.onmousemove = document.onmouseup = null;
}
}
function onMouseMove(e)
{
//console.log("mouse move: " + e.clientX);
var delta = {x: e.clientX - md.e.clientX,
y: e.clientY - md.e.clientY};
if (direction === "H" ) // Horizontal
{
// Prevent negative-sized elements
delta.x = Math.min(Math.max(delta.x, -md.firstWidth),
md.secondWidth);
element.style.left = md.offsetLeft + delta.x + "px";
first.style.width = (md.firstWidth + delta.x) + "px";
second.style.width = (md.secondWidth - delta.x) + "px";
}
}
}
dragElement( document.getElementById("separator"), "H" );
</script></body></html>
I wrote simple code for it without any third-party library. This code is only for a horizontal splitter (vertical is the same).
function onload()
{
dragElement( document.getElementById("separator"), "H" );
}
// This function is used for dragging and moving
function dragElement( element, direction, handler )
{
// Two variables for tracking positions of the cursor
const drag = { x : 0, y : 0 };
const delta = { x : 0, y : 0 };
/* If present, the handler is where you move the DIV from
otherwise, move the DIV from anywhere inside the DIV */
handler ? ( handler.onmousedown = dragMouseDown ): ( element.onmousedown = dragMouseDown );
// A function that will be called whenever the down event of the mouse is raised
function dragMouseDown( e )
{
drag.x = e.clientX;
drag.y = e.clientY;
document.onmousemove = onMouseMove;
document.onmouseup = () => { document.onmousemove = document.onmouseup = null; }
}
// A function that will be called whenever the up event of the mouse is raised
function onMouseMove( e )
{
const currentX = e.clientX;
const currentY = e.clientY;
delta.x = currentX - drag.x;
delta.y = currentY - drag.y;
const offsetLeft = element.offsetLeft;
const offsetTop = element.offsetTop;
const first = document.getElementById("first");
const second = document.getElementById("second");
let firstWidth = first.offsetWidth;
let secondWidth = second.offsetWidth;
if (direction === "H" ) // Horizontal
{
element.style.left = offsetLeft + delta.x + "px";
firstWidth += delta.x;
secondWidth -= delta.x;
}
drag.x = currentX;
drag.y = currentY;
first.style.width = firstWidth + "px";
second.style.width = secondWidth + "px";
}
}
.splitter {
width: 500px;
height: 100px;
display: flex;
}
#separator {
cursor: col-resize;
background: url(https://raw.githubusercontent.com/RickStrahl/jquery-resizable/master/assets/vsizegrip.png) center center no-repeat #535353;
width: 10px;
height: 100px;
min-width: 10px;
}
#first {
background-color: green;
width: 100px;
height: 100px;
min-width: 10px;
}
#second {
background-color: red;
width: 390px;
height: 100px;
min-width: 10px;
}
<html>
<head>
<link rel="stylesheet" href="T10-Splitter.css">
<script src="T10-Splitter.js"></script>
</head>
<body onload="onload()">
<div class="splitter">
<div id="first"></div>
<div id="separator"></div>
<div id="second"></div>
</div>
</body>
</html>
Here is my lightweight vanilla JavaScript approach, using Flexbox:
http://codepen.io/lingtalfi/pen/zoNeJp
It was tested successfully in Google Chrome 54, Firefox 50, Safari 10, don't know about other browsers.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.rawgit.com/lingtalfi/simpledrag/master/simpledrag.js"></script>
<style type="text/css">
html, body {
height: 100%;
}
.panes-container {
display: flex;
width: 100%;
overflow: hidden;
}
.left-pane {
width: 18%;
background: #ccc;
}
.panes-separator {
width: 2%;
background: red;
position: relative;
cursor: col-resize;
}
.right-pane {
flex: auto;
background: #eee;
}
.panes-container,
.panes-separator,
.left-pane,
.right-pane {
margin: 0;
padding: 0;
height: 100%;
}
</style>
</head>
<body>
<div class="panes-container">
<div class="left-pane" id="left-pane">
<p>I'm the left pane</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
<div class="panes-separator" id="panes-separator"></div>
<div class="right-pane" id="right-pane">
<p>And I'm the right pane</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. A accusantium at cum cupiditate dolorum, eius eum
eveniet facilis illum maiores molestiae necessitatibus optio possimus sequi sunt, vel voluptate. Asperiores,
voluptate!
</p>
</div>
</div>
<script>
var leftPane = document.getElementById('left-pane');
var rightPane = document.getElementById('right-pane');
var paneSep = document.getElementById('panes-separator');
// The script below constrains the target to move horizontally between a left and a right virtual boundaries.
// - the left limit is positioned at 10% of the screen width
// - the right limit is positioned at 90% of the screen width
var leftLimit = 10;
var rightLimit = 90;
paneSep.sdrag(function (el, pageX, startX, pageY, startY, fix) {
fix.skipX = true;
if (pageX < window.innerWidth * leftLimit / 100) {
pageX = window.innerWidth * leftLimit / 100;
fix.pageX = pageX;
}
if (pageX > window.innerWidth * rightLimit / 100) {
pageX = window.innerWidth * rightLimit / 100;
fix.pageX = pageX;
}
var cur = pageX / window.innerWidth * 100;
if (cur < 0) {
cur = 0;
}
if (cur > window.innerWidth) {
cur = window.innerWidth;
}
var right = (100-cur-2);
leftPane.style.width = cur + '%';
rightPane.style.width = right + '%';
}, null, 'horizontal');
</script>
</body>
</html>
This HTML code depends on the simpledrag vanilla JavaScript lightweight library (less than 60 lines of code).
Hmm, I came across this property in CSS 3.
This might be easier to use.
CSS resize Property
In the old days, you would use frames to achieve this. There are several reasons why this approach is not so good. See Reece's response to Why are HTML frames bad?. See also Jakob Nielson's Why Frames Suck (Most of the Time).
A somewhat newer approach is to use inline frames. This has pluses and minuses as well: Are iframes considered 'bad practice'?
An even better approach is to use fixed positioning. By placing the navigation content (e.g. the favorites links in your example) in a block element (like a div) then applying position:fixed to that element and setting the left, top and bottom properties like this:
#myNav {
position: fixed;
left: 0px;
top: 0px;
bottom: 0px;
width: 200px;
}
... you will achieve a vertical column down the left side of the page that will not move when the user scrolls the page.
The rest of the content on the page will not "feel" the presence of this nav element, so it must take into account the 200px of space it occupies. You can do this by placing the rest for the content in another div and setting margin-left:200px;.
Many missed this post from Barguast on Feb 27 '15 where shows a interesting generic flexbox vertical and horizontal resizer.
Take a look: Flexbox Resizing
Barguast note that "... it only handles items sized with flex-grow. If flex-shrink or flex-basis is defined, then the calculations simply don't work.", and he is looking for a better solution, so do I.
Here is his code for reference:
function manageResize(md, sizeProp, posProp)
{
var r = md.target;
var prev = r.previousElementSibling;
var next = r.nextElementSibling;
if (!prev || !next) {
return;
}
md.preventDefault();
var prevSize = prev[sizeProp];
var nextSize = next[sizeProp];
var sumSize = prevSize + nextSize;
var prevGrow = Number(prev.style.flexGrow);
var nextGrow = Number(next.style.flexGrow);
var sumGrow = prevGrow + nextGrow;
var lastPos = md[posProp];
function onMouseMove(mm)
{
var pos = mm[posProp];
var d = pos - lastPos;
prevSize += d;
nextSize -= d;
if (prevSize < 0) {
nextSize += prevSize;
pos -= prevSize;
prevSize = 0;
}
if (nextSize < 0) {
prevSize += nextSize;
pos += nextSize;
nextSize = 0;
}
var prevGrowNew = sumGrow * (prevSize / sumSize);
var nextGrowNew = sumGrow * (nextSize / sumSize);
prev.style.flexGrow = prevGrowNew;
next.style.flexGrow = nextGrowNew;
lastPos = pos;
}
function onMouseUp(mu)
{
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
}
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mouseup", onMouseUp);
}
function setupResizerEvents()
{
document.body.addEventListener("mousedown", function (md) {
var target = md.target;
if (target.nodeType !== 1 || target.tagName !== "FLEX-RESIZER") {
return;
}
var parent = target.parentNode;
var h = parent.classList.contains("h");
var v = parent.classList.contains("v");
if (h && v) {
return;
} else if (h) {
manageResize(md, "scrollWidth", "pageX");
} else if (v) {
manageResize(md, "scrollHeight", "pageY");
}
});
}
setupResizerEvents();
flex {
display: flex;
}
flex-item > flex {
position: absolute;
width: 100%;
height: 100%;
}
flex.h {
-ms-flex-direction: row;
flex-direction: row;
}
flex.v {
-ms-flex-direction: column;
flex-direction: column;
}
flex-item {
display: flex;
position: relative;
overflow: hidden;
}
flex > flex-resizer {
-ms-flex: 0 0 8px;
flex: 0 0 8px;
background: white;
}
flex.h > flex-resizer {
cursor: ew-resize;
}
flex.v > flex-resizer {
cursor: ns-resize;
}
<body>
<flex class="v" style="height: 500px">
<flex-item style="flex: 1; background: red">Flex 1</flex-item>
<flex-resizer></flex-resizer>
<flex-item style="flex: 1; background: blue">
<flex class="h">
<flex-item style="flex: 1">Flex 2</flex-item>
<flex-resizer></flex-resizer>
<flex-item style="flex: 2; background: green">
<flex class="v">
<flex-item style="flex: 1; background: pink;">Flex 3</flex-item>
<flex-resizer></flex-resizer>
<flex-item style="flex: 1">
<flex class="h">
<flex-item style="flex: 1">Flex 4</flex-item>
<flex-resizer></flex-resizer>
<flex-item style="flex: 2; background: yellow">Flex 5</flex-item>
<flex-item style="flex: 2; background: yellow">Flex 6</flex-item>
</flex>
</flex-item>
</flex>
</flex-item>
</flex>
</flex-item>
</flex>
</body>
And here is my improved version:
function manageResize(md, sizeProp, posProp) {
var r = md.target;
var prev = r.previousElementSibling;
var next = r.nextElementSibling;
if (!prev || !next) {
return;
}
md.preventDefault();
var prevSize = prev[sizeProp];
var nextSize = next[sizeProp];
var sumSize = prevSize + nextSize;
var prevGrow = Number(prev.style.flexGrow);
var nextGrow = Number(next.style.flexGrow);
var sumGrow = prevGrow + nextGrow;
var lastPos = md[posProp];
function onMouseMove(mm) {
var pos = mm[posProp];
var d = pos - lastPos;
prevSize += d;
nextSize -= d;
if (prevSize < 0) {
nextSize += prevSize;
pos -= prevSize;
prevSize = 0;
}
if (nextSize < 0) {
prevSize += nextSize;
pos += nextSize;
nextSize = 0;
}
var prevGrowNew = sumGrow * (prevSize / sumSize);
var nextGrowNew = sumGrow * (nextSize / sumSize);
prev.style.flexGrow = prevGrowNew;
next.style.flexGrow = nextGrowNew;
lastPos = pos;
}
function onMouseUp(mu) {
// Change cursor to signal a state's change: stop resizing.
const html = document.querySelector('html');
html.style.cursor = 'default';
if (posProp === 'pageX') {
r.style.cursor = 'ew-resize';
} else {
r.style.cursor = 'ns-resize';
}
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
}
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mouseup", onMouseUp);
}
function setupResizerEvents() {
document.body.addEventListener("mousedown", function (md) {
// Used to avoid cursor's flickering
const html = document.querySelector('html');
var target = md.target;
if (target.nodeType !== 1 || target.tagName !== "FLEX-RESIZER") {
return;
}
var parent = target.parentNode;
var h = parent.classList.contains("h");
var v = parent.classList.contains("v");
if (h && v) {
return;
} else if (h) {
// Change cursor to signal a state's change: begin resizing on H.
target.style.cursor = 'col-resize';
html.style.cursor = 'col-resize'; // avoid cursor's flickering
// use offsetWidth versus scrollWidth (and clientWidth) to avoid splitter's jump on resize when a flex-item content overflow (overflow: auto).
manageResize(md, "offsetWidth", "pageX");
} else if (v) {
// Change cursor to signal a state's change: begin resizing on V.
target.style.cursor = 'row-resize';
html.style.cursor = 'row-resize'; // avoid cursor's flickering
manageResize(md, "offsetHeight", "pageY");
}
});
}
setupResizerEvents();
body {
/* margin:0; */
border: 10px solid #aaa;
}
flex {
display: flex;
overflow: hidden;
}
/* flex-item > flex {
position: absolute;
width: 100%;
height: 100%;
} */
flex.h {
flex-direction: row;
}
flex.v {
flex-direction: column;
}
flex-item {
/* display: flex; */
/* position: relative; */
/* overflow: hidden; */
overflow: auto;
}
flex > flex-resizer {
flex: 0 0 10px;
/* background: white; */
background-color: #aaa;
background-repeat: no-repeat;
background-position: center;
}
flex.h > flex-resizer {
cursor: ew-resize;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='30'><path d='M2 0 v30 M5 0 v30 M8 0 v30' fill='none' stroke='black'/></svg>");
}
flex.v > flex-resizer {
cursor: ns-resize;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='10'><path d='M0 2 h30 M0 5 h30 M0 8 h30' fill='none' stroke='black'/></svg>");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>flex-splitter</title>
<link rel="stylesheet" href="./src/styles.css">
<script src="./src/index.js" defer></script>
</head>
<body>
<flex class="v" style="flex: 1; height: 500px;">
<flex-item style="flex: 1;">Flex 1</flex-item>
<flex-resizer></flex-resizer>
<flex class="h" style="flex: 1;">
<flex-item style="flex: 1; background-color: aqua;">
<!--
The next section is an example to test the splitter when there is content inside a flex-item
-->
<section>
<div>
<label for="CursorCoor" style="display: block;">showCursorCoor: </label>
<textarea id="CursorCoor" rows="6" cols="50" wrap="soft" readonly></textarea>
</div>
<br />
<div>
<label for="boxInfo" style="display: block;">showBoxInfo: </label>
<textarea id="boxInfo" rows="6" cols="50" wrap="soft" readonly></textarea>
</div>
</section>
</flex-item>
<flex-resizer></flex-resizer>
<flex class="v" style="flex: 2; ">
<flex-item style="flex: 1; background: pink;">Flex 3</flex-item>
<flex-resizer></flex-resizer>
<flex class="h" style="flex: 1">
<flex-item style="flex: 1; background: green;">Flex 4</flex-item>
<flex-resizer></flex-resizer>
<flex-item style="flex: 2;">Flex 5</flex-item>
<!-- <flex-resizer></flex-resizer> -->
<flex-item style="flex: 3; background: darkorange;">Flex 6</flex-item>
</flex>
</flex>
</flex>
</flex>
</body>
</html>
Or see it on Codesandbox:
You can do it with jQuery UI without another JavaScript library. Just add a function to the .resizable resize event to adjust the width of the other div.
$("#left_pane").resizable({
handles: 'e', // 'East' side of div draggable
resize: function() {
$("#right_pane").outerWidth( $("#container").innerWidth() - $("#left_pane").outerWidth() );
}
});
Here's the complete JSFiddle.
One totally different approach is to put things in a grid, such as ui-grid or Kendo's grid, and have the columns be resizable. A downside is that users would not be able to resize the rows, though the row size could be set programmatically.
You can use absolute of fixed positioning. This CSS for example will dock a 2em-bar on the left side of your page:
body {
padding-left: 2.5em;
}
body > #bar {
position:fixed;
top:0; left:0;
width: 2em;
height: 100%;
border-right: 2px solid #55F; background: #ddd;
}
(Demo at jsfiddle.net)
The Angular version with no third-party libraries (based on personal_cloud's answer):
import { Component, Renderer2, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit, OnDestroy {
#ViewChild('leftPanel', {static: true})
leftPanelElement: ElementRef;
#ViewChild('rightPanel', {static: true})
rightPanelElement: ElementRef;
#ViewChild('separator', {static: true})
separatorElement: ElementRef;
private separatorMouseDownFunc: Function;
private documentMouseMoveFunc: Function;
private documentMouseUpFunc: Function;
private documentSelectStartFunc: Function;
private mouseDownInfo: any;
constructor(private renderer: Renderer2) {
}
ngAfterViewInit() {
// Init page separator
this.separatorMouseDownFunc = this.renderer.listen(this.separatorElement.nativeElement, 'mousedown', e => {
this.mouseDownInfo = {
e: e,
offsetLeft: this.separatorElement.nativeElement.offsetLeft,
leftWidth: this.leftPanelElement.nativeElement.offsetWidth,
rightWidth: this.rightPanelElement.nativeElement.offsetWidth
};
this.documentMouseMoveFunc = this.renderer.listen('document', 'mousemove', e => {
let deltaX = e.clientX - this.mouseDownInfo.e.x;
// set min and max width for left panel here
const minLeftSize = 30;
const maxLeftSize = (this.mouseDownInfo.leftWidth + this.mouseDownInfo.rightWidth + 5) - 30;
deltaX = Math.min(Math.max(deltaX, minLeftSize - this.mouseDownInfo.leftWidth), maxLeftSize - this.mouseDownInfo.leftWidth);
this.leftPanelElement.nativeElement.style.width = this.mouseDownInfo.leftWidth + deltaX + 'px';
});
this.documentSelectStartFunc = this.renderer.listen('document', 'selectstart', e => {
e.preventDefault();
});
this.documentMouseUpFunc = this.renderer.listen('document', 'mouseup', e => {
this.documentMouseMoveFunc();
this.documentSelectStartFunc();
this.documentMouseUpFunc();
});
});
}
ngOnDestroy() {
if (this.separatorMouseDownFunc) {
this.separatorMouseDownFunc();
}
if (this.documentMouseMoveFunc) {
this.documentMouseMoveFunc();
}
if (this.documentMouseUpFunc) {
this.documentMouseUpFunc();
}
if (this.documentSelectStartFunc()) {
this.documentSelectStartFunc();
}
}
}
.main {
display: flex;
height: 400px;
}
.left {
width: calc(50% - 5px);
background-color: rgba(0, 0, 0, 0.1);
}
.right {
flex: auto;
background-color: rgba(0, 0, 0, 0.2);
}
.separator {
width: 5px;
background-color: red;
cursor: col-resize;
}
<div class="main">
<div class="left" #leftPanel></div>
<div class="separator" #separator></div>
<div class="right" #rightPanel></div>
</div>
Running example on Stackblitz
I found a working splitter, http://www.dreamchain.com/split-pane/, which works with jQuery v1.9. Note I had to add the following CSS code to get it working with a fixed bootstrap navigation bar.
fixed-left {
position: absolute !important; /* to override relative */
height: auto !important;
top: 55px; /* Fixed navbar height */
bottom: 0px;
}
A good library is Shield UI - you can take a look at their flexible Splitter widget and the rest of the powerful components the framework offers.