Html canvas element resets width and height to zero after drag/drop - html

I'm working on customisable dashboard where (amongst other features) users can drag dashboard tiles (div elements) around and reposition those tiles anywhere in the dashboard.
HTML Structure
The html structure is similar to the snippet below
<div class="dashboard">
<div class="tile"><canvas/></div>
<div class="tile"><canvas/></div>
<div class="tile empty"></div>
</div>
Expected Behavior
The idea is that the .dashboard can contain multiple .tiles and each .tile contains a report (a graph/chart drawn on a canvas element). Some of these .tiles can be .empty, as in, not containing any report. Then .tile can be dragged and dropped into the .empty tiles.
So, div.tile.empty serves as "dropzone" while div.tile will be draggable elements. A fiddler snippet has been added below for a simplistic-but-fully-functional example.
Libraries used
jQuery
ChartJs. An open source js library to draw charts on a canvas
The problem
It all seems to work well, except that after dropping a .tile the canvas resets its width/height to zero!!! And I haven't found a way to reset it back to its original dimensions before the drag/drop events. Even if I set the width/height manually, nothing is drawn on the canvas.
Question
Is there any way I can preserve (or recover) the width/height of the canvas while also getting it to re-drawn the graph after drag/dropping?
I tried using chartjs's update, render and resize functions to no avail.
The documentation of these functions can be found in the link below (version 3.5.0)...
https://www.chartjs.org/docs/3.5.0/developers/api.html
Code Example
Here's a sample code snippet where you can reproduce the issue mentioned above. The buttons are my attempt to update/resize/re-render the graphs after drag/dropping.
var $sourceTile = null;
var charts = [];
$(() => {
$(".buttons-container a").on("click", btnClickHandler);
renderChart("canvas1", 'doughnut');
renderChart("canvas2", "line");
attachDropHandlers();
});
attachDropHandlers = () => {
$(".tile").off("dragstart").off("dragover").off("drop");
$(".tile .report").on("dragstart", dragStartHandler);
$(".tile.empty").on("dragover", dragOverHandler);
$(".tile.empty").on("drop", dropHandler);
}
dragStartHandler = (e) => {
const $target = $(e.target);
const $report = $target.is(".report") ? $target : $target.parents(".report");
$sourceTile = $report.parents(".tile");
e.originalEvent.dataTransfer.setData("application/dashboard", $report[0].id);
e.originalEvent.dataTransfer.effectAllowed = "move";
e.originalEvent.dataTransfer.dropEffect = "move";
}
dragOverHandler = (e) => {
e.preventDefault();
e.originalEvent.dataTransfer.dropEffect = "move";
}
dropHandler = (e) => {
e.preventDefault();
const id = e.originalEvent.dataTransfer.getData("application/dashboard");
if (id) {
$("#" + id).appendTo(".tile.empty");
$(".tile.empty").removeClass("empty");
if ($sourceTile) {
$sourceTile.addClass("empty");
attachDropHandlers();
}
}
}
renderChart = (canvasId, type) => {
const labels = ["Red", "Green", "Blue"];
const data = [30, 25, 42];
const colors = ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)'];
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext('2d');
const chart = new Chart(ctx, {
type: type,
data: {
labels: labels,
datasets: [{
data: data,
backgroundColor: colors,
borderColor: colors,
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
aspectRatio: 1,
plugins: {
legend: {
display: false
},
htmlLegend: {
tile: this.$tile,
maxItems: 8
}
}
}
});
chart.update();
charts.push(chart);
}
btnClickHandler = (e) => {
const button = e.target.id;
switch (button) {
case "btn1":
charts.forEach((chart) => chart.update());
break;
case "btn2":
charts.forEach((chart) => chart.update('resize'));
break;
case "btn3":
charts.forEach((chart) => chart.render());
break;
case "btn4":
charts.forEach((chart) => chart.resize());
break;
case "btn5":
charts.forEach((chart) => chart.resize(120, 120));
break;
}
}
html,
body {
background-color: #eee;
}
h3 {
margin: 0;
padding: 10px;
}
.dashboard {}
.dashboard .tile {
display: inline-block;
vertical-align: top;
margin: 5px;
height: 250px;
width: 250px;
}
.tile.empty {
border: 2px dashed #ccc;
}
.report {
height: 250px;
width: 250px;
background-color: #fff;
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, .18);
}
.buttons-container {
display: flex;
justify-content: space-between;
margin: 20px 0;
}
.buttons-container a {
background-color: #673AB7;
color: #EDE7F6;
cursor: pointer;
padding: 10px 15px;
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, .18);
}
.buttons-container a:hover {
background-color: #7E57C2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.6.0/dist/chart.min.js"></script>
<div class="dashboard">
<div class="tile">
<div id="report1" class="report" draggable="true">
<h3>
Report 1
</h3>
<div style="padding:10px;height:180px;width:180px">
<canvas id="canvas1"></canvas>
</div>
</div>
</div>
<div class="tile">
<div id="report2" class="report" draggable="true">
<h3>
Report 2
</h3>
<div style="padding:10px;height:180px;width:180px">
<canvas id="canvas2"></canvas>
</div>
</div>
</div>
<div class="tile empty">
</div>
</div>
<div class="buttons-container">
<a id="btn1">update()</a>
<a id="btn2">update('resize')</a>
<a id="btn3">render()</a>
<a id="btn4">resize()</a>
<a id="btn5">resize(120,120)</a>
</div>

This is a Chart.js issue of version 3.6.0 and fixed in version 3.6.1. Example below:
var $sourceTile = null;
var charts = [];
$(() => {
$(".buttons-container a").on("click", btnClickHandler);
renderChart("canvas1", 'doughnut');
renderChart("canvas2", "line");
attachDropHandlers();
});
attachDropHandlers = () => {
$(".tile").off("dragstart").off("dragover").off("drop");
$(".tile .report").on("dragstart", dragStartHandler);
$(".tile.empty").on("dragover", dragOverHandler);
$(".tile.empty").on("drop", dropHandler);
}
dragStartHandler = (e) => {
const $target = $(e.target);
const $report = $target.is(".report") ? $target : $target.parents(".report");
$sourceTile = $report.parents(".tile");
e.originalEvent.dataTransfer.setData("application/dashboard", $report[0].id);
e.originalEvent.dataTransfer.effectAllowed = "move";
e.originalEvent.dataTransfer.dropEffect = "move";
}
dragOverHandler = (e) => {
e.preventDefault();
e.originalEvent.dataTransfer.dropEffect = "move";
}
dropHandler = (e) => {
e.preventDefault();
const id = e.originalEvent.dataTransfer.getData("application/dashboard");
if (id) {
$("#" + id).appendTo(".tile.empty");
$(".tile.empty").removeClass("empty");
if ($sourceTile) {
$sourceTile.addClass("empty");
attachDropHandlers();
}
}
}
renderChart = (canvasId, type) => {
const labels = ["Red", "Green", "Blue"];
const data = [30, 25, 42];
const colors = ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)'];
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext('2d');
const chart = new Chart(ctx, {
type: type,
data: {
labels: labels,
datasets: [{
data: data,
backgroundColor: colors,
borderColor: colors,
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
aspectRatio: 1,
plugins: {
legend: {
display: false
},
htmlLegend: {
tile: this.$tile,
maxItems: 8
}
}
}
});
chart.update();
charts.push(chart);
}
btnClickHandler = (e) => {
const button = e.target.id;
switch (button) {
case "btn1":
charts.forEach((chart) => chart.update());
break;
case "btn2":
charts.forEach((chart) => chart.update('resize'));
break;
case "btn3":
charts.forEach((chart) => chart.render());
break;
case "btn4":
charts.forEach((chart) => chart.resize());
break;
case "btn5":
charts.forEach((chart) => chart.resize(120, 120));
break;
}
}
html,
body {
background-color: #eee;
}
h3 {
margin: 0;
padding: 10px;
}
.dashboard {}
.dashboard .tile {
display: inline-block;
vertical-align: top;
margin: 5px;
height: 250px;
width: 250px;
}
.tile.empty {
border: 2px dashed #ccc;
}
.report {
height: 250px;
width: 250px;
background-color: #fff;
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, .18);
}
.buttons-container {
display: flex;
justify-content: space-between;
margin: 20px 0;
}
.buttons-container a {
background-color: #673AB7;
color: #EDE7F6;
cursor: pointer;
padding: 10px 15px;
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, .18);
}
.buttons-container a:hover {
background-color: #7E57C2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.6.1/dist/chart.min.js"></script>
<div class="dashboard">
<div class="tile">
<div id="report1" class="report" draggable="true">
<h3>
Report 1
</h3>
<div style="padding:10px;height:180px;width:180px">
<canvas id="canvas1"></canvas>
</div>
</div>
</div>
<div class="tile">
<div id="report2" class="report" draggable="true">
<h3>
Report 2
</h3>
<div style="padding:10px;height:180px;width:180px">
<canvas id="canvas2"></canvas>
</div>
</div>
</div>
<div class="tile empty">
</div>
</div>
<div class="buttons-container">
<a id="btn1">update()</a>
<a id="btn2">update('resize')</a>
<a id="btn3">render()</a>
<a id="btn4">resize()</a>
<a id="btn5">resize(120,120)</a>
</div>

Related

Change color of absolutely positioned element when overlapping with another

I am trying to build a component where you can visualize on what section are you in and allows you to easily move sections on the page.
My page is structured like this
<SectionManager /> // the absolutely positioned element
<Navbar />
<Menu />
<Section1 />
<Section2 />
<Section3 />
{...}
I want to have every even numbered section to have a black background and the others to have a white background. Now I want the text inside my SectionManager component to be white when overlapping a black background and black when overlapping a white background.
Here is a photo:
My component is the one on the left. And when you scroll down to the black section I want just the about me text and the circle after that to turn white.
Sorry if this is a stupid question by I searched for hours and did not find anything. I tried mix-blend-mode but it did not work.
Here the code for my component:
const SectionManager: React.FC = () => {
const globalState = React.useContext(MyContext);
const observerCallback = (entries: IntersectionObserverEntry[]) => {
...
};
const observerOptions = React.useMemo(
...
);
React.useEffect(() => {
const observer = new IntersectionObserver(...);
globalState.currentSections.forEach((section: HTMLElement) => {
observer.observe(section);
});
}, []);
const sections = [
{
text: "Hello!",
},
{
text: "about me",
},
{
text: "work i did",
},
{
text: "contact",
},
];
return (
<div className={styles.sectionManager}>
{sections.map((section, sectionID) => (
<>
{sectionID > 0 && (
<div className={styles.sectionManager_separator}></div>
)}
<div
className={
sectionID === globalState.activeSectionId
? `${styles.sectionManager_item} ${styles.sectionManager_itemActive}`
: styles.sectionManager_item
}
>
<p>{section.text}</p>
</div>
</>
))}
</div>
);
};
export default SectionManager;
here is the scss file:
.sectionManager {
position: fixed;
z-index: 100;
right: 30px;
top: 50%;
display: flex;
flex-direction: column;
align-items: flex-end;
transform: translateY(-50%);
&_separator {
width: 1px;
height: 25px;
background: $text-secondary-dark;
margin-right: 7px;
}
&_itemActive {
&::after {
background-color: $text-primary-light !important;
transform: scale(1) !important;
}
p {
color: $text-primary-light !important;
transform: scaleX(1) !important;
}
}
&_item {
mix-blend-mode: difference;
display: flex;
align-items: center;
font-size: 1rem;
margin-top: 5px;
cursor: pointer;
background: transparent;
#include transition();
&:hover {
&::after {
background-color: $text-primary-light;
transform: scale(1);
}
p {
transform: scaleX(1);
color: $text-primary-light;
}
}
p {
margin: 0;
transform: scaleX(0);
transform-origin: right;
color: $text-secondary-light;
#include transition();
}
&::after {
content: "";
width: 15px;
height: 15px;
border-radius: 999999px;
margin-left: 10px;
transform: scale(0.9);
background: $text-secondary-dark;
#include transition();
}
}
}
And for the section background I am not doing anything fancy, I am just setting a background-color property on there.
Thank you in advance!
Edit:
I want something similar to that. The design is in figma.
I solved the issue!
I ended up getting all the sections on my page using querySelector and using an IntersectionObserver to get the section that is in viewPort and get its background color, then passing the background color to my component using data-section-bg.
Here is the whole component code:
const SectionManager: React.FC = () => {
const [currentSectionBg, setCurrentSectionsBg] =
React.useState<string>("#fff");
const globalState = React.useContext(MyContext);
const observerCallback = (entries: IntersectionObserverEntry[]) => {
// other observer ...
};
const sectionColorObserverCallback = (
entries: IntersectionObserverEntry[]
) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0.25) {
const sectionBgColor = (
document.getElementById(entry.target.id) as HTMLElement
).style.backgroundColor;
console.log(sectionBgColor);
setCurrentSectionsBg(sectionBgColor);
}
});
};
const observerOptions = React.useMemo(
() => ({
root: null,
rootMargin: "0px",
threshold: 0.25,
}),
[]
);
React.useEffect(() => {
const observer = new IntersectionObserver(
// other observer...
);
globalState.currentSections.forEach((section: HTMLElement) => {
// other observer...
});
// Detect Section Color Observer
const allSections = document.querySelectorAll("section");
if (!allSections) return;
const sectionColorObserver = new IntersectionObserver(
sectionColorObserverCallback,
observerOptions
);
allSections.forEach((section, sectionId) => {
section.id = `SECTION_${sectionId}`;
section.style.backgroundColor = sectionId % 2 === 0 ? "#fff" : "#000";
sectionColorObserver.observe(section);
});
}, []);
const sections = [
{
text: "Hello!",
},
{
text: "about me",
},
{
text: "work i did",
},
{
text: "contact",
},
];
return (
<motion.div
initial={{ x: 150, opacity: 0 }}
animate={{
x: 0,
y: "-50%",
opacity: 1,
transition: {
duration: 1,
delay: 0.8,
ease: defaultAnimationEasing,
},
}}
className={styles.sectionManager}
>
{sections.map((section, sectionID) => (
<>
{sectionID > 0 && (
<div className={styles.sectionManager_separator}></div>
)}
<div
data-section-bg={currentSectionBg}
className={
sectionID === globalState.activeSectionId
? `${styles.sectionManager_item} ${styles.sectionManager_itemActive}`
: styles.sectionManager_item
}
>
<p>{section.text}</p>
</div>
</>
))}
</motion.div>
);
};
export default SectionManager;
Here is what I added to my scss File:
[data-section-bg="rgb(0, 0, 0)"] {
&:hover {
&::after {
background: $text-primary-dark !important;
}
p {
color: $text-primary-dark;
}
}
p {
color: $text-primary-dark;
}
}
[data-section-bg="rgb(255, 255, 255)"] {
&:hover {
&::after {
background: $text-primary-light !important;
}
p {
color: $text-primary-light;
}
}
p {
color: $text-primary-light;
}
}
&_itemActive[data-section-bg="rgb(255, 255, 255)"] {
&::after {
background-color: $text-primary-light !important;
}
}
&_itemActive[data-section-bg="rgb(0, 0, 0)"] {
&::after {
background-color: $text-primary-dark !important;
}
}

