Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Sunday, February 4, 2018

Some Tips and Tricks of Working With Bootstrap Select2 Control

Hello,

Since I am a web developer, I used to work  a lot with Bootstrap Select 2 Control. Here I am going to share some quick tips and tricks of working with Select 2 controls.

1) Dynamically create Select2 control with JavaScript

When we are working on dynamic websites, sometimes we also have to create select2 controls dynamically. Most of the developers faces issues here. Because select2 control is created by JavaScript on document ready. So if you want create it dynamically, first append basic html of control inside and the by using JavaScript init it.

Something like this.

$('.select2').select2();

Sometimes it takes time to get reflect in DOM so in this case you may have to give some timeout.

setTimeout(function(){
      $('.select2').select2();
},500);

2) Open Select2 dropdown on focus.

This is one more UX experience. Most of the web users are used to work with TAB. So in your form if you have select2 control and you come on it via tab. It should open dropdown.

Here is how we can do it.

$(document).on('focus', '.select2', function() {
if($(this).prev().val() == ''){
  $(this).siblings('select').select2('open');
}
});

3) Open Select2 dropdown with down arrow key

This is one more UX experience. Most of the web users are used to work with up and down arrow while working with dropdown. So in case of select2 they are expecting the same result.

$(document).on('keydown', '.select2', function(event) {
    if(event.keyCode == 40){
    $(this).siblings('select').select2('open');
    }
});

4) Keep focus on Select2 after selecting item and dropdown is closed.

In new version of Select2 there is a bug that after you select an item and dropdown is closed. It will lost focus. So to keep focus on the control, use following code.

$('select').on(
  'select2:close',
  function () {
  $(this).focus();
  }
  );
},1000);

Hope this tips helps you in your development with Select2.

Sunday, January 14, 2018

jQuery Close Modal Window When User Clicks Outside of It

Recently in my work we faced an issue due to some JavaScript conflict on a page where we have modal popups that were not closing when user clicks outside of it and anywhere on page. Normally it does automatically in jQuery pop up. So here we have to add custom code to handle this situation. In this blog I am going to explain how to do it.

In above picture I explained how to do it. So basic trick is to track click event on entire web page and to check it it's X and Y coordinates are inside the BOX of modal window. If yes then do not close it. But if it's out side of it, close the modal popup. Here is the code for the same.

  var rect = $('.modalSelector')[0].getBoundingClientRect();
  clientX1 = rect.x
  clientX2 = rect.x + rect.width;

  clientY1 = rect.y
  clientY2 = rect.y + rect.height;

  if((e.clientX >= clientX1 && e.clientX <= clientX2) && (e.clientY >= clientY1 && e.clientY <= clientY2)){
    return;
  }

  if($('#modalSelector').hasClass('active')){
    $('#modalSelector').removeClass('active');
    $('. modalSelector').hide();
  }

That's it and it will close if you click anywhere on web page outside of modal popup.

Thursday, September 7, 2017

jQuery Submit Form with Ajax

Hello,

In this blog we are going to take a look at how we can submit for with Ajax using jQuery.

First of all add jQuery file in your head section of HTML page.

<script src="jquery.min.js"></script>

Now we will have following form.

<form action="">
      <input id="text" autocomplete="off" placeholder="Type here" />
</form>

If you want to submit this form with Ajax using jQuery, first you have to do is add submit event handler.

$(function () {
$('form').submit(function(){
var formData = JSON.stringify($('form').serializeArray());
$.ajax({
type: "POST",
url: "YOUR_API_URL",
data: formData,
success: function(data){

},
failure: function(errMsg) {
}
});
return false;
    });
});

So first we have added submit event handler and used return false so it does refresh the whole page and just use the Ajax request.  Inside event handler we are using HTML 5 FormData to get form data first and then using Ajax request to send data to server in APIs.

Hope this helps you.

Friday, January 22, 2016

jQuery JSTree Tips and Tricks Like Expand All Nodes, Get Selected Node, Get Extra Information

Hello,

Recently in one my project I used jQuery JSTree for display data in tree format and while working with I faced certain issues so here I am sharing some tips and tricks you can use with JSTree.

1) Expand All Nodes on Page Load


If you have dynamic dataset in JSTree and you want to expand it when tree is created here is what you can do. First call AJAX service to get data.

$.ajax({
            url: "cat-tree",
            cache: false
        }).done(function( json ) {
            //init js tree here
         
        });

For example in above service I am calling url cat-tree and get my JSON data. Now add following code to initialize JSTree.

$('#categoryTree').jstree({
                'plugins': ["wholerow", "types"],
                'core': {
                    "themes" : {
                        "responsive": false
                    },
                    'data': json
                },
                "types" : {
                    "default" : {
                        "icon" : "fa fa-folder icon-state-warning icon-lg"
                    },
                    "file" : {
                        "icon" : "fa fa-file icon-state-warning icon-lg"
                    }
                }
            });

That's it now wait for sometime to get it rendered in DOM and then expand it.

setTimeout(function(){
                $('#categoryTree').jstree("open_all");
            },500);

2) Add select event and get Selected Node in JSTree

Add following code to add select event.

$('#categoryTree').on('select_node.jstree', function(e,data) {
                    //Your code here
                });

Use following code to get single selected node of JSTree.

var selectedNode = $('#categoryTree').jstree().get_selected(true)[0];

Use following code to get single multiple selected nodes of JSTree.

var selectedNode = $('#categoryTree').jstree().get_selected(true);

3) Deselect all the Nodes in JSTree

Use following code to deselect all the nodes in JSTree.

$('#categoryTree').jstree("deselect_all");

4) Access Additional Data of Selected Node

We know that there is a standard format of data used with JSTree. For example.

