how to add css class to a quill selection? - javascript

How can I add my own style with a class css in quilljs?
I have this following css class
.ql-editor spanblock {
background-color: #F8F8F8;
border: 1px solid #CCC;
line-height: 19px;
padding: 6px 10px;
border-radius: 3px;
margin: 15px 0;
}
and an event targeting this CSS transformation
var toolbarOptions = [
[{ "header": [false, 1, 2, 3, 4, 5, 6] }, "bold", "italic"],
[{ "list": "ordered"}, { "list": "bullet" }, { "indent": "-1"}, { "indent": "+1" }],
["blockquote","code-block", "span-block","link", "hr"]
];
var quill = new Quill("#form_field_" + options.id + " .editor-container > .editor", {
modules: {
toolbar: toolbarOptions
},
theme: "snow"
});
var toolbar = quill.getModule("toolbar");
toolbar.addHandler("span-block", function(){});
var spanBlockButton = document.querySelector(".ql-span-block");
spanBlockButton.addEventListener("click", () => {
let range = quill.getSelection(true);
// what should I add here
}
I cannot find anything in the documentation of quilljs
https://quilljs.com
thank you

Basically you have to extend Parchment blots to have custom styled element in quill.
I went through this tutorial here and here.
Following is the simple html
<link href="http://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<link href="http://cdn.quilljs.com/1.3.6/quill.bubble.css" rel="stylesheet">
<link href="http://cdn.quilljs.com/1.3.6/quill.core.css" rel="stylesheet">
<style>
.ql-spanblock:after {
content: "<spanblock/>";
}
.spanblock {
background-color: #F8F8F8;
border: 1px solid #CCC;
line-height: 19px;
padding: 6px 10px;
border-radius: 3px;
margin: 15px 0;
}
</style>
<div id="editor">
</div>
Here is the actual answer,I have extended blots/inline in following way to wrap selected text into a div with desired class.
<script src="http://cdn.quilljs.com/1.3.6/quill.min.js"></script>
<script type="text/javascript">
let Inline = Quill.import('blots/inline');
class SpanBlock extends Inline{
static create(value){
let node = super.create();
node.setAttribute('class','spanblock');
return node;
}
}
SpanBlock.blotName = 'spanblock';
SpanBlock.tagName = 'div';
Quill.register(SpanBlock);
var toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script':'sub'}, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['clean'], // remove formatting button
['link', 'image', 'video'],
['spanblock']
];
var quill = new Quill('#editor', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
var spanBlockButton = document.querySelector('.ql-spanblock');
//event listener to spanblock button on toolbar
spanBlockButton.addEventListener('click', function() {
var range = quill.getSelection();
if(range){
quill.formatText(range,'spanblock',true);
}else{
}
}
);
</script>
Codepen-demo.

Quite late to the scene, but it seems there's a better way to do this (than the previous answers) through Parchment's Attributor Class, hence this post.
Parchment Class Attributors and the Quill toolbar handlers are in-built ways to let you do exactly that, without having to create a new Blot.
Just register a new Class Attributor for span-block:
Parchment = Quill.import('parchment');
let config = { scope: Parchment.Scope.BLOCK };
let SpanBlockClass = new Parchment.Attributor.Class('span-block', 'span', config);
Quill.register(SpanBlockClass, true);
and attach a handler to format (or removeFormat if already formatted) for the toolbar button (rather than a separate event listener):
// ...
toolbar: {
container: toolbarOptions,
handlers: {
'span-block': function() {
var range = quill.getSelection();
var format = quill.getFormat(range);
if (!format['span-block']) {
quill.format('span-block', 'block');
} else {
quill.removeFormat(range.index, range.index + range.length);
}
}
}
}
// ...
Here's a demo (Or if you prefer, see it on Codepen)
Parchment = Quill.import('parchment');
let config = { scope: Parchment.Scope.BLOCK };
let SpanBlockClass = new Parchment.Attributor.Class('span-block', 'span', config);
Quill.register(SpanBlockClass, true)
var toolbarOptions = [
[{ "header": [false, 1, 2, 3, 4, 5, 6]}, "bold", "italic"],
[{"list": "ordered"}, {"list": "bullet"}, {"indent": "-1"}, {"indent": "+1"}],
["blockquote", "code-block", "span-block", "link"]
];
var icons = Quill.import('ui/icons');
icons['span-block'] = 'sb';
var quill = new Quill("#editor-container", {
modules: {
toolbar: {
container: toolbarOptions,
handlers: {
'span-block': function() {
var range = quill.getSelection();
var format = quill.getFormat(range);
if (!format['span-block']) {
quill.format('span-block', 'block');
} else {
quill.removeFormat(range.index, range.index + range.length);
}
}
}
}
},
theme: "snow"
});
#editor-container {
height: 375px;
}
.ql-editor .span-block {
background-color: #F8F8F8;
border: 1px solid #CCC;
line-height: 19px;
padding: 6px 10px;
border-radius: 3px;
margin: 15px 0;
}
<link href="//cdn.quilljs.com/1.2.4/quill.snow.css" rel="stylesheet" />
<script src="//cdn.quilljs.com/1.2.4/quill.js"></script>
<div id="editor-container"></div>