Why width includes border when box-sizing is content-box?

I have this html file
<html lang="en" class=""><head>
<meta charset="UTF-8">
<title>CodePen Demo</title>
<meta name="robots" content="noindex">
<link rel="shortcut icon" type="image/x-icon" href="https://static.codepen.io/assets/favicon/favicon-aec34940fbc1a6e787974dcd360f2c6b63348d4b1f4e06c77743096d55480f33.ico">
<link rel="mask-icon" type="" href="https://static.codepen.io/assets/favicon/logo-pin-8f3771b1072e3c38bd662872f6b673a722f4b3ca2421637d5596661b4e2132cc.svg" color="#111">
<link rel="canonical" href="https://codepen.io/hardkoded/pen/VwjvWBm">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<style class="INLINE_PEN_STYLESHEET_ID">
body {
font: 14px "Century Gothic", Futura, sans-serif;
margin: 20px;
}
ol, ul {
padding-left: 30px;
}
.board-row:after {
clear: both;
content: "";
display: table;
}
.status {
margin-bottom: 10px;
}
.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
padding: 0;
text-align: center;
width: 34px;
}
.square:focus {
outline: none;
}
.kbd-navigation .square:focus {
background: #ddd;
}
.game {
display: flex;
flex-direction: row;
}
.game-info {
margin-left: 20px;
}
</style>
<script src="https://static.codepen.io/assets/editor/iframe/iframeConsoleRunner-7f4d47902dc785f30dedcac9c996b9f31d4dfcc33567cc48f0431bc918c2bf05.js"></script>
<script src="https://static.codepen.io/assets/editor/iframe/iframeRefreshCSS-e03f509ba0a671350b4b363ff105b2eb009850f34a2b4deaadaa63ed5d970b37.js"></script>
<script src="https://static.codepen.io/assets/editor/iframe/iframeRuntimeErrors-29f059e28a3c6d3878960591ef98b1e303c1fe1935197dae7797c017a3ca1e82.js"></script>
</head>
<body class="mouse-navigation">
<div id="errors" style="
background: #c00;
color: #fff;
display: none;
margin: -20px -20px 20px;
padding: 20px;
white-space: pre-wrap;
"></div>
<div id="root"><div class="game"><div class="game-board"><div><div class="board-row"><button class="square"></button><button class="square"></button><button class="square"></button></div><div class="board-row"><button class="square"></button><button class="square"></button><button class="square"></button></div><div class="board-row"><button class="square"></button><button class="square"></button><button class="square"></button></div></div></div><div class="game-info"><div id="status">Next player: X</div><ol><li><button>Go to game start</button></li></ol></div></div></div>
<script>
window.addEventListener('mousedown', function(e) {
document.body.classList.add('mouse-navigation');
document.body.classList.remove('kbd-navigation');
});
window.addEventListener('keydown', function(e) {
if (e.keyCode === 9) {
document.body.classList.add('kbd-navigation');
document.body.classList.remove('mouse-navigation');
}
});
window.addEventListener('click', function(e) {
if (e.target.tagName === 'A' && e.target.getAttribute('href') === '#') {
e.preventDefault();
}
});
window.onerror = function(message, source, line, col, error) {
var text = error ? error.stack || error : message + ' (at ' + source + ':' + line + ':' + col + ')';
errors.textContent += text + '\n';
errors.style.display = '';
};
console.error = (function(old) {
return function error() {
errors.textContent += Array.prototype.slice.call(arguments).join(' ') + '\n';
errors.style.display = '';
old.apply(this, arguments);
}
})(console.error);
</script>
<script src="https://static.codepen.io/assets/common/stopExecutionOnTimeout-157cd5b220a5c80d4ff8e0e70ac069bffd87a61252088146915e8726e5d9f147.js"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script id="INLINE_PEN_JS_ID">
function Square(props) {
return (
React.createElement("button", { className: "square", onClick: props.onClick },
props.value));
}
class Board extends React.Component {
renderSquare(i) {
return (
React.createElement(Square, {
value: this.props.squares[i],
onClick: () => this.props.onClick(i) }));
}
render() {
return (
React.createElement("div", null,
React.createElement("div", { className: "board-row" },
this.renderSquare(0),
this.renderSquare(1),
this.renderSquare(2)),
React.createElement("div", { className: "board-row" },
this.renderSquare(3),
this.renderSquare(4),
this.renderSquare(5)),
React.createElement("div", { className: "board-row" },
this.renderSquare(6),
this.renderSquare(7),
this.renderSquare(8))));
}}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [
{
squares: Array(9).fill(null) }],
stepNumber: 0,
xIsNext: true };
}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
this.setState({
history: history.concat([
{
squares: squares }]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext });
}
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: step % 2 === 0 });
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const moves = history.map((step, move) => {
const desc = move ?
'Go to move #' + move :
'Go to game start';
return (
React.createElement("li", { key: move },
React.createElement("button", { onClick: () => this.jumpTo(move) }, desc)));
});
let status;
if (winner) {
status = "Winner: " + winner;
} else {
status = "Next player: " + (this.state.xIsNext ? "X" : "O");
}
return (
React.createElement("div", { className: "game" },
React.createElement("div", { className: "game-board" },
React.createElement(Board, {
squares: current.squares,
onClick: i => this.handleClick(i) })),
React.createElement("div", { className: "game-info" },
React.createElement("div", { id: "status" }, status),
React.createElement("ol", null, moves))));
}}
// ========================================
ReactDOM.render(React.createElement(Game, null), document.getElementById("root"));
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]];
for (let i = 0; i < lines.length; i++) {if (window.CP.shouldStopExecution(0)) break;
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}window.CP.exitedLoop(0);
return null;
}
//# sourceURL=pen.js
</script>
</body></html>
It's a tic tac toe game from this codepen link https://codepen.io/sophiebits/pen/qNOZOP (I've modified it a little bit).
When I used the inspect utility of Chrome to select one square, and looked at the computed css box model, it says the content of the square is 32px. But in the css portion of the html file, I clearly set the width of the square to be 34px, shouldn't the computed css box model have content width of 34px?
I know that the default value of box-sizing is content-box, so the width property should contain neither border nor padding. That's why I have this question.
Buttons (and some other items) use a box-sizing property "border-box" instead of "content-box"; this explains the different behavior.
Documentation for reference: https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing
You can change this in css using:
.square{
box-sizing: content-box; /* border-box */
}
See this very simple JSFiddle: https://jsfiddle.net/ue5f164h/
<div class="box"></div>
.box {
background: blue;
border: 5px solid red;
width: 20px;
height: 20px;
}
For me, the width is correct!
You should give a smaller reproducible example in your question so that it's easier for us to debug what's gone wrong.
But as the other answer points out, the problem is that some elements have a different default box-sizing value.
Basically the way box-sizing works is that, it determines if element width should include border or not.
For example -> If you have a div with width of 300px
By using box-sizing: border-box like so
div {
width: 300px;
height: 100px;
border: 10px solid blue;
box-sizing: border-box;
}
Then the width of this div element will always be 300px -> 20px of border and 280px of content -> by adding padding or changing border size you are changing the size of the content
If you use box-sizing: content-box like so:
div {
width: 300px;
height: 100px;
border: 10px solid red;
box-sizing: content-box;
}
The width of the div element will now be 320px -> 300px of content + 20px of border width.
So if you want your element to always have width or height of lets say 50px you would use box-sizing: border-box