[
       'Simple root node',
       {
         'text' : 'Root node 2',
         'state' : {
           'opened' : true,
           'selected' : true
         },
         'children' : [
           { 'text' : 'Child 1' },
           'Child 2'
         ]
      }
    ]

What if you want to have extra data like this.

[
       'Simple root node',
       {
         'text' : 'Root node 2',
         'key1': 'value1',
         'key2': 'value2'
         'state' : {
           'opened' : true,
           'selected' : true
         },
         'children' : [
           { 'text' : 'Child 1' , 'key1': 'value1', 'key2': 'value2'},
           'Child 2'
         ]
      }
    ]

You can pass any number of extra data buy how will you access it. Check the following code.

First get selected node.

var selectedNode = $('#categoryTree').jstree().get_selected(true)[0];

Extra data is available in key  called original.

var value1 = selectedNode.original.key1;
var value2 = selectedNode.original.key2;

Hope this helps you.

Sunday, April 21, 2013

TinyMCE Editor Height Issue in ExtJs Application

Hello,

This is another blog post on TinyMCE editor in ExtJs application, Have you ever noticed that If you use TinyMce editor in ExtJs application there are some issues with height. Sometimes it takes more height then you specified and that might destroy your layout completely. This is due to internal calculations and logic of TinyMCE editor.

The logic is wrong in two ways. First thing is that it always assume that minimum height of TinyMCE editor should be 100 so if you give height less then 100. It will always take it as 100 and hence your layout is wrong. Because outer div of editor will show the height which you gave but it's actual height would be different.

Second issue is that it does not take care of editor's tool bar where you have all the controls. Actually editor's height should be height which you specified minus height of control toolbar. Which actually is not the case. It gives separate height to toolbar. For example if you set height of your editor to 100. It actually set height to 128. 100px height of editor and 28px height of toolbar controls so it's totally wrong. So what is the solution?

Well the solution is in the TinyMCE src file. You will have tiny_mce_src.js file in your app. There go to line no 13301 approximately. There you will see following line.

mh = s.min_height || 100;

This is where the issue is. If you give height less then 100 it will always take 100 as minimum height. So change it as follow.

mh = s.min_height || s.height;

Now it will take minimum height which you specified. Now go to line no 13426 approximately.  Here change the height from

height : h

to

height : h-28

That's it and all your issues related to heights are resolved.

It took 4 hours for me to find the solution so I hope this post saves your time.

Thanks.






TinyMCE editor in ExtJs Application Returns Old Value.

Hello,

Finally I got some to add some more interesting blogs. Recently I have faced an issue with TinyMCE editor in ExtJs application. The issue was little wired. We have a TinyMCE editor in ExtJs form panel where it's disabled first. There is a button in form panel which enables. After that if we update any value in TinyMCE editor, it shows on screen but when we get value from form panel, the value of TinyMCE field is always the old one.

After struggling for some hours, I find out the issue. When TinyMCE is disabled, there are no events of active editor. But when we enable it editor should be initialized properly and all the event handlers should be attached. However it's not happening. So what is the solution for it. Change the logic of TinyMCE intilization and add key up event.


setup : function( ed ) {
ed.onKeyUp.add(function(ed) {
tinymce.activeEditor.save();
});
}

This you can find it your TinyMCEHtmlEditor.js file. What it does is it saves the state of current active editor when we type something it it. This logic works when you have more then one TinyMCE editor in single form. Because when you are typing inside it tinymce.activeEditor gives instance of current active editor and keyup events save its state. So when you getValue of editor, it reflects the new value.

Hope this helps you.

Saturday, February 12, 2011

Modified jQuery sortable for horizontal and vertical sorting

Recently I got a requirement to modify jQuery sortable for horizontal and vertical sorting capability. Basically we have to override some functions from jQuery sortable. By default jQuery sortable only provides vertical sorting. But for me requirement was some thing different. See the images below.

Sorting should be something like above. First of all let's see how jQuery sortable does this. If you see the source code there is a function called _rearrange(). This is the function responsible for rearranging the items. This function is called when there is some kind of intersection between items. For example if you want to swap item1 and item2, you have to drag item1 over item2. Code will detect intersection and it will rearrange the items. But in our case there is no intersection as we are dragging item 2 towards right hand side where there are no items.

So how we can do this? First of all we need to give style clear:both and float:left to all the items. When we set this style to any component, it will not allow any floating element on both sides. After setting above styles to all the items we get layout shown in left hand side image. As there is no intersection now we can not use _rearrange() function for changing position. We have to use another function available in jQuery sortable code, that is _mouseStop(). This is the function which is executed when we stop dragging. In this function first of all we need to identify drag direction . Drag direction should be either right top or right bottom. Once the direction is identified we have to set style clear:none for dragged object. Following is the code for it.

var horizontalDistance = Math.abs(this.offset.left - this.currentItem[0].offsetLeft);
var verticalDistance = Math.abs(this.offset.top - this.currentItem[0].offsetTop);
if(horizontalDistance > (this.currentItem[0].clientWidth/2) || verticalDistance > (this.currentItem[0].clientHeight))
{
if(this.offset.left>event.pageX){
this.horizontalDirection = 'left';
}
else{
this.horizontalDirection = 'right';
}
if(this.offset.top>event.pageY){
this.verticalDirection = 'up';
}
else{
this.verticalDirection = 'down';
}
if(this.horizontalDirection == 'right' && this.verticalDirection == 'up'){
this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
this.currentItem[0].style.clear = "none";
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
}
}

To avoid unnecessary flicker effect, I have removed placeholder.

This is the code which you need to insert in _mouseStop() function at start. I am still working on it and doing some more changes to make it fully functional for all the scenarios so your suggestions are welcome. Please post a comment if you have any suggestion.