jQuery UI Droppable items - javascript

Hello
I have a problem. The problem is, when I move an item to multiple slots it works perfectly.
But when i have two items of the same type, and I put them together it turns into a single item with the value of 2.
But I can't figure out how i could separate that two items into two separate items with the value of one.
if($(this)[0].querySelector('.size').innerText > 1) {
$(this).children().children().html(1);
}
Project: https://codepen.io/KsenonAdv/pen/bGRaRjR

Consider the following example.
$(function() {
function log(string) {
console.log(Date.now(), string);
}
function makeGrid() {
log("Make Grid...");
for (var i = 0; i < 36; i++) {
$("<div>", {
class: "slot"
}).data({
count: 0,
stackable: true
}).appendTo(".slots");
}
log("-* Grid Complete *-");
}
function makeDraggable(target) {
log("Make Drag, Current Class: " + $(target).attr("class"));
console.log(target);
$(target).draggable({
scroll: false,
helper: "clone",
cursor: "pointer",
zIndex: 27,
revert: "invalid"
});
log("After Make Drag, Current Class: " + $(target).attr("class"));
console.log(target);
}
function refreshSlot(target) {
log("Refresh Slot");
$(".size", target).html($(target).data("count"));
}
function addItem(slot, item) {
log("Add Item " + item.id);
$.extend(item, {
stackable: (item.category != 0),
count: (item.count == undefined ? 1 : item.count)
});
slot = $(slot);
var newItem = $("<div>", {
class: "item",
id: item.id,
})
.data(item)
.css("background-image", "url(" + item.img + ")");
newItem.appendTo(slot);
$("<div>", {
class: "size"
}).appendTo(slot);
slot.data({
count: item.count,
stackable: item.stackable
});
log("Item Added - Refreshing");
refreshSlot(slot);
}
function emptySlot(target) {
log("Empty Slot " + $(target).index());
$(target).data({
count: 0,
stackable: true
}).empty();
}
function loadPlayerItems(items) {
log("Loading Player Items...");
$.each(items, function(index, item) {
addItem($(".slots > .slot").eq(index), item);
});
log("-* Loading Complete *-");
}
function isAcceptable(item) {
if ($(this).children().length == 0 || $(".item", this).data("stackable")) {
return true;
}
return false;
}
var pItems = {
playerItems: [{
img: 'https://i.imgur.com/5cjSI9X.png',
name: 'bat',
id: 1,
category: 0
},
{
img: 'https://i.imgur.com/HLQORBk.png',
name: 'axe',
id: 2,
category: 1
},
{
img: 'https://i.imgur.com/HLQORBk.png',
name: 'axe',
id: 3,
category: 1
}
]
};
makeGrid();
loadPlayerItems(pItems.playerItems);
makeDraggable(".item");
$(".slots > .slot").droppable({
accept: isAcceptable,
drop: function(event, ui) {
var origin = ui.draggable.parent();
var target = $(this);
log("Drop Accepted; From: " + origin.index() + ", To: " + target.index());
// Increase the Count
target.data("count", target.data("count") + 1);
// Check for Stack
if (target.children().length == 0) {
addItem(target, ui.draggable.data());
} else {
refreshSlot(target);
}
// Check Orginal Stack
if (origin.data("count") > 1) {
origin.data("count", origin.data("count") - 1);
refreshSlot(origin);
} else {
emptySlot(origin);
}
makeDraggable($(".item", this));
}
});
});
body {
display: flex;
justify-content: space-between;
background: url(http://img.playground.ru/images/5/1/GTA5_2015-05-07_00-53-36-07.png);
}
#inventory {
height: 56.25vw;
background: rgba(0, 0, 0, .5);
}
.list-slots {
position: relative;
background: rgba(0, 0, 0, .7);
max-width: 80%;
}
.slots {
max-width: 87%;
margin: auto;
padding-top: 3.125vw;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.slots .slot {
width: 100px;
height: calc(100px + 1em);
background-color: #ccc;
margin-bottom: 0.781vw;
}
.slots .slot .item {
background-repeat: no-repeat;
width: 100px;
height: 100px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="inventory">
<div class="list-slots">
<div class="slots"></div>
</div>
</div>
As discussed in the comment, this updates the Count of items in the Slot by 1. When an items is dragged out, the count is lowered by 1.
To make things easier, I created a number of functions. You may choose to handle it in another manner if you like.

Related

How to implement a simple box plot chart with javascript and css?

I want to implement a chart like below.
But my problem is collision of the numbers in this chart and I couldn't find a suitable solution for this. For example when two or three values are very close together, the collision happens. (the image below)
<template>
<div style="width: 100%">
<div class="box" style="width: 100%">
<div :style="{ left: `${bound1.spaceLeft}%` }" class="box__q1-line" />
<div :style="{ left: `${bound2.spaceLeft}%` }" class="box__q2-line" />
<div :style="{ width: `${theValue.width}%` }" class="box__value" />
</div>
<div class="box__values-container">
<div
v-for="(item, i) in sorted"
:key="i"
class="box__amount"
:style="{ left: `${item.spaceLeft}%` }"
>
{{ item.realValue }}
</div>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from "#vue/composition-api";
function round(number: number) {
return Math.floor(number * 1000) / 1000;
}
export default defineComponent({
setup(props) {
const bound1 = ref({
realValue: 0,
spaceLeft: 0,
});
const bound2 = ref({
realValue: 0,
spaceLeft: 0,
});
const theValue = ref({
realValue: 0,
spaceLeft: 0,
width: 0,
});
const eachWidth = 6;
type ChartData = { realValue: number; spaceLeft: number };
const sorted = ref<Array<ChartData>>();
function compare(obj1: ChartData, obj2: ChartData) {
if (obj1.spaceLeft < obj2.spaceLeft) return -1;
if (obj1.spaceLeft > obj2.spaceLeft) return 1;
return 0;
}
watch(
props,
() => {
bound1.value.realValue = props.q1!;
bound2.value.realValue = props.q2!;
theValue.value.realValue = props.value!;
bound1.value.spaceLeft = round((props.q1! / props.max!) * 100);
bound2.value.spaceLeft = round((props.q2! / props.max!) * 100);
theValue.value.spaceLeft = round((props.value! / props.max!) * 100);
theValue.value.width = round((props.value! / props.max!) * 100);
sorted.value = [bound1.value, bound2.value, theValue.value].sort(
compare
);
if (
sorted.value[1].spaceLeft + eachWidth >
sorted.value[2].spaceLeft
) {
sorted.value[1].spaceLeft = sorted.value[2].spaceLeft - eachWidth;
}
if (
sorted.value[0].spaceLeft + eachWidth >
sorted.value[1].spaceLeft
) {
sorted.value[0].spaceLeft = sorted.value[1].spaceLeft - eachWidth;
}
if (theValue.value.width < 0) theValue.value.width = 3;
if (bound1.value.spaceLeft < 0) bound1.value.spaceLeft = 3;
if (bound2.value.spaceLeft < 0) bound2.value.spaceLeft = 3;
},
{ deep: true, immediate: true }
);
return {
bound1,
bound2,
theValue,
sorted,
};
},
props: {
q1: {
type: Number,
},
q2: {
type: Number,
},
max: {
type: Number,
},
value: {
type: Number,
},
},
});
</script>
<style>
.box {
width: 100%;
height: 50px;
position: relative;
border-radius: 5px;
border: 2px solid #fff;
background: #b8d0de;
overflow: hidden;
}
.box__q1-line,
.box__q2-line {
position: absolute;
width: 2px;
background: #fff;
height: 100%;
}
.box__value {
background: #3c8dbc;
height: 100%;
}
.box__amount {
position: absolute;
width: 60px;
bottom: -25px;
}
.box__values-container {
position: relative;
}
</style>
I considered two thin divs with absolute position for the two lines and I set the left property of them according to their values and another div for the amount and I set the width of it according to its value.

jquery UI inventory items block after move slot

I have a problem
When i move a item on another slot, the item will block, and can't be moved.
Code:
$(function() {
function log(string) {
console.log(Date.now(), string);
}
function makeGrid() {
log("Make Grid...");
for (var i = 0; i < 36; i++) {
$("<div>", {
class: "slot"
}).data({
count: 0,
stackable: true
}).appendTo(".slots");
}
log("-* Grid Complete *-");
}
function makeDraggable(target) {
log("Make Drag, Current Class: " + $(target).attr("class"));
console.log(target);
$(target).draggable({
scroll: false,
helper: "clone",
cursor: "pointer",
zIndex: 27,
revert: "invalid"
});
log("After Make Drag, Current Class: " + $(target).attr("class"));
console.log(target);
}
function refreshSlot(target) {
log("Refresh Slot");
$(".size", target).html($(target).data("count"));
}
function addItem(slot, item) {
log("Add Item " + item.id);
$.extend(item, {
stackable: (item.category != 0),
count: (item.count == undefined ? 1 : item.count)
});
slot = $(slot);
var newItem = $("<div>", {
class: "item",
id: item.id,
})
.data(item)
.css("background-image", "url(" + item.img + ")");
newItem.appendTo(slot);
$("<div>", {
class: "size"
}).appendTo(slot);
slot.data({
count: item.count,
stackable: item.stackable
});
log("Item Added - Refreshing");
refreshSlot(slot);
}
function emptySlot(target) {
log("Empty Slot " + $(target).index());
$(target).data({
count: 0,
stackable: true
}).empty();
}
function loadPlayerItems(items) {
log("Loading Player Items...");
$.each(items, function(index, item) {
addItem($(".slots > .slot").eq(index), item);
});
log("-* Loading Complete *-");
}
function isAcceptable(item) {
if ($(this).children().length == 0 || $(".item", this).data("stackable")) {
return true;
}
return false;
}
var pItems = {
playerItems: [{
img: 'https://i.imgur.com/5cjSI9X.png',
name: 'bat',
id: 1,
category: 0
},
{
img: 'https://i.imgur.com/HLQORBk.png',
name: 'axe',
id: 2,
category: 1
},
{
img: 'https://i.imgur.com/HLQORBk.png',
name: 'axe',
id: 3,
category: 1
}
]
};
makeGrid();
loadPlayerItems(pItems.playerItems);
makeDraggable(".item");
$(".slots > .slot").droppable({
accept: isAcceptable,
drop: function(event, ui) {
var origin = ui.draggable.parent();
var target = $(this);
log("Drop Accepted; From: " + origin.index() + ", To: " + target.index());
// Increase the Count
target.data("count", target.data("count") + 1);
// Check for Stack
if (target.children().length == 0) {
addItem(target, ui.draggable.data());
} else {
refreshSlot(target);
}
// Check Orginal Stack
if (origin.data("count") > 1) {
origin.data("count", origin.data("count") - 1);
refreshSlot(origin);
} else {
emptySlot(origin);
}
makeDraggable($(".item", this));
}
});
});
body {
display: flex;
justify-content: space-between;
}
#inventory {
width: 100vw;
height: 56.25vw;
background: rgba(0,0,0,.5);
}
.list-slots {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0,0,0,.7);
width: 41.667vw;
height: 41.667vw;
max-width: 80%;
}
.slots {
max-width: 87%;
margin: auto;
padding-top: 3.125vw;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.slots .slot {
width: 100px;
height: calc(100px + 1em);
background-color: #ccc;
margin-bottom: 0.781vw;
}
.slots .slot .item {
background-repeat: no-repeat;
width: 100px;
height: 100px;
}
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="inventory">
<div class="list-slots">
<div class="slots"></div>
</div>
</div>

Update the dom instead of append with jQuery

I have a question about jQuery: I now render content from an array to the dom with:
errors.forEach(error => {
let message = error.message;
let fileName = error.fileName;
$('.errors').append("<li class=\"error-item\">".concat(fileName, " : ").concat(message, "</li><br>"));
});
but I got some actions that update the array where I render the content from, but when I run this function after the update of the array, it appends. I use the .empty() before now but that feels like a hack around but I want it to update
I hope this make sense
What can I do that it updates the dom instead of appending?
I hope someone can help me with this
The jQuery method .html() overwrites the content of the targeted element(s) with a given htmlString. The following demo function logger() will accept an array of objects and render the data in a <ul>.
let failData = [{
DOM: '.fail',
title: 'Errors: ',
header: ['File', 'Message']
},
{
item: '12ffda8a99.log',
message: 'Connection failed'
},
{
item: 'bb6200c400.log',
message: 'Corrupted download'
},
{
item: 'd93ba66731.log',
message: 'Encryption key needed'
},
{
item: '08caa5240f.log',
message: 'Mismatched certification'
},
{
item: 'dead0b8a99.log',
message: 'Insecure protocol'
}
];
let warnData = [{
DOM: '.warn',
title: 'Alerts: ',
header: ['System', 'Message']
},
{
item: 'network',
message: '1GB of data left before limit is exceeded'
},
{
item: 'file',
message: '1GB of storage left before partition is full'
},
{
item: 'power',
message: '5% of battery remains'
}
];
let infoData = [{
DOM: '.info',
title: 'Updates: ',
header: ['Priority', 'Message']
},
{
item: 'critical',
message: 'Anti-virus update required'
},
{
item: 'optional',
message: 'Media encoding update available'
}
];
const logger = array => {
let html = '';
let list;
for (let [index, object] of array.entries()) {
list = $(array[0].DOM);
if (index === 0) {
list.prev('header').html(`<u><b>${object.title}</b><output>${array.length-1}</output></u><u><b>${object.header[0]}</b><b>${object.header[1]}</b></u>`);
} else {
html += `<li><b>${object.item}</b><b>${object.message}</b></li>`;
}
}
list.html(html);
return false;
}
logger(failData);
logger(warnData);
logger(infoData);
header {
margin: 10px 0 -15px;
}
ul {
padding: 5px 0 10px;
border: 3px ridge #777;
overflow-y: hidden;
}
ul,
header {
display: table;
table-layout: fixed;
width: 90%;
}
li,
u {
display: table-row;
}
b {
display: table-cell;
width: 50%;
border-bottom: 1px solid #000;
padding-left:5px
}
output {
display: inline-block;
width: 10ch;
}
<main>
<section class='logs'>
<header></header>
<ul class='fail'></ul>
<header></header>
<ul class='warn'></ul>
<header></header>
<ul class='info'></ul>
</section>
</main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Loop through array data in carousel not working

I'm trying to build a carousel in JS that uses an array to store my data.
I want my box on the left to show the value for "Client" and the box on the right to show the value for "Candidate".
I can't seem to get it working despite what I believe is all correct?
let testimonials = [{
client: "Raphel",
candidate: "male"
},
{
client: "Tom",
candidate: "male"
},
{
client: "Jerry",
candidate: "male"
},
{
client: "Dorry",
candidate: "female"
}
];
var i = 0;
function nextItem() {
i = i + 1;
i = i % testimonials.length;
return testimonials[i].candidate;
}
function prevItem() {
if (i === 0) {
i = testimonials.length;
}
i = i - 1;
return testimonials[i].client;
}
window.addEventListener('load', function() {
$('.client-box').html(testimonials[i].client);
$('.candidate-box').html(testimonials[i].candidate);
$('.left-btn').on('click', function(e) {
$('.client-box').html(prevItem());
$('.candidate-box').html(prevItem());
});
$('.right-btn').on('click', function(e) {
$('.client-box').html(nextItem());
$('.candidate-box').html(nextItem());
});
});
https://jsfiddle.net/cL5mok3f/
Fixing the code:
let testimonials = [{
client: "Raphel",
candidate: "male"
},
{
client: "Tom",
candidate: "male"
},
{
client: "Jerry",
candidate: "male"
},
{
client: "Dorry",
candidate: "female"
}
];
var i = 0;
function nextItem() {
i = i + 1;
i = i % testimonials.length;
return testimonials[i];
}
function prevItem() {
if (i === 0) {
i = testimonials.length;
}
i = i - 1;
return testimonials[i];
}
window.addEventListener('load', function() {
$('.client-box').html(testimonials[i].client);
$('.candidate-box').html(testimonials[i].candidate);
$('.left-btn').on('click', function(e) {
var prev = prevItem();
$('.client-box').html(prev.client);
$('.candidate-box').html(prev.candidate);
});
$('.right-btn').on('click', function(e) {
var next = nextItem();
$('.client-box').html(next.client);
$('.candidate-box').html(next.candidate);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="client-box"></div>
<div class="candidate-box"></div>
<input type="button" class="left-btn" value="Prev" />
<input type="button" class="right-btn" value="Next" />
To achieve expected result, use below option
Issue: PrevItem and nextItem methods are called twice on clicking left and right which creates inconsistent carousel
Code sample
let testimonials = [
{client: "Raphel", candidate: "male"},
{client: "Tom", candidate: "male"},
{client: "Jerry", candidate: "male"},
{client: "Dorry", candidate: "female"}
];
var i = 0;
$('.client-box').text(testimonials[0].client);
$('.candidate-box').text(testimonials[1].candidate);
function nextItem() {
i = i + 1;
if (i === testimonials.length) {
i = i % testimonials.length;
}
return testimonials[i];
}
function prevItem() {
if (i === 0) {
i = testimonials.length;
}
i = i - 1;
console.log("prev", i)
return testimonials[i];
}
$('.left-btn').on('click', function(e){
let val = prevItem()
$('.client-box').text(val.client);
$('.candidate-box').text(val.candidate);
});
$('.right-btn').on('click', function(e){
let val = nextItem()
$('.client-box').text(val.client);
$('.candidate-box').text(val.candidate);
});
.testimonial-carousel {
position: relative;
width: 1000px;
}
.testimonial-carousel::after {
content: "";
display: block;
clear: both;
}
.testimonial-carousel .testimonial-box {
width: 500px;
height: 100px;
float: left;
background: #999999;
}
.testimonial-carousel .testimonial-box.candidate-box {
background: white;
margin-top: 2rem;
box-shadow: 0 0 1rem rgba(0, 0, 0, 0.2);
}
.testimonial-carousel .buttons {
position: absolute;
bottom: -60px;
right: 20px;
}
.testimonial-carousel .buttons::after {
content: "";
display: block;
clear: both;
}
.testimonial-carousel .buttons .btn {
background: black;
width: 60px;
height: 60px;
float: left;
margin-right: 5px;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="testimonial-carousel">
<div class="testimonial-box client-box"></div>
<div class="testimonial-box candidate-box"></div>
<div class="buttons">
LEFT
RIGHT
</div>
</div>
codepen - https://codepen.io/nagasai/pen/wLKoVv

Jquery, change all json entries to collapsed state

I'm still new to jquery and javascript as a whole.
I am trying to get all the entries from this collapsible json parser to be collapsed on webpage load.
I tried fiddling around with the first function but that doesn't seem to work.
Any help would be appreciated.
Here is the JS code:
/**
* json-view - jQuery collapsible JSON plugin
* #version v1.0.0
* #link http://github.com/bazh/jquery.json-view
* #license MIT
*/
;(function ($) {
'use strict';
var collapser = function(collapsed) {
var item = $('<span />', {
'class': 'collapser',
on: {
click: function() {
var $this = $(this);
$this.toggleClass('collapsed');
var block = $this.parent().children('.block');
var ul = block.children('ul');
if ($this.hasClass('collapsed')) {
ul.hide();
block.children('.dots, .comments').show();
} else {
ul.show();
block.children('.dots, .comments').hide();
}
}
}
});
if (collapsed) {
item.addClass('collapsed');
}
return item;
};
var formatter = function(json, opts) {
var options = $.extend({}, {
nl2br: true
}, opts);
var htmlEncode = function(html) {
if (!html.toString()) {
return '';
}
return html.toString().replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
};
var span = function(val, cls) {
return $('<span />', {
'class': cls,
html: htmlEncode(val)
});
};
var genBlock = function(val, level) {
switch($.type(val)) {
case 'object':
if (!level) {
level = 0;
}
var output = $('<span />', {
'class': 'block'
});
var cnt = Object.keys(val).length;
if (!cnt) {
return output
.append(span('{', 'b'))
.append(' ')
.append(span('}', 'b'));
}
output.append(span('{', 'b'));
var items = $('<ul />', {
'class': 'obj collapsible level' + level
});
$.each(val, function(key, data) {
cnt--;
var item = $('<li />')
.append(span('"', 'q'))
.append(key)
.append(span('"', 'q'))
.append(': ')
.append(genBlock(data, level + 1));
if (['object', 'array'].indexOf($.type(data)) !== -1 && !$.isEmptyObject(data)) {
item.prepend(collapser());
}
if (cnt > 0) {
item.append(',');
}
items.append(item);
});
output.append(items);
output.append(span('...', 'dots'));
output.append(span('}', 'b'));
if (Object.keys(val).length === 1) {
output.append(span('// 1 item', 'comments'));
} else {
output.append(span('// ' + Object.keys(val).length + ' items', 'comments'));
}
return output;
case 'array':
if (!level) {
level = 0;
}
cnt = val.length;
output = $('<span />', {
'class': 'block'
});
if (!cnt) {
return output
.append(span('[', 'b'))
.append(' ')
.append(span(']', 'b'));
}
output.append(span('[', 'b'));
items = $('<ul />', {
'class': 'obj collapsible level' + level
});
$.each(val, function(key, data) {
cnt--;
var item = $('<li />')
.append(genBlock(data, level + 1));
if (['object', 'array'].indexOf($.type(data)) !== -1 && !$.isEmptyObject(data)) {
item.prepend(collapser());
}
if (cnt > 0) {
item.append(',');
}
items.append(item);
});
output.append(items);
output.append(span('...', 'dots'));
output.append(span(']', 'b'));
if (val.length === 1) {
output.append(span('// 1 item', 'comments'));
} else {
output.append(span('// ' + val.length + ' items', 'comments'));
}
return output;
case 'string':
val = htmlEncode(val);
if (/^(http|https|file):\/\/[^\s]+$/i.test(val)) {
return $('<span />')
.append(span('"', 'q'))
.append($('<a />', {
href: val,
text: val
}))
.append(span('"', 'q'));
}
if (options.nl2br) {
var pattern = /\n/g;
if (pattern.test(val)) {
val = (val + '').replace(pattern, '<br />');
}
}
var text = $('<span />', { 'class': 'str' })
.html(val);
return $('<span />')
.append(span('"', 'q'))
.append(text)
.append(span('"', 'q'));
case 'number':
return span(val.toString(), 'num');
case 'undefined':
return span('undefined', 'undef');
case 'null':
return span('null', 'null');
case 'boolean':
return span(val ? 'true' : 'false', 'bool');
}
};
return genBlock(json);
};
return $.fn.jsonView = function(json, options) {
var $this = $(this);
options = $.extend({}, {
nl2br: true
}, options);
if (typeof json === 'string') {
try {
json = JSON.parse(json);
} catch (err) {
}
}
$this.append($('<div />', {
class: 'json-view'
}).append(formatter(json, options)));
return $this;
};
})(jQuery);
/**
* json-view - jQuery collapsible JSON plugin
* #version v1.0.0
* #link http://github.com/bazh/jquery.json-view
* #license MIT
*/
.json-view {
position: relative;
}
.json-view .collapser {
width: 20px;
height: 18px;
display: block;
position: absolute;
left: -1.7em;
top: -0.2em;
z-index: 5;
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAD1JREFUeNpiYGBgOADE%2F3Hgw0DM4IRHgSsDFOzFInmMAQnY49ONzZRjDFiADT7dMLALiE8y4AGW6LoBAgwAuIkf%2F%2FB7O9sAAAAASUVORK5CYII%3D");
background-repeat: no-repeat;
background-position: center center;
opacity: 0.5;
cursor: pointer;
}
.json-view .collapsed {
-ms-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-khtml-transform: rotate(-90deg);
-webkit-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
transform: rotate(-90deg);
}
.json-view .bl {
display: block;
padding-left: 20px;
margin-left: -20px;
position: relative;
}
.json-view {
font-family: monospace;
}
.json-view ul {
list-style-type: none;
padding-left: 2em;
border-left: 1px dotted;
margin: 0.3em;
}
.json-view ul li {
position: relative;
}
.json-view .dots,
.json-view .comments {
display: none;
-moz-user-select: none;
-ms-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
user-select: none;
}
.json-view .comments {
padding-left: 0.8em;
font-style: italic;
color: #888;
}
.json-view .null,
.json-view .num,
.json-view .bool,
.json-view .undef {
font-weight: bold;
color: #1A01CC;
}
.json-view .str {
color: #800;
}
<!DOCTYPE html>
<html>
<head>
<title>jQuery JSON View demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="../dist/jquery.json-view.js"></script>
<link href="../dist/jquery.json-view.css" rel="stylesheet">
</head>
<body>
<div id="element"></div>
<script>
$(function() {
$('#element').jsonView(JSON.stringify({
demo: 'string',
notSet: null,
zero: 0,
'true': true,
'false': false,
undef: undefined,
number: 5,
arr: [1, 2, 3, 'string', null, { a: 1 }, [2, 3, 4]],
obj: {
string: 'test string',
arr: [1, 2, 3, 4, 'myString', ['wow', [9,8,7,6]]],
obj1: {
hello: 'world',
nice: {
to: 'meet you',
'finally': [1, 2, 3, 4, 5]
}
}
}
}));
});
</script>
</body>
</html>
Please acknowledge that all three code files are licensed under MIT.
Each <li> has a span with class collapser , using the inspect element, When you collapse the node, it adds the class collapsed in that element.
So technically, you can try to have this jQuery code:
$(".collapser").addClass("collapsed");
after loading the JSON collapser.

Categories