jQuery SimpleTree: Add a node programatically - javascript

I'm trying to add a new node to an jQuery SimpleTree, but all I seem to be able to get is "sTC.addNode is not a function"...
var simpleTreeCollection = $('.simpleTree').simpleTree({
animate:true,
drag:false,
autoclose: false,
afterClick:function(node){},
afterDblClick:function(node){},
beforeMove:function (destination, source, pos){},
afterMove:function(destination, source, pos){},
afterAjax:function() {},
afterContextMenu:function(node){}
});
simpleTreeCollection.addNode('test', 'test');
Any suggestions what I might be doing wrong? Is there even the possibility to add a node?

Maybe take a look at jsTree

hmm tricky one this and I have to say I dont like the plugin as it uses numerics as id's and w3c states "The attribute's value must begin with a letter in the range A-Z or a-z and may be followed by letters......."
However to get you working u need to select one of the nodes first in order to add to it like this
//Select first child node in tree
$('#2').click();
//Add new node to selected node
simpleTreeCollection.get(0).addNode(1,'A New Node')

FYI the above code works in the firebug console on their demo page. On your tree ake sure you use a correct selector to highlight the node

I have solved it by editing the addNode funcion. I commented the temp_node.remove(); and added dragNode_destination.after(dragNode_source);
Just like that:
TREE.addNode = function(id, text, callback)
{
var temp_node = $('<li><ul><li id="'+id+'"><span>'+text+'</span></li></ul></li>');
TREE.setTreeNodes(temp_node);
dragNode_destination = TREE.getSelected();
dragNode_source = $('.doc-last',temp_node);
TREE.moveNodeToFolder(dragNode_destination);
// temp_node.remove();
dragNode_destination.after(dragNode_source);
if(typeof(callback) == 'function')
{
callback(dragNode_destination, dragNode_source);
}
};

Related

Get the className of the tag within a Range object

I have two custom context menu (one was written by my, the other one was already there). Mine show up only when a word is underlined because he is poorly written and the other one show up on table so the user can choose to add another line or to delete a line from this table.
The trouble I got is that the one working on table is blocking mine to execute if there is an error in the table and you want to correct it.
For this contextMenu, they write it so they got a range object from the place where the right click is done.
document.oncontextmenu = elementSelect;
function elementSelect(){
Rng = document.selection.createRange();
}
I've tried to get the className of the tag inside the range object so if it match the class from my error tag (a span with class="error"), I do a simple return in the contextMenu for the table so it does not trigger.
var rngClassName = Rng(0).getAttribute("class").value;
alert("class =>" + rngClassName);
if(rngClassName == "error")
{
return;
}
The Rng(0) is used after several time to retrieve somme attribute and work fine for them. But It seems that it does not work to get the class value, no value is return, the script stop execution at line var rngClassName = Rng(0).getAttribute("class").value; and no error is returned from the debugging (F12 in IE).
It is my first time working with Range object so I think I am missing something but don't know what.
Spec : IE5, Vanilla Javascript.
Try using element.classList .
with following methods : classList.add() , classList.remove() , classList.contains()
edit: i see your comment now, and below won't work in IE5...
But if I understand your question correctly, you want to check the class of an element whitin the selection? I don't have IE5 so I checked it in 11 and Chrome. You could try something like this:
var selection = document.getSelection();
var selRange = selection.getRangeAt(0);
var parentNode = selRange.startContainer.parentNode;
var hasError = parentNode.classList.contains('error');
Demo: https://jsfiddle.net/spdwn7bo/1/ (select a text within 2 seconds :))

How to remove the specific text node from the DOM