#moghya's answer has a problem for me: I can't redraw the content from generated html, the element will loose the added class name.
I fixed it by add a formats() method and set the className. See my demo below.
let Block = Quill.import('blots/block');
var icons = Quill.import('ui/icons');
// Lottery tooltip
class LotteryTitle extends Block {
static create() {
let node = super.create();
node.setAttribute('class', this.className);
return node;
}
static formats(domNode) {
return true;
}
}
LotteryTitle.blotName = 'lottery-title';
LotteryTitle.className = "sc-lottery-title"
Quill.register(LotteryTitle);
icons['lottery-title'] = icons.header["2"];

Related

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>

sorting the network graph in a specific type

I have finally made a network graph with highcharts. I would like to sort the graph in a specific shape if possible.
Expected shape:
// Add the nodes option through an event call. We want to start with the parent
// item and apply separate colors to each child element, then the same color to
// grandchildren.
Highcharts.addEvent(
Highcharts.seriesTypes.networkgraph,
'afterSetOptions',
function (e) {
var colors = Highcharts.getOptions().colors,
i = 0,
nodes = {};
e.options.data.forEach(function (link) {
if (link[0] === 'last01') {
nodes['last01'] = {
id: 'last01',
marker: {
radius: 20
}
};
nodes[link[1]] = {
id: link[1],
marker: {
radius: 10
},
color: colors[i++]
};
} else if (nodes[link[0]] && nodes[link[0]].color) {
nodes[link[1]] = {
id: link[1],
color: nodes[link[0]].color
};
}
});
e.options.nodes = Object.keys(nodes).map(function (id) {
return nodes[id];
});
}
);
const options = {
chart: {
type: 'networkgraph',
height: '100%'
},
title: {
text: 'Main diag'
},
subtitle: {
text: 'Router connection'
},
plotOptions: {
networkgraph: {
keys: ['from', 'to'],
layoutAlgorithm: {
enableSimulation: false,
repulsiveForce: function (d, k) {
return k * k * k * k / d;
}
}
}
},
series: [{
dataLabels: {
enabled: true,
linkFormat: ''
},
data: [
['last01','last02'],
['last01','medium201'],
['last01','medium202'],
['last01','medium203'],
['last01','medium204'],
['last01','medium205'],
['last01','medium206'],
['last01','medium207'],
['last01','medium208'],
['last01','medium209'],
['last01','medium210'],
['last01','medium211'],
['last01','medium212'],
['last01','medium213'],
['last01','medium214'],
['last01','medium215'],
['last01','medium216'],
['last02','last01'],
['last02','medium201'],
['last02','medium202'],
['last02','medium203'],
['last02','medium204'],
['last02','medium205'],
['last02','medium206'],
['last02','medium207'],
['last02','medium208'],
['last02','medium209'],
['last02','medium210'],
['last02','medium211'],
['last02','medium212'],
['last02','medium213'],
['last02','medium214'],
['last02','medium215'],
['last02','medium216'],
['medium201','last01'],
['medium201','last02'],
['medium201','medium101'],
['medium201','medium102'],
['medium201','medium103'],
['medium201','medium104'],
['medium202','last01'],
['medium202','last02'],
['medium202','medium101'],
['medium202','medium102'],
['medium202','medium103'],
['medium202','medium104'],
['medium203','last01'],
['medium203','last02'],
['medium203','medium101'],
['medium203','medium102'],
['medium203','medium103'],
['medium203','medium104'],
['medium204','last01'],
['medium204','last02'],
['medium204','medium101'],
['medium204','medium102'],
['medium204','medium103'],
['medium204','medium104'],
['medium205','last01'],
['medium205','last02'],
['medium205','medium101'],
['medium205','medium102'],
['medium205','medium103'],
['medium205','medium104'],
['medium206','last01'],
['medium206','last02'],
['medium206','medium101'],
['medium206','medium102'],
['medium206','medium103'],
['medium206','medium104'],
['medium207','last01'],
['medium207','last02'],
['medium207','medium101'],
['medium207','medium102'],
['medium207','medium103'],
['medium207','medium104'],
['medium208','last01'],
['medium208','last02'],
['medium208','medium101'],
['medium208','medium102'],
['medium208','medium103'],
['medium208','medium104'],
['medium209','last01'],
['medium209','last02'],
['medium209','medium101'],
['medium209','medium102'],
['medium209','medium103'],
['medium209','medium104'],
['medium210','last01'],
['medium210','last02'],
['medium210','medium101'],
['medium210','medium102'],
['medium210','medium103'],
['medium210','medium104'],
['medium211','last01'],
['medium211','last02'],
['medium211','medium101'],
['medium211','medium102'],
['medium211','medium103'],
['medium211','medium104'],
['medium212','last01'],
['medium212','last02'],
['medium212','medium101'],
['medium212','medium102'],
['medium212','medium103'],
['medium212','medium104'],
['medium213','last01'],
['medium213','last02'],
['medium213','medium101'],
['medium213','medium102'],
['medium213','medium103'],
['medium213','medium104'],
['medium214','last01'],
['medium214','last02'],
['medium214','medium101'],
['medium214','medium102'],
['medium214','medium103'],
['medium214','medium104'],
['medium215','last01'],
['medium215','last02'],
['medium215','medium101'],
['medium215','medium102'],
['medium215','medium103'],
['medium215','medium104'],
['medium216','last01'],
['medium216','last02'],
['medium216','medium101'],
['medium216','medium102'],
['medium216','medium103'],
['medium216','medium104'],
['medium101','medium201'],
['medium101','medium202'],
['medium101','medium203'],
['medium101','medium204'],
['medium101','medium205'],
['medium101','medium206'],
['medium101','medium207'],
['medium101','medium208'],
['medium101','medium209'],
['medium101','medium210'],
['medium101','medium211'],
['medium101','medium212'],
['medium101','medium213'],
['medium101','medium214'],
['medium101','medium215'],
['medium101','medium216'],
['medium101','first104'],
['medium101','first103'],
['medium101','first102'],
['medium101','first101'],
['medium102','medium201'],
['medium102','medium202'],
['medium102','medium203'],
['medium102','medium204'],
['medium102','medium205'],
['medium102','medium206'],
['medium102','medium207'],
['medium102','medium208'],
['medium102','medium209'],
['medium102','medium210'],
['medium102','medium211'],
['medium102','medium212'],
['medium102','medium213'],
['medium102','medium214'],
['medium102','medium215'],
['medium102','medium216'],
['medium102','first104'],
['medium102','first103'],
['medium102','first102'],
['medium102','first101'],
['medium103','medium201'],
['medium103','medium202'],
['medium103','medium203'],
['medium103','medium204'],
['medium103','medium205'],
['medium103','medium206'],
['medium103','medium207'],
['medium103','medium208'],
['medium103','medium209'],
['medium103','medium210'],
['medium103','medium211'],
['medium103','medium212'],
['medium103','medium213'],
['medium103','medium214'],
['medium103','medium215'],
['medium103','medium216'],
['medium103','first104'],
['medium103','first103'],
['medium103','first102'],
['medium103','first101'],
['medium104','medium201'],
['medium104','medium202'],
['medium104','medium203'],
['medium104','medium204'],
['medium104','medium205'],
['medium104','medium206'],
['medium104','medium207'],
['medium104','medium208'],
['medium104','medium209'],
['medium104','medium210'],
['medium104','medium211'],
['medium104','medium212'],
['medium104','medium213'],
['medium104','medium214'],
['medium104','medium215'],
['medium104','medium216'],
['medium104','first104'],
['medium104','first103'],
['medium104','first102'],
['medium104','first101'],
['first101','medium104'],
['first101','medium103'],
['first101','medium102'],
['first101','medium101'],
['first102','medium104'],
['first102','medium103'],
['first102','medium102'],
['first102','medium101'],
['first103','medium104'],
['first103','medium103'],
['first103','medium102'],
['first103','medium101'],
['first104','medium104'],
['first104','medium103'],
['first104','medium102'],
['first104','medium101'],
]
}]
};
Highcharts.chart('container', options);
Highcharts.chart('container2', options);
#container {
min-width: 320px;
max-width: 800px;
margin: 0 auto;
}
#container2 {
min-width: 320px;
max-width: 400px;
margin: 0 auto;
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/networkgraph.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div>

