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

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

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 does this CSS position transition slightly overshoot the desired end position, based on a DOMRect?

I am attempting a visual effect of dislocating a div from one container to another, both also divs in this case. To do this, I first obtain the DOMRect from the initial position. Then, I briefly add a clone of the element to its destination and obtain the DOMRect of that, promptly removing the clone. I then remove the element from its source, and append it as a child of an outmost div, with absolute positioning, and "left" and "top" properties in px according to the obtained values from the DOMRect. window.scrollX and window.scrollY are added, in order to get the absolute position. Once appended, I add a CSS class to the element which states that it transitions on all properties. Following this, I change the element's "left" and "top" properties to match those of the destination's DOMRect. Once the transition is finished, I append the element as a child of the destination container div. All works nearly as expected, the apparent defect being that the element begins its transition slightly off of its initial position, and ends similarly. I will add my used code below.
index.ts:
type PlacementStage = 'source-removal' | 'medium-placement' | 'medium-removal' | 'destination-placement';
type Tuple<V, N extends number, T extends V[] = []> =
N extends T['length'] ?
T :
Tuple<V, N, [...T, V]>;
const defaultPlacementStageSequence: Tuple<PlacementStage, 4> = [
'source-removal',
'medium-placement',
'medium-removal',
'destination-placement'
];
type SurjectivePlacementStageMapping<T> = {
[V in PlacementStage]: T
};
interface DefaultPlacementStageInstructionsParameters {
element: HTMLElement,
source: HTMLElement,
medium: HTMLElement,
destination: HTMLElement
};
function makeDefaultPlacementStageInstructions(
{
element,
source,
medium,
destination
}: DefaultPlacementStageInstructionsParameters
): SurjectivePlacementStageMapping<() => void> {
const {
initial: initialBoundingClientRect,
final: finalBoundingClientRect
} = getInitialAndFinalBoundingClientRects({ element, destination });
return {
'source-removal': () => {
source.removeChild(element);
},
'medium-placement': () => {
element.classList.add('moves-smoothly');
medium.appendChild(element);
console.log({ initialBoundingClientRect, finalBoundingClientRect });
element.style.top = `${initialBoundingClientRect.top + window.scrollY}px`;
element.style.left = `${initialBoundingClientRect.left + window.scrollX}px`;
element.style.top = `${finalBoundingClientRect.top + window.scrollY}px`;
element.style.left = `${finalBoundingClientRect.left + window.scrollX}px`;
},
'medium-removal': () => {
element.classList.remove('moves-smoothly');
medium.removeChild(element);
},
'destination-placement': () => {
destination.appendChild(element);
}
};
}
function getInitialAndFinalBoundingClientRects(
{
element,
destination
}: {
element: HTMLElement,
destination: HTMLElement
}
): { initial: DOMRect, final: DOMRect } {
const initialBoundingClientRect = element.getBoundingClientRect();
const elementCopy = element.cloneNode() as HTMLElement;
destination.appendChild(elementCopy);
const finalBoundingClientRect = elementCopy.getBoundingClientRect();
destination.removeChild(elementCopy);
return {
initial: initialBoundingClientRect,
final: finalBoundingClientRect
};
}
function moveElementInstantly(parameters: DefaultPlacementStageInstructionsParameters): void {
const instructions = makeDefaultPlacementStageInstructions(parameters);
defaultPlacementStageSequence.forEach(stage => instructions[stage]());
}
const defaultPlacementStageDelays: SurjectivePlacementStageMapping<number> = {
'source-removal': 0,
'medium-placement': 0,
'medium-removal': 1000,
'destination-placement': 1000
};
function moveElementWithDelay(parameters: DefaultPlacementStageInstructionsParameters): void {
const instructions = makeDefaultPlacementStageInstructions(parameters);
defaultPlacementStageSequence.forEach(stage => {
setTimeout(instructions[stage], defaultPlacementStageDelays[stage])
});
}
document.querySelectorAll('.small-box').forEach((nonHtmlElement) => {
const element = nonHtmlElement as HTMLElement;
element.addEventListener(
'click',
() => {
moveElementWithDelay({
element,
source: document.querySelector('#left-panel') as HTMLElement,
medium: document.querySelector('#main-content') as HTMLElement,
destination: document.querySelector('#main-display-area') as HTMLElement
});
}
);
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Experiment</title>
</head>
<body>
<div id="root-div">
<div id="main-content">
<div id="left-panel" class="panel">
<div class="small-box" style="background-color: red;">
</div>
<div class="small-box" style="background-color: blue;">
</div>
</div>
<div id="main-display-area" class="panel">
</div>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
style.css:
body {
margin: 0;
}
#main-content {
width: 100vw;
margin: 0;
}
#main-content {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: row;
}
.panel {
display: flex;
flex-direction: column;
width: 50%;
justify-content: center;
align-items: center;
}
.small-box {
width: 50px;
height: 50px;
margin: 10px;
}
.moves-smoothly {
position: absolute;
transition: all 1s ease-in-out;
}
#left-panel {
background-color: lightblue;
}
#main-display-area {
background-color: lightgreen;
}
height: 100vh;
display: flex;
flex-direction: row;
}
.panel {
display: flex;
flex-direction: column;
width: 50%;
justify-content: center;
align-items: center;
}
.small-box {
width: 50px;
height: 50px;
margin: 10px;
}
.moves-smoothly {
position: absolute;
transition: all 1s ease-in-out;
}
#left-panel {
background-color: lightblue;
}
#main-display-area {
background-color: lightgreen;
}

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

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>