I'm trying to remove the text node "one".
$targetDiv is jQuery object
$targetDiv[0].outerHTML
<div><div>one<font face="Impact" size="4">www</font></div></div>
$targetDiv[0].innerHTML
<div>one<font face="Impact" size="4">www</font></div>
I can remove the other text node "www" like below:
$targetDiv.find("font").each(function ()
{
if (this.firstChild.nodeType === 3)
{
this.firstChild.data = "";
}
});
But having tough time removing the "one" part.
$targetDiv[0].firstChild
<div>
$targetDiv[0].firstChild.data
undefined
$targetDiv[0].firstChild.innerText
undefined
$targetDiv[0].firstChild.innerHTML
"one<font face="Impact" size="4">www</font>"
$targetDiv[0].firstChild.innerText
undefined
$targetDiv[0].firstChild.textContent
"onewww"
It's not very clear what context this is in, or what $targetDiv is, but based on the results you're getting we can assume you are using Firefox, and that $targetDiv is the first div, and that this should work
$($targetDiv.find("div").get(0).firstChild).remove();
FIDDLE
You can use the native .removeChild method to remove the first text node:
var div=targetDiv[0].firstChild;
div.removeChild(div.firstChild);
This method is invoked from the parent of the node that you wish to remove, and receives the node to remove as its argument.
Modern browsers let you simply call .remove() on the node itself.
target[0].firstChild.firstChild.remove();
Your .each() loop was close. In that particular case, since the one text node is the only sibling that is a text node, you'd just iterate the children under target since there's only one.
$targetDiv.children("div").each(function ()
{
if (this.firstChild.nodeType === 3)
{
this.firstChild.data = "";
}
});
Though targeting it directly instead of a loop makes more sense in this case.
Try,
$($targetDiv.children('div').contents()[0]).remove();
DEMO

How to access first or specific object from json data

I have a json file with below mentioned format
mydata.json
{
"nodes":{
"Aidan":{"color":"green", "shape":"dot", "alpha":1, "id" : "aidan"},
"Sofia":{"color":"green", "shape":"dot", "alpha":1},
"Liam":{"color":"GoldenRod", "shape":"dot", "alpha":1}
},
"edges":{
"Quinn":{
"Liam":{"length":2.5,"weight":2},
"Audrey":{"length":2.5,"weight":2},
"Noah":{"length":2.5,"weight":2},
"Claire":{"length":2.5,"weight":2}
},
"Liam":{
"Sofia":{"length":2.5,"weight":2},
"Ethan":{"length":2.5,"weight":2},
"Amelia":{"length":2.5,"weight":2}
}
}
}
I will be reading above file data using jquery as mentioned below
var data = $.getJSON("data/mydata.json",function(data){
var nodes = data.nodes;
var edges = data.edges;
//i want to access first element or between element.
//like var edge = edges.get(0) or nodes.get("aidan")
})
I want to access first element or between element with the index or by name property of object. like var edge = edges.get(0) or nodes.get("aidan").
Thanks
There are several ways of doing it
Object.keys(nodes)[0]; //retrieve the first key
edges['Quinn'];
edges.Quinn
A little warning on the first one, Object in JS are unordered so it may break, thus browser tends to keep the insertion order.
hope it helped
Try this code
nodes['aidan']
edges['Quinn']
Either the before mentioned code
nodes['aidan']
or
nodes.aidan
should work equally fine.
Prepared a fiddle for you. You can check there.

jquery offset method doesn't always work / exist

Good morning and happy new year everyone!
I've run into a snag on something and need to figure out a solution or an alternative, and I don't know how to approach this. I actually hope it's something easy; meaning one of you all have dealt with this already.
The problem is that I'm doing rollovers that contain information. They're divs that get moved to the absolute location. Now I've tried this with jquery 1.6 - 1.9.1. Of course this has to work in multiple browsers.
What needs to happen is on rollover show a div, and when you rollout of that div, make it hide.
...
// .columnItem is class level and works
$(".columnItem").mouseleave(function() {
$(this).css("display", "none");
});
...
$(".column").mouseenter(function() {
var currentItem = $(this)[0]; // this is where the problem is
// hide all .columnItems
$(".columnItem").css("display", "none");
// i get this error: Object #<HTMLDivElement> has no method 'offset' (viewing in chrome console)
var offsetTop = currentItem.offset().top;
var columnInfoPanel = $("#column" + currentItem.innerText);
});
So the immediate thought of some would be don't use $(this)[0]. Instead, I should use $(this), and you are correct! Where the other problem comes into play is by removing the array index, currentItem.innerText is now undefined.
The only thing I can think of is I'll have to mix both, but it seems like there should be a way to use the selector and get both options.
What have you all done?
Thanks,
Kelly
Replace:
var currentItem = $(this)[0];
With:
var currentItem = $(this).eq(0);
This creates a new jQuery object containing only the first element, so offset will work.
Then you can use either currentItem[0].innerText or currentItem.text(), whichever you prefer.
Skip the [0] at the beginning as you are saying.
But then change the last line to:
var columnInfoPanel = $("#column" + currentItem[0].innerText);
De-referencing the jQuery selector gives you the DOM-object.
If you want to stick to pure jQuery, the .text() / .html() methods will give you the same functionality.