How to get a row in Kendo UI TreeList / Grid?

I have a Kendo TreeList where I search for the row where myDataItem is (with help of the uid or value).
When I execute:
$("#treeList tbody").on("click", "tr", function (e) {
var rSelectedRow = $(this);
var getSelect = treeList.select();
console.log("'real' selected row: "+rSelectedRow);
console.log("selected row: "+getSelect);
});
and in another function, where I want to get a row (not the selected one, just a row where myDataItem is):
var grid = treeList.element.find(".k-grid-content");
var myRow = grid.find("tr[data-uid='" + myDataItem.uid + "']"));
//or
// myRow = treeList.content.find("tr").eq(myDataItem.val);
console.log("my row:" + myRow)
I get:
'real' selected row: Object [ tr.k-alt ... ]
selected row: Object { length: 0 ... }
my row: Object { length: 0 ... }
I need the same structure of rSelectedRow for myRow. So how can I get the ,real' tr-element?
UPDATE: I wrote this method to find the row of my new added item:
//I have an id of the item and put it in an invisible row in the treelist.
getRowWhereItem: function (itemId) {
treeList.dataSource.read();
$("#menuItemTree .k-grid-content tr").each(function (i) {
var rowId = $(this).find('td:eq(1)').text();
console.log(itemId);
console.log(rowId);
if (rowId == itemId) {
console.log("found");
console.log(itemId + " " + rowId);
var row = this;
console.log(row);
return row;
}
});
},
The each-iteration reaches all tr's until/except the new added one. Why?
Use the change event instead of binding a click event to the widget's DOM. Note that for change to work, you need to set selectable to true:
<!-- Orginal demo at https://demos.telerik.com/kendo-ui/treelist/index -->
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/treelist/index">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.3.911/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.3.911/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.3.911/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2018.3.911/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.3.911/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div id="treelist"></div>
<script id="photo-template" type="text/x-kendo-template">
<div class='employee-photo'
style='background-image: url(../content/web/treelist/people/#:data.EmployeeID#.jpg);'></div>
<div class='employee-name'>#: FirstName #</div>
</script>
<script>
$(document).ready(function() {
var service = "https://demos.telerik.com/kendo-ui/service";
$("#treelist").kendoTreeList({
dataSource: {
transport: {
read: {
url: service + "/EmployeeDirectory/All",
dataType: "jsonp"
}
},
schema: {
model: {
id: "EmployeeID",
parentId: "ReportsTo",
fields: {
ReportsTo: { field: "ReportsTo", nullable: true },
EmployeeID: { field: "EmployeeId", type: "number" },
Extension: { field: "Extension", type: "number" }
},
expanded: true
}
}
},
height: 540,
filterable: true,
sortable: true,
columns: [
{ field: "FirstName", title: "First Name", width: 280,
template: $("#photo-template").html() },
{ field: "LastName", title: "Last Name", width: 160 },
{ field: "Position" },
{ field: "Phone", width: 200 },
{ field: "Extension", width: 140 },
{ field: "Address" }
],
pageable: {
pageSize: 15,
pageSizes: true
},
/* See here */
selectable: true,
change: function() {
let $selectedItem = this.select(),
dataItem1 = this.dataItem($selectedItem),
uid1 = $selectedItem.data("uid"),
uid2 = dataItem1.uid,
dataItem2 = this.dataSource.getByUid(uid1);
console.log("selected item", $selectedItem);
console.log("dataItem", dataItem1);
console.log("dataItem(alternative way)", dataItem2);
console.log("uid", uid1);
console.log("uid(alternative way)", uid2);
}
});
});
</script>
<style>
.employee-photo {
display: inline-block;
width: 32px;
height: 32px;
border-radius: 50%;
background-size: 32px 35px;
background-position: center center;
vertical-align: middle;
line-height: 32px;
box-shadow: inset 0 0 1px #999, inset 0 0 10px rgba(0,0,0,.2);
margin-left: 5px;
}
.employee-name {
display: inline-block;
vertical-align: middle;
line-height: 32px;
padding-left: 3px;
}
</style>
</div>
</body>
</html>
The part that really matters:
selectable: true,
change: function() {
let $selectedItem = this.select(),
dataItem1 = this.dataItem($selectedItem),
uid1 = $selectedItem.data("uid"),
uid2 = dataItem1.uid,
dataItem2 = this.dataSource.getByUid(uid1);
console.log("selected item", $selectedItem);
console.log("dataItem", dataItem1);
console.log("dataItem(alternative way)", dataItem2);
console.log("uid", uid1);
console.log("uid(alternative way)", uid2);
}
Demo
I didn't find a solution where I can get the tr by datauid.
But in my case, I took the id of the item and put it in an invisible row in the treelist.
Therefore, the method getRowWhereItem(itemId) in the question works well when making it execute after a successfull Ajax Call. With the callback from my ajax call, I load the new item and then the method can find the row. So the issue was that I had to have the uptodate data from my database.
Another issue was with contexts. The method getRowWhereItem(itemId) was a method of a namespace. I tried to call that method outside the namespace and couldn't get its return. Now, I moved the method into the same context where I call it.
(note: My development follows the MVC pattern, Administration is a Controller-class)
$.ajax({
url: General.createMethodUrl("Administration", "Admin", "Add_New"),
data: { parentItemId: parentOfNewId },
type: "POST",
dataType: "json",
success: function (response) {
if (response) {
var addedItem = $.parseJSON(response);
//waiting for callback because otherwise the window opens a few milliseconds before the properties are loaded and newRow cannot be find
tManag.ajaxCallSelectedEntry(addedItem.Id, treeList, function () {
newRow = tManag.getRowWhereItem(addedItem.Id);
});
jQuery(newRow).addClass("k-state-selected")
} else {
tManag.alertDialog(dialog, "Adding New Item Notification", response.responseText);
}
},
error: function (response) {
tManag.alertDialog(dialog, "Adding New Item Error", "Error");
}
});

dynamic datasource in GetOrgChart

I am new to programming I am working on dynamic organization hierarchy chart using GetOrgChart. I want to remove hard code values in java script function and pass my mysql query result data in to javascript function i have get data from database through query and converted it in to json format to display in javascript function.
Here is my code :
<?php
require ('db.php');
$selectSql = "SELECT
emp.id, emp.employee_parent_id, emp.emp_name,
emp.email,hd.desg_name
FROM
hr_employees emp
LEFT JOIN
hr_employees_designations empd ON emp.id = empd.id
LEFT JOIN
hr_designations hd ON empd.id = hd.id";
$result = mysqli_query($conn, $selectSql);
$arrAssociate = [];
while ($value = mysqli_fetch_assoc($result))
{
$json_array = json_encode($value);
echo $json_array;
//echo '<pre>', print_r($value, 1) , '</pre>';
}
?>
<!DOCTYPE html>
<html>
<head>
<title>OrgChart | Create Your Own Theme 3</title>
<style type="text/css">
html, body {
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
overflow: hidden;
}
#people {
width: 100%;
height: 100%;
}
.get-org-chart rect.get-box {
fill: #ffffff;
stroke: #D9D9D9;
}
.get-org-chart .get-text.get-text-0 {
fill: #262626;
}
.get-org-chart .get-text.get-text-1 {
fill: #262626;
}
.get-org-chart .get-text.get-text-2 {
fill: #788687;
}
.get-green.get-org-chart {
background-color: #f2f2f2;
}
.more-info {
fill: #18879B;
}
.btn path {
fill: #F8F8F8;
stroke: #D9D9D9;
}
.btn {
cursor: pointer;
}
.btn circle {
fill: #555555;
}
.btn line {
stroke-width: 3px;
stroke: #ffffff;
}
</style>
</head>
<body>
<div id="people"></div>
<script type="text/javascript">
getOrgChart.themes.myTheme =
{
size: [330, 260],
toolbarHeight: 46,
textPoints: [
{ x: 20, y: 45, width: 300 },
{ x: 120, y: 100, width: 200 },
{ x: 120, y: 125, width: 200 }
],
// textPointsNoImage: [] NOT IMPLEMENTED,
box: '<rect x="0" y="0" height="260" width="330" rx="10" ry="10"
class="get-box"></rect>'
+ '
<g transform="matrix(0.25,0,0,0.25,123,142)"><path
d="M48.014,42.889l-9.553-
4.776C37.56,37.662,37,36.756,37,35.748v-3.381c0.229-0.28,0.47-
0.599,0.719-0.951 c1.239-1.75,2.232-3.698,2.954-
5.799C42.084,24.97,43,23.575,43,22v-4c0-0.963-0.36-1.896-1-
2.625v-5.319 c0.056-0.55,0.276-3.824-2.092-
6.525C37.854,1.188,34.521,0,30,0s-7.854,1.188-
9.908,3.53C17.724,6.231,17.944,9.506,18,10.056 v5.319c-
0.64,0.729-1,1.662-
};
var orgChart = new getOrgChart(document.getElementById("people"), {
theme: "myTheme",
enableEdit: false,
enableDetailsView: false,
primaryFields: ["Title", "Name", "Email", "Image"],
color: "green",
updatedEvent: function () {
init();
},
dataSource: [
// Want Dynamic data here instead of this hard code values
{ id : 1,
parentId : null,
Name : "Jasper Lepardo",
Title : "CEO",
Email : "jasper#example.com",
Image :
"http://www.getorgchart.com/GetOrgChart/getorgchart-
demos/images/f-11.jpg"
},
{ id : 2,
parentId : 1,
Name : "John Smith",
Title : "Front-endDeveloper",
Email : "john#example.com",
Image :
"http://www.getorgchart.com/GetOrgChart/getorgchart
demos/images/f-12.jpg"
},
{ id : 3,
parentId : 1,
Name : "Avaa Field",
Title : "Project Manager",
Email : "ava#example.com",
Image :
"http://www.getorgchart.com/GetOrgChart/getorgchart-demos/images/f-
14.jpg"
},
{ id : 4,
parentId : 1,
Name : "Ava Field",
Title : "Project Manager",
Email : "ava#example.com",
Image :
"http://www.getorgchart.com/GetOrgChart/getorgchart-demos/images/f-
14.jpg" }]
});
function getNodeByClickedBtn(el) {
while (el.parentNode) {
el = el.parentNode;
if (el.getAttribute("data-node-id"))
return el;
}
return null;
}
var init = function () {
var btns = document.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function () {
var nodeElement = getNodeByClickedBtn(this);
var action = this.getAttribute("data-action");
var id = nodeElement.getAttribute("data-node-id");
var node = orgChart.nodes[id];
switch (action) {
case "add":
orgChart.insertNode(id);
break;
case "edit":
orgChart.showEditView(id);
break;
case "preview":
orgChart.showDetailsView(id);
break;
}
});
}
}
init();
</script>
</body>
</html>
Look at this.
Using Laravel (Blade):
let json = JSON.parse('#json($your_array_here)');
No Framework (your case):
let json = JSON.parse('<?=json_encode($your_array_here)?>');
When you have an Array in PHP and need to use it in JS, you have two ways to implement:
Ajax (fetch, axios, xhr2);
Hard coding like you did.
But pay attention to you browser Console (Chrome, Firefox), you will be warned if your JSON is malformatted.
Take a look at JSON.parse and JSON.stringify, it is important to understand this functions too.
And don't forget the ' in the beginning and at the end of the declaration, like I did in the example below.
Hope it helps you.
Have a nice day.

jquery.addClass from JSON isn't work correcly

http://jsfiddle.net/phongphan117/a212my20/
I have a json variable and use jquery.each()to write html tag and create loop for add class in the object. If you look at my code, it's not work correctly. How to fix them?
var db = {
"class" : [
{
"appearance": ["red-bg", "white-text"]
},
{
"appearance": ["yellow-bg", "black-text"]
},
{
"appearance": "red"
},
{
"appearance": "yellow"
},
{
"appearance": ""
}
]
}
$.each(db.class, function (key, data) {
console.log(data);
$('main').append('<div class="box">text</div>');
for (i=0; i<data.appearance.length; i++) {
var classtext = data.appearance[i].toString();
$('.box').addClass(classtext);
}
});
header, main, footer { padding-left: 0px; }
.box { width: 100px; height: 100px; }
.red-bg { background-color: red; }
.yellow-bg { background-color: yellow; }
.white-text { color: white; }
.black-text { color: black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/2.2.1/isotope.pkgd.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/css/materialize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/js/materialize.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
</main>
The problem is, you're passing some array and some strings, so when you have an array, the items are each item inside, ie:
["red-bg", "white-text"]
[0] = "red-bg"
[1] = "white-text"
but when it's a string, each item is a letter, ie:
"red"
[0] = "r"
[1] = "e"
[2] = "d"
so you can just update your class array to:
"class" : [
{
"appearance": ["red-bg", "white-text"]
},
{
"appearance": ["yellow-bg", "black-text"]
},
{
"appearance": ["red"]
},
{
"appearance": ["yellow"]
},
{
"appearance": [""]
}
]
you'll also have to update your each function, since you're adding the classes to the same .box.
$('.box:last-child').addClass(data.appearance[i]);
Now you're adding the data.appearance to your last .box inserted!
and it'll works! see the jsfiddle https://jsfiddle.net/2z95ye56/1/

Categories