Replace cell's editor of ag-grid with tinymce editor

How can we add tinymce editor in the place of editor present in the cell of ag-grid?
In order to customize ag-grid's cell's you need to create a custom Cell Renderer component.
You can pretty much put anything you want in that custom component, including tinyMCE.
More info: https://www.ag-grid.com/javascript-grid-cell-rendering-components/
Please see Cell Renderer
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script>var __basePath = './';</script>
<style media="only screen">
html, body {
height: 100%;
width: 100%;
margin: 0;
box-sizing: border-box;
-webkit-overflow-scrolling: touch;
}
html {
position: absolute;
top: 0;
left: 0;
padding: 0;
overflow: auto;
}
body {
padding: 1rem;
overflow: auto;
}
</style>
<script src="https://unpkg.com/#ag-grid-community/all-modules#24.1.0/dist/ag-grid-community.min.js"></script>
</head>
<body>
<div id="myGrid" style="height: 100%;width: 100%" class="ag-theme-alpine"></div>
<script src="main.js"></script>
</body>
</html>
main.js
var columnDefs = [
{ field: 'athlete' },
{ field: 'country' },
{ field: 'year', width: 100 },
{ field: 'gold', width: 100, cellRenderer: 'medalCellRenderer' },
{ field: 'silver', width: 100, cellRenderer: 'medalCellRenderer' },
{ field: 'bronze', width: 100, cellRenderer: 'medalCellRenderer' },
{ field: 'total', width: 100 }
];
var gridOptions = {
columnDefs: columnDefs,
components: {
'medalCellRenderer': MedalCellRenderer
},
defaultColDef: {
editable: true,
sortable: true,
flex: 1,
minWidth: 100,
filter: true,
resizable: true
}
};
// cell renderer class
function MedalCellRenderer() {
}
// init method gets the details of the cell to be renderer
MedalCellRenderer.prototype.init = function(params) {
this.eGui = document.createElement('span');
var text = '';
// one star for each medal
for (var i = 0; i < params.value; i++) {
text += '#';
}
this.eGui.innerHTML = text;
};
MedalCellRenderer.prototype.getGui = function() {
return this.eGui;
};
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
agGrid.simpleHttpRequest({ url: 'https://raw.githubusercontent.com/ag-grid/ag-grid/master/grid-packages/ag-grid-docs/src/olympicWinnersSmall.json' })
.then(function(data) {
gridOptions.api.setRowData(data);
});
});

