Friday 30 March 2018

Useful jstree events & functions

Get jstree node by id

Syntax:  $("jstree_id").jstree(true).get_node("node_id", true);
Example:  $("#mytree").jstree(true).get_node(j1_1, true);

Set maximum length for jstree node input

$(".jstree-rename-input").attr('maxLength', 20);

Get jstree node length (total number of nodes)

var nodeLen=$("#mytree").jstree(true).get_json('#', {flat:false}).length;
console.log(nodeLen)

How to rename jstree node

$("#mytree").jstree('rename_node', data.node , "My Node" ); // set name as "My Node"

Do some operation when node is opened (jstree open node event)

$("#mytree").on('open_node.jstree', function(evt, data){
 // Do something
});

Do some operation when node is hovered (This event will be triggered when you hover on jstree node)

$("#mytree").on("hover_node.jstree", function(evt, data){
 // Do something
});

Set new id for jstree node

var newId=10;
$("#mytree").jstree(true).set_id(node,newId);

Get children of node

var nodeId=10;
var childrensArr = $("#mytree").jstree(true).get_node(nodeId).children;
for (var i = 0; i < childrensArr.length; i++){    
 // Do something
}

Open all jstree nodes

$("#mytree").jstree("open_all");

Sunday 14 January 2018

How to check image exist on server using JQuery Ajax

Sometimes you need to check whether resource is available on the server or not to show it on web page. For instance if you want to show image on your web page but you don't know whether it exists or not on server. How do you check that using Javascript or JQuery??

Well there is a way, using simple & small jquery/ajax code you can achieve that.

Here is the example:

 function IsImageExists(imageUrl){
  var result;  
  $.ajax({
       url: imageUrl,
       type:'HEAD',
       async: false,
       success: function(res){
        result=true;        
       },
       error:function(error){
        result=false;        
       }
  });
  return result;
 }
 
 var url="http://localhost:8080/myproject/images/myimg.png";
 var result=IsImageExists(url); 
 
 if(result == true){
  console.log("Image Exists");  
 }else{
  console.log("Image Not found");
 }

Hope it works. Thanks..!!