Traffic lights on vue.js doesn't work, how to solve?

I created a traffic light using vue.js, but it doesn't work. It should display the colours (red, yellow and green) according to the time duration. Is there a problem that I've missed?
CSS
#screen {
width: 450px;
height: 740px;
background: #222;
border-radius: 12px;
margin: auto;
padding: 23px;
}
.light {
width: 230px;
height: 270px;
display: inline-block;
opacity: 0.2;
border-radius: 100%;
transition: opacity 10s;
margin-bottom: 12px;
}
.active {
opacity: 1;
}
.red {
background: red;
}
.yellow {
background: yellow;
}
.green {
background: green;
}
My HTMl
I've created the divs.
<div id="screen">
<div id="light red" :class="{active: now=='red'}"></div>
<div id="light yellow" :class="{active: now=='yellow'}"></div>
<div id="light green" :class="{active: now=='green'}"></div>
</div>
and this is vue.js
It seems like everything on it's place and console doesn't send any error.
But I still can't understand, why it isn't working?
class State {
constructor(name, dur, next){
this.name = name;
this.dur = dur;
this.next = next;
}
}
class Constroller {
trigger(state, callback){
callback(state);
setTimeout(()=>{
this.trigger(state.next, callback);
}, state.dur * 10)
}
}
var app = new Vue({
el: '#screen',
data:{
now: 'red'
},
mounted(){
var constroller = new Constroller();
var red = new State('red', 2);
var yellowRed = new State('yellow', 1);
var yellowGreen = new State('yellow', 1);
var green = new State('green', 3);
red.next = yellowRed;
yellowR.next = green;
green.next = yellowGreen;
yellowG.next = red;
constroller.trigger(red, (state)=>{
this.now = state.name;
});
}
})
Am I missing smth? Should I rewrite my function?
Well there are several things wrong here:
<div id="light red" :class="{active: now=='red'}"></div>
<div id="light yellow" :class="{active: now=='yellow'}"></div>
<div id="light green" :class="{active: now=='green'}"></div>
Should be class instead of id.
var red = new State('red', 2);
var yellowRed = new State('yellow', 1);
var yellowGreen = new State('yellow', 1);
var green = new State('green', 3);
red.next = yellowRed;
yellowR.next = green;
green.next = yellowGreen;
yellowG.next = red;
You named yellowRed and yellowGreen but then used yellowR and YellowG
Anyway, I made a quick fiddle here https://jsfiddle.net/Lo50j4rw/ that you can check out, I also tweak some duration stuff.
Also, at least in my country the light goes green after red :D
Your main problem is that you used id where you should have used class for your HTML light elements. You also had weird choices for timing: each light had a very short duration, but the transition was 10 seconds.
Fixing those, you get this:
class State {
constructor(name, dur, next) {
this.name = name;
this.dur = dur;
this.next = next;
}
}
class Constroller {
trigger(state, callback) {
callback(state);
setTimeout(() => {
this.trigger(state.next, callback);
}, state.dur * 1000)
}
}
new Vue({
el: '#screen',
data: {
now: 'red'
},
mounted() {
var constroller = new Constroller();
var red = new State('red', 2);
var yellowRed = new State('yellow', 1);
var yellowGreen = new State('yellow', 1);
var green = new State('green', 3);
red.next = yellowRed;
yellowRed.next = green;
green.next = yellowGreen;
yellowGreen.next = red;
constroller.trigger(red, (state) => {
this.now = state.name;
});
}
})
#screen {
width: 450px;
height: 740px;
background: #222;
border-radius: 12px;
margin: auto;
padding: 23px;
}
.light {
width: 230px;
height: 270px;
display: inline-block;
opacity: 0.2;
border-radius: 100%;
transition: opacity 0.3s;
margin-bottom: 12px;
background-color: white;
}
.active {
opacity: 1;
}
.red {
background: red;
}
.yellow {
background: yellow;
}
.green {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="screen">
<div class="light red" :class="{active: now=='red'}"></div>
<div class="light yellow" :class="{active: now=='yellow'}"></div>
<div class="light green" :class="{active: now=='green'}"></div>
</div>

Default value is not showing for input number type

I'm trying to change the code from showing a placeholder "quantity" to having a default value of 1. Users have given feedback that it would help to have a common value in place, instead of having to enter it.
Here's what I tried, it removes the placeholder, but the number field looks blank. (when I inspect element, it does show my code, just the number does not appear in the box.) I'm not very experienced in input coding, any help is appreciated. Thanks!
<div class="bo-quantity-input-section bo-col-3">
<input type="number" value="1"
ng-model="lineItem.quantity"
ng-change="quantityChanged()"
tabindex="[[1000 + 2 * index + 1]]"/>
</div>
Here's the original chunk of code:
<div class="bo-quantity-input-section bo-col-3">
<input type="number" placeholder="Quantity"
ng-model="lineItem.quantity"
ng-change="quantityChanged()"
tabindex="[[1000 + 2 * index + 1]]"/>
</div>
Here's the entire page:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/angucomplete-alt/1.3.0/angucomplete-alt.min.js"></script>
<div ng-app="bulkOrderAppModule">
<div ng-controller="BulkOrderRootCtrl" class="bo-app"><bo-line-item ng-repeat="lineItem in lineItems" line-item="lineItem" index="$index" all-line-items="lineItems"> </bo-line-item>
<div class="bo-row">
<div class="bo-add-line-item bo-col-12"><a ng-click="addLineItem()"> Add Line Item </a></div>
</div>
<div class="bo-row">
<div class="bo-cart-controls">
<div class="bo-cart-link bo-col-6"> Go to Cart - Total: <span ng-bind-html="cart['total_price'] | shopifyMoneyFormat"></span>  |  [[cart['item_count'] ]] Items </div>
<div class="bo-clear-cart bo-col-3"><a ng-click="clearCart()"> Clear Cart </a></div>
<div class="bo-update-cart bo-col-3"><button class="btn bo-update-cart-btn" ng-disabled="!hasChanges" ng-click="updateCart()"> Update Cart </button></div>
</div>
</div>
</div>
<script type="text/ng-template" id="line-item-template">// <![CDATA[
<div class="bo-line-item">
<div class="bo-row">
<div class="bo-variant-input-section bo-col-8">
<angucomplete-alt ng-if="!lineItem.searchResult"
placeholder="Search for products by name or SKU"
pause="400"
selected-object="selectResult"
remote-url="/search?type=product&view=bulk-order-json&q="
remote-url-data-field="results"
title-field="product_title,variant_title"
image-field="thumbnail_url"
input-class="bo-variant-input"
bo-configure-angucomplete bo-tabindex="[[1000 + 2 * index]]">
</angucomplete-alt>
<div ng-if="lineItem.searchResult">
<div class="bo-col-2 bo-img-container">
<img class="bo-img" ng-src="[[lineItem.searchResult['thumbnail_url'] ]]"/>
</div>
<div class="bo-col-10">
<div class="bo-line-item-details">
[[lineItem.searchResult['product_title'] ]]
<span ng-if="lineItem.searchResult['variant_title']">
-
[[lineItem.searchResult['variant_title'] ]]
</span>
<span ng-if="lineItem.searchResult['sku']">
-
[[lineItem.searchResult['sku'] ]]
</span>
</div>
<div class="bo-line-item-price" ng-if="lineItem.searchResult['price']">
Unit price: <span ng-bind-html="lineItem.searchResult['price'] | shopifyMoneyFormat"></span>
</div>
<div ng-if="numVariants() > 1 && !lineItem.expanded">
<a href="javascript:void(0)" ng-click="expandAllVariants()">
Expand all [[numVariants()]] variants
</a>
</div>
</div>
</div>
</div>
<div class="bo-quantity-input-section bo-col-3">
<input type="number" placeholder="Quantity"
ng-model="lineItem.quantity"
ng-change="quantityChanged()"
tabindex="[[1000 + 2 * index + 1]]"/>
</div>
<div class="bo-remove-section bo-col-1">
<a href="javascript:void(0)" ng-click="deleteLineItem()">
<div class="bo-svg-container">
<svg viewBox="0 0 49 49" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
<path d="M24.486,-3.55271368e-15 C10.984,-3.55271368e-15 -3.55271368e-15,10.985 -3.55271368e-15,24.486 C-3.55271368e-15,37.988 10.984,48.972 24.486,48.972 C37.988,48.972 48.972,37.988 48.972,24.486 C48.972,10.984 37.988,-3.55271368e-15 24.486,-3.55271368e-15 L24.486,-3.55271368e-15 Z M24.486,45.972 C12.638,45.972 3,36.331 3,24.485 C3,12.637 12.639,3 24.486,3 C36.334,3 45.972,12.638 45.972,24.486 C45.972,36.334 36.334,45.972 24.486,45.972 L24.486,45.972 Z M32.007,16.965 C31.42,16.379 30.471,16.379 29.885,16.965 L24.486,22.365 L19.087,16.966 C18.501,16.38 17.552,16.38 16.966,16.966 C16.381,17.551 16.38,18.502 16.966,19.088 L22.365,24.486 L16.965,29.886 C16.38,30.471 16.379,31.421 16.965,32.007 C17.55,32.593 18.501,32.592 19.086,32.007 L24.486,26.607 L29.884,32.006 C30.47,32.591 31.42,32.591 32.005,32.006 C32.592,31.419 32.591,30.47 32.005,29.884 L26.607,24.486 L32.007,19.087 C32.593,18.501 32.592,17.551 32.007,16.965 L32.007,16.965 Z" id="Shape" fill="#404040" sketch:type="MSShapeGroup"></path>
</g>
</svg>
</div>
</a>
</div>
</div>
<div class="bo-row" ng-if="showLineItemAlreadyExistsMsg">
<div class="bo-col-12 bo-line-item-already-exists-msg">
A line item already exists for that product
</div>
</div>
</div>
// ]]></script><script>// <![CDATA[
var template = document.getElementById('line-item-template');
template.innerHTML = template.innerHTML.replace('// <![CDATA[', '').replace('// ]]>', '');
// ]]></script></div>
<style><!--
.bo-app {
padding: 20px 0px 10px 0px;
border: 1px solid #EEEEEE;
}
.bo-variant-input-section {
display: inline-block;
}
.bo-quantity-input-section {
display: inline-block;
}
.bo-remove-section {
display: inline-block;
height: 50px;
line-height: 50px;
text-align: center;
}
.bo-svg-container {
padding: 5px 0px;
}
.bo-remove-section svg {
height: 25px;
width: 25px;
}
.bo-variant-input {
width: 100%;
}
.bo-line-item {
margin-bottom: 20px;
}
.bo-line-item input {
height: 50px !important;
width: 100% !important;
padding-top: 0px !important;
padding-bottom: 0px !important;
}
.bo-img {
margin-left: 0px !important;
max-height: 50px !important;
width: auto !important;
}
.bo-img-container {
max-height: 50px !important;
}
.bo-line-item-details {
font-size: 1.05rem;
}
.angucomplete-searching {
padding: 0px 5px;
font-size: 1.05rem;
}
.angucomplete-holder{
position: relative;
}
.angucomplete-dropdown {
margin-top: 0px;
padding: 20px 10px;
background-color: #FCFCFC;
border: 1px solid #DDDDDD;
max-height: 360px;
overflow: scroll;
position: absolute;
z-index: 999;
width: 100%;
}
.angucomplete-row {
min-height: 50px;
margin-bottom: 20px;
cursor: pointer;
}
.angucomplete-image-holder {
width: calc(16.66666667% - 20px);
float: left;
padding: 0px 5px;
margin: 0px !important;
}
.angucomplete-image {
max-height: 50px !important;
width: auto !important;
}
.angucomplete-title {
width: calc(83.33333333% - 20px);
float: left;
font-size: 1.05rem;
padding: 0px 5px;
}
.bo-add-line-item {
position: relative;
font-size: 1.05rem;
margin-top: 10px;
}
.bo-cart-controls {
margin-top: 20px;
font-size: 1.05rem;
}
.bo-clear-cart,
.bo-update-cart {
text-align: right;
margin-bottom: 10px;
}
.bo-update-cart-btn {
float: right;
max-width: 80%;
position: relative;
bottom: 5px;
}
.bo-line-item-already-exists-msg {
color: red;
}
.bo-row {
padding: 0px 10px;
min-height: 50px;
}
.bo-col-1 {
width: calc(8.33333333% - 20px);
float: left;
}
.bo-col-2 {
width: calc(16.6666667% - 20px);
float: left;
}
.bo-col-3 {
width: calc(25% - 20px);
float: left;
}
.bo-col-4 {
width: calc(33.33333333% - 20px);
float: left;
}
.bo-col-5 {
width: calc(41.66666667% - 20px);
float: left;
}
.bo-col-6 {
width: calc(50% - 20px);
float: left;
}
.bo-col-7 {
width: calc(58.33333333% - 20px);
float: left;
}
.bo-col-8 {
width: calc(66.66666667% - 20px);
float: left;
}
.bo-col-9 {
width: calc(75% - 20px);
float: left;
}
.bo-col-10 {
width: calc(83.33333333% - 20px);
float: left;
}
.bo-col-11 {
width: calc(91.66666667% - 20px);
float: left;
}
.bo-col-12 {
width: calc(100% - 20px);
float: left;
}
.bo-col-1, .bo-col-2, .bo-col-3, .bo-col-4, .bo-col-5, .bo-col-6,
.bo-col-7, .bo-col-8, .bo-col-9, .bo-col-10, .bo-col-11, .bo-col-12 {
margin: 0px 10px;
}
--></style><script>// <![CDATA[
(function() {
function BulkOrderRootCtrl($scope, $http, $timeout) {
$scope.lineItems = [];
$scope.cart = null;
$scope.hasChanges = false;
$http.get('/cart.js').success(function(response) {
$scope.cart = response;
});
$scope.addLineItem = function(opt_initial) {
$scope.lineItems.push({
searchResult: null,
expanded: false,
quantity: null
});
if (!opt_initial) {
$scope.hasChanges = true;
}
};
// Initialize the first empty line item in a timeout.
// Certain themes look for number inputs at page load time
// and replace them with custom widgets.
$timeout(function() {
$scope.addLineItem(true);
});
$scope.updateCart = function() {
$http.post('/cart/update.js', {
'updates': _.reduce($scope.lineItems, function(obj, lineItem) {
if (lineItem.searchResult && _.isNumber(lineItem.quantity)) {
obj[lineItem.searchResult['variant_id']] = lineItem.quantity;
}
return obj;
}, {})
})
.success(function(response) {
$scope.cart = response;
$scope.hasChanges = false;
$scope.lineItems = _.filter($scope.lineItems, function(lineItem) {
return lineItem.quantity > 0;
});
})
.error(function(response) {
// Handle out of stock here
console.log(response);
});
};
$scope.clearCart = function() {
$http.post('/cart/clear.js')
.success(function(response) {
$scope.cart = response;
$scope.lineItems = [];
$scope.hasChanges = false;
});
};
$scope.$on('quantity-changed', function() {
$scope.hasChanges = true;
});
$scope.$on('delete-line-item', function(event, lineItem) {
var idx = $scope.lineItems.indexOf(lineItem);
if (idx != -1) {
$scope.lineItems.splice(idx, 1);
}
});
$scope.$on('expand-all-variants', function(event, lineItem) {
var idx = $scope.lineItems.indexOf(lineItem);
if (idx != -1) {
var args = [idx, 1];
angular.forEach(lineItem.searchResult['product']['variants'], function(variant) {
var imageUrl = '';
if (variant['featured_image'] && variant['featured_image']['src']) {
imageUrl = variant['featured_image']['src']
} else if (lineItem.searchResult['product']['featured_image']) {
imageUrl = lineItem.searchResult['product']['featured_image'];
}
args.push({
quantity: lineItem.searchResult['variant_id'] == variant['id'] ? lineItem.quantity : null,
expanded: true,
searchResult: {
'product_title': lineItem.searchResult['product_title'],
'variant_title': variant['title'],
'variant_id': variant['id'],
'sku': variant['sku'],
'price': variant['price'],
'url': variant['url'],
'product': lineItem.searchResult['product'],
'thumbnail_url': shopifyImageUrl(imageUrl, 'thumb')
}
});
});
Array.prototype.splice.apply($scope.lineItems, args);
}
});
}
function boLineItem() {
return {
scope: {
lineItem: '=',
index: '=',
allLineItems: '='
},
templateUrl: 'line-item-template',
controller: function($scope) {
$scope.showLineItemAlreadyExistsMsg = false;
$scope.selectResult = function(result) {
$scope.showLineItemAlreadyExistsMsg = false;
if ($scope.variantLineItemAlreadyExists(result.originalObject['variant_id'])) {
$scope.showLineItemAlreadyExistsMsg = true;
} else {
$scope.lineItem.searchResult = result.originalObject;
}
};
$scope.variantLineItemAlreadyExists = function(variantId) {
var exists = false;
angular.forEach($scope.allLineItems, function(lineItem) {
if (lineItem !== $scope.lineItem && lineItem.searchResult['variant_id'] == variantId) {
exists = true;
}
});
return exists;
};
$scope.quantityChanged = function() {
$scope.$emit('quantity-changed');
};
$scope.deleteLineItem = function() {
if (_.isNumber($scope.lineItem.quantity)) {
$scope.lineItem.quantity = 0;
$scope.quantityChanged();
} else {
$scope.$emit('delete-line-item', $scope.lineItem);
}
};
$scope.numVariants = function() {
return $scope.lineItem.searchResult['product']['variants'].length;
};
$scope.expandAllVariants = function() {
$scope.$emit('expand-all-variants', $scope.lineItem);
};
}
};
}
function boConfigureAngucomplete($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var input = element.find('input');
input.attr('tabindex', attrs.boTabindex);
$timeout(function() {
input.focus();
});
}
};
}
function shopifyImageUrl(url, imageType) {
if (url.indexOf('_' + imageType + '.') != -1) {
return url;
}
var dotIdx = url.lastIndexOf('.');
return [url.slice(0, dotIdx), '_', imageType, url.slice(dotIdx, url.length)].join('');
}
function shopifyMoneyFormat($shopifyMoneyFormatString, $sce) {
return function(cents) {
return $sce.trustAsHtml(Shopify.formatMoney(cents, $shopifyMoneyFormatString));
};
}
function interpolator($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}
// Polyfill for themes that don't include these:
function polyfillShopifyBuiltins() {
if (!window['Shopify']) {
window['Shopify'] = {};
}
if (!Shopify.formatMoney) {
Shopify.formatMoney = function(cents, format) {
if (typeof cents == 'string') cents = cents.replace('.','');
var value = '';
var patt = /\{\{\s*(\w+)\s*\}\}/;
var formatString = (format || this.money_format);
function addCommas(moneyString) {
return moneyString.replace(/(\d+)(\d{3}[\.,]?)/,'$1,$2');
}
switch(formatString.match(patt)[1]) {
case 'amount':
value = addCommas(floatToString(cents/100.0, 2));
break;
case 'amount_no_decimals':
value = addCommas(floatToString(cents/100.0, 0));
break;
case 'amount_with_comma_separator':
value = floatToString(cents/100.0, 2).replace(/\./, ',');
break;
case 'amount_no_decimals_with_comma_separator':
value = addCommas(floatToString(cents/100.0, 0)).replace(/\./, ',');
break;
}
return formatString.replace(patt, value);
};
if (!window['floatToString']) {
window['floatToString'] = function(numeric, decimals) {
var amount = numeric.toFixed(decimals).toString();
if(amount.match(/^\.\d+/)) {return "0"+amount; }
else { return amount; }
}
}
}
}
polyfillShopifyBuiltins();
angular.module('bulkOrderAppModule', ['angucomplete-alt'], interpolator)
.controller('BulkOrderRootCtrl', BulkOrderRootCtrl)
.directive('boLineItem', boLineItem)
.directive('boConfigureAngucomplete', boConfigureAngucomplete)
.filter('shopifyMoneyFormat', shopifyMoneyFormat)
.value('$shopifyMoneyFormatString', BO_MONEY_FORMAT);
})();
// ]]></script>