the table border-bottom disappear?

I try to implement a table with large size of data. then due to the performance issue, I just want to render the data in the body window.
But the new render element border disappear.
HTML:
<script src="//unpkg.com/vue#2.5.15/dist/vue.js"></script>
<script type="text/x-template" id="list-template">
<div class='table-body' ref="body" #scroll="handleScroll">
<div class="list-view">
<div
class="list-view-phantom"
:style="{
height: contentHeight
}">
</div>
<div class="list-view-colgroup">
<div class="list-view-item-col-g" v-for='count in 5'>
</div>
</div>
<div
ref="content"
class="list-view-content">
<ul
class="list-view-item"
:style="{
height: itemHeight + 'px'
}"
v-for="item in visibleData" :key='item.value'>
<li class="list-view-item-col" v-for='count in 5'>
{{item.value+count}}
</li>
</ul>
</div>
</div>
</div>
</script>
<div id="app">
<template>
<list-view :data="data"></list-view>
</template>
</div>
JS:
const ListView = {
name: 'ListView',
template: '#list-template',
props: {
data: {
type: Array,
required: true
},
itemHeight: {
type: Number,
default: 30
}
},
computed: {
contentHeight() {
return this.data.length * this.itemHeight + 'px';
}
},
mounted() {
this.updateVisibleData();
},
data() {
return {
visibleData: []
};
},
methods: {
updateVisibleData(scrollTop) {
scrollTop = scrollTop || 0;
const visibleCount = Math.ceil(this.$el.clientHeight / this.itemHeight);
const start = Math.floor(scrollTop / this.itemHeight);
const end = start + visibleCount;
this.visibleData = this.data.slice(start, end);
this.$refs.content.style.transform = `translate3d(0, ${ start * this.itemHeight }px, 0)`;
},
handleScroll() {
const scrollTop = this.$refs.body.scrollTop;
this.updateVisibleData(scrollTop);
}
}
};
new Vue({
components: {
ListView
},
data() {
const data = [];
for (let i = 0; i < 1000; i++) {
data.push({ value: i });
}
return {
data
};
}
}).$mount('#app')
code example:
https://jsfiddle.net/441701328/hq1ej6bx/6/
you can see only the data render in the first time can have border.
could anyone help?
thanks all!!!
table-row-group does not work with divs you can change the whole layout and use tables or instead you can do it like this.
.list-view-item {
padding: 5px;
color: #666;
display: table;
line-height: 30px;
box-sizing: border-box;
border-bottom: 1px solid red;
min-width: 100vw;
}
.list-view-item-col {
display: table-cell;
min-width: 50px;
}
jsfiddle for table-row-group
Hope it helps.
Use display :flex for list-view-item class, Try with following code.Hope it will work fine for you.
.list-view-item {
padding: 5px;
color: #666;
display: flex;
flex-basis: 100%;
flex-direction: row;
line-height: 30px;
box-sizing: border-box;
border-bottom: 1px solid red;
}
Try with this CSS. I hope it will works for you.
.list-view-item {
padding: 5px;
color: #666;
display:table;
line-height: 30px;
box-sizing: border-box;
border-bottom: 1px solid green;
}
I try to change the js code :
this.$refs.content.style.transform = `translateY(0, ${ start * this.itemHeight }px, 0)`;
to :
this.$refs.content.style.transform = `translateY(${ start * this.itemHeight }px)`;
and add a css to div class is list-view:
transform:translateY(0)px;
then the border showed.
don't understand why this action work!
.list-view-item {
padding: 5px;
color: #666;
display: flex;
flex-basis: 100%;
flex-direction: row;
line-height: 30px;
box-sizing: border-box;
border-bottom: 1px solid red;
}