I am using a library
called gridstack.js. I have a grid
which looks like below ↓
This is the code I used:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/gridstack.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gridstack.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
<style>
.card-body {
-webkit-box-flex: 1;
-ms-flex: 1 1 auto;
flex: 1 1 auto;
min-height: 1px;
padding: 1.25rem;
}
.newWidget {
background-color: #6cad84 !important;
}
.card {
background: none;
}
#trash {
background-color: #cc6857;
}
.text-white {
color: #fff !important;
}
.text-center {
text-align: center !important;
}
.ui-resizable-se, .ui-resizable-sw {
opacity: 0 !important;
}
.ui-resizable-se {
bottom: -5px !important;
right: -5px !important;
}
.grid-stack-item-content{
overflow:hidden !important
}
</style>
<body>
<div class="container-fluid">
<span id="dashboardName">
<p>My dashboard</p>
</span>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
<!-- gridstack.js elements go here -->
<div class="grid-stack">
<div class="grid-stack-item ui-draggable-handle ui-resizable" data-gs-x="0" data-gs-y="3" data-gs-width="7" data-gs-height="4">
<div class="grid-stack-item-content ui-draggable-handle card-color card-body cardProperty">
<img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80">
</div>
</div>
<div class="grid-stack-item ui-draggable-handle ui-resizable hasPanelHeader " data-gs-x="8" data-gs-y="6" data-gs-width="5" data-gs-height="4">
<div class="grid-stack-item-content ui-draggable-handle panel-warning card-body cardProperty">
<img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80">
</div>
</div>
<div class="grid-stack-item ui-draggable-handle ui-resizable" data-gs-x="0" data-gs-y="6" data-gs-width="4" data-gs-height="4">
<div class="grid-stack-item-content card-body ui-draggable-handle card-color cardProperty">
<img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80">
</div>
</div>
<div class="grid-stack-item ui-draggable-handle ui-resizable hasPanelHeader " data-gs-x="4" data-gs-y="6" data-gs-width="4" data-gs-height="4">
<div class="grid-stack-item-content ui-draggable-handle panel-warning card-body cardProperty">
<img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80">
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// save the size and coordinates of the widgets
function saveData() {
var items = [];
$('.grid-stack-item.ui-draggable').each(function () {
var $this = $(this);
items.push({
x: $this.attr('data-gs-x'),
y: $this.attr('data-gs-y'),
w: $this.attr('data-gs-width'),
h: $this.attr('data-gs-height'),
content: $('.grid-stack-item-content', $this).html()
});
});
// Save data to local storage
localStorage.setItem("grid-layout", JSON.stringify(items))
}
// check for widgets size and coordinates and add to the grid
function getWidgetData() {
let serialization = null;
let grid_stack = $('.grid-stack');
let grid = $('.grid-stack').data('gridstack')
console.log("grid", grid)
if (localStorage.getItem("grid-layout") !== null) {
serialization = JSON.parse(localStorage.getItem("grid-layout"));
_.each(JSON.parse(serialization), function (node) {
grid.addWidget($('<div><div class="grid-stack-item-content"> </div></div>'),
node.x, node.y, node.w, node.h);
});
} else {
console.log("There was no local storage data to read")
}
}
// check for localstorage in the beginning
getWidgetData ()
var simpleGrid = GridStack.init({
alwaysShowResizeHandle: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator
.userAgent),
resizable: {
handles: 'e, se, s, sw, w, n'
},
animate: true,
acceptWidgets: true,
dragIn: '.newWidget', // class that can be dragged from outside
dragInOptions: { revert: 'invalid', scroll: false, appendTo: 'body', helper: 'clone' },
removable: '#trash', // drag-out delete class
removeTimeout: 100,
});
// save the widgets layout on every change
simpleGrid.on('added removed change', function(e, items) {
saveData()
});
</script>
</body>
Now the grid
appears fine and I am able to resize
and drag
the widgets
. Now I want to store
the changes in my browser storage and retrieve it on page load. So as mentioned in the code above, this is what I do to store
the layout
// save the size and coordinates of the widgets
function saveData() {
var items = [];
$('.grid-stack-item.ui-draggable').each(function () {
var $this = $(this);
items.push({
x: $this.attr('data-gs-x'),
y: $this.attr('data-gs-y'),
w: $this.attr('data-gs-width'),
h: $this.attr('data-gs-height'),
content: $('.grid-stack-item-content', $this).html()
});
});
// Save data to local storage
localStorage.setItem("grid-layout", JSON.stringify(items))
}
Now to load
the layout from browser storage, this is what I do (mentioned in the code above)
// check for widgets size and coordinates and add to the grid
function getWidgetData() {
let serialization = null;
let grid_stack = $('.grid-stack');
let grid = $('.grid-stack').data('gridstack')
console.log("grid", grid)
if (localStorage.getItem("grid-layout") !== null) {
serialization = JSON.parse(localStorage.getItem("grid-layout"));
_.each(JSON.parse(serialization), function (node) {
grid.addWidget($('<div><div class="grid-stack-item-content"> </div></div>'),
node.x, node.y, node.w, node.h);
});
} else {
console.log("There was no local storage data to read")
}
}
But for some reason I get this error
index.html:156 Uncaught TypeError: Cannot read property 'addWidget' of undefined
at index.html:156
at r (lodash.min.js:9)
at Function.hf (lodash.min.js:83)
at getWidgetData (index.html:155)
at index.html:168
Turns out this piece of code below
let grid = $('.grid-stack').data('gridstack')
It gives undefined for some reason. Now I just can't figure out why it is undefined. I looked up online for help but didn't find anything useful that solves my problem. I found these two questions on stack overflow
Gridstack undefined when calling $(".grid-stack").data("gridstack") in global context
can't read property addWidget of undefined with JSON and gridstack
But I don't quite understand what they are doing or if it applies in my case. What am I doing wrong?
as mentioned in the 'bug' reported https://github.com/gridstack/gridstack.js/issues/1405, he's mixing old API call of
$(".grid-stack")
which is jquery code based for v0.6 and older and the latest version 2.x which usesGridStack.init()
to init and return a grid pointer.GridStack does not use jquery API since 1.x