How to reject a drop item/event in html5 drag and drop with Angularjs

I was searching on how I can cancel a drop event based on some logic. I came across this example which shows how to do native drag and drop in html5 using Angularjs http://jsfiddle.net/CW2LC/
On this example can some one please show us how to cancel a drop event. So if I want to prevent the word 'Blue' from being dropped but allow it to be dragged, how can I achieve that?
For complete reference, here is the html, css and javascript code from the example mentioned above
.container {
width: 600px;
border: 1px solid #CCC;
box-shadow: 0 1px 5px #CCC;
border-radius: 5px;
font-family: verdana;
margin: 25px auto;
}
.container header {
background: #f1f1f1;
background-image: -webkit-linear-gradient( top, #f1f1f1, #CCC );
background-image: -ms-linear-gradient( top, #f1f1f1, #CCC );
background-image: -moz-linear-gradient( top, #f1f1f1, #CCC );
background-image: -o-linear-gradient( top, #f1f1f1, #CCC );
box-shadow: 0 1px 2px #888;
padding: 10px;
}
.container h1 {
padding: 0;
margin: 0;
font-size: 16px;
font-weight: normal;
text-shadow: 0 1px 2px white;
color: #888;
text-align: center;
}
.container section {
padding: 10px 30px;
font-size: 12px;
line-height: 175%;
color: #333;
}
<div ng-app="my-app" ng-controller="MainController">
<div class="container">
<header><h1>Draggables</h1></header>
<section>
<div draggable="true" ng-repeat="drag_type in drag_types">{{drag_type.name}}</div>
</section>
</div>
<div class="container">
<header><h1>Drop Schtuff Here</h1></header>
<section droppable="true">
<div><span>You dragged in: </span>
<span ng-repeat="name in items">
<span ng-show="$index != 0">,</span>
{{name}}
</span>
</div>
</section>
</div>
<button ng-click='sayHi()'>Say hi!</button>
<pre>{{items|json}}</pre>
</div>
var module = angular.module('my-app', []);
module.directive('draggable', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element[0].addEventListener('dragstart', scope.handleDragStart, false);
element[0].addEventListener('dragend', scope.handleDragEnd, false);
}
}
});
module.directive('droppable', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element[0].addEventListener('drop', scope.handleDrop, false);
element[0].addEventListener('dragover', scope.handleDragOver, false);
}
}
});
function MainController($scope)
{
$scope.drag_types = [
{name: "Blue"},
{name: "Red"},
{name: "Green"},
];
$scope.items = [];
$scope.handleDragStart = function(e){
this.style.opacity = '0.4';
e.dataTransfer.setData('text/plain', this.innerHTML);
};
$scope.handleDragEnd = function(e){
this.style.opacity = '1.0';
};
$scope.handleDrop = function(e){
e.preventDefault();
e.stopPropagation();
var dataText = e.dataTransfer.getData('text/plain');
$scope.$apply(function() {
$scope.items.push(dataText);
});
console.log($scope.items);
};
$scope.handleDragOver = function (e) {
e.preventDefault(); // Necessary. Allows us to drop.
e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
return false;
};
$scope.sayHi = function() {
alert('Hi!');
};
}
Thanks
Sul
Just adding a simple check in handleDrop() function did the trick. To prevent 'Blue' from being dropped, I added the check as below:
$scope.$apply(function() {
if (dataText != 'Blue') { // prevent the text 'Blue' from being dropped
$scope.items.push(dataText);
}
});
But if you want to prevent drop altogether, just remove the method
$scope.$apply()
~ Wasif