How do I get the id of the selected node in jsTree?

How can I get the id of the selected node in a jsTree?
function createNewNode() {
alert('test');
var tree = $.tree.reference("#basic_html");
selectedNodeId = xxxxxxxxx; //insert instruction to get id here
tree.create({ data : "New Node Name" }, selectedNodeId);
}
Unable to get harpo's solution to work, and unwilling to use Olivier's solution as it uses internal jsTree functions, I came up with a different approach.
$('#tree').jstree('get_selected').attr('id')
It's that simple. The get_selected function returns an array of selected list items. If you do .attr on that array, jQuery will look at the first item in the list. If you need IDs of multiple selections, then treat it as an array instead.
Nodes in jsTree are essentially wrapped list items. This will get you a reference to the first one.
var n = $.tree.focused().get_node('li:eq(0)')
You can replace $.tree.focused() if you have a reference to the tree.
To get the id, take the first matched element
if (n.length)
id = n[0].id
or you can use the jQuery attr function, which works on the first element in the set
id = n.attr('id');
In jstree version 3.1.1, you can get it directly from get_selected:
$("#<your tree container's id>").jstree("get_selected")
In the most recent version of jsTree (checked at 3.3.3), you can do this to get an array of IDs:
var ids = $('#tree').jstree('get_selected');
This will return, for example, ["selected_id1", "selected_id2", "selected_id3"]. If you want to get the selected nodes (not IDs), you can do this:
var nodes = $('#tree').jstree('get_selected', true);
The current docs contain more information.
$.jstree._reference('#my_tree_container')._get_node(null, true).each(function() {
id = $(this).attr("id");
alert('Id selected: ' + id);
});
I was having problems getting the selected ids from a tree with MULTIPLE selections. This is the way I got them:
var checked_ids = [];
$("#your-tree-id").jstree('get_selected').each(function(){
checked_ids.push($(this).data('id'));
});
In my case, the data call doesnt work.
I succeed in accessing my node data by using attr function.
$("#tree").jstree("get_selected").attr("my-data-name");
to get all selected ids use the below code
var selectedData = [];
var selectedIndexes;
selectedIndexes = $("#jstree").jstree("get_selected", true);
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(selectedIndexes[index].id);
});
now you have all the selected id's in the "selectedData" variable
<script type="text/javascript>
checked_ids.push($(this).context.id);
</script>
Just use
var nodeId = $('#FaqTreeView').jstree().get_selected("id")[0].id;
where #FaqTreeView is the id of your div that contains the jstree.
In some cases and/or jstree versions this solution doesn't work.
$('#tree').jstree('get_selected').attr('id');
Instead of defined "id" I get nothing.
What did the trick for me is:
$("#tree").jstree("get_selected").toString();
These are all old answers for old versions. As of version 3.3.3 this will work to get all attributes of the selected node.
$('#jstree').jstree().get_selected(true)[0]
If you then want the id then add .id at the end. You can look at all the other attributes in web developer tools if you copy the above code.
You can use the following code
var nodes = $("#jstree_demo_div").jstree(true).get_selected("full", true);//List of selected node
nodes[0].id//Which will give id of 1st object from array
With the latest version of jsTree, you can do it as follows:
var checked_ids = [];
$('#your-tree-id').jstree("get_checked",null,true).each(function(){
checked_ids.push(this.id);
});
alert(checked_ids.join(","));

Categories

Resources