Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatables 1.10 sort only by cliking sort icons in th

I am using datatables version 1.10. I have a requirement where

  1. when clicked on sort icons (up and down arrows) sorting should work server side
  2. when clicked on th , sorting should work locally.This is because user clicks on thead by mistake and servers gets unwanted burden.

Objective: I wanted to keep both

  1. local sorting [clicking thead not icons](only for data currently in table display/page)
  2. server side sorting [only by clicking icons].

THE PROBLEM: DataTables uses css background-image for sorting. This makes it difficult to detect click on icons since css background-image can not be captured on clicks as per my knowledge.

This is what i have come up with but still no progress

JSFIDDLE: http://jsfiddle.net/bababalcksheep/mae29pau/10/

JS:

$(document).ready(function () {
    //http://www.datatables.net/reference/api/
    var url = "http://www.json-generator.com/api/json/get/cbEfqLwFaq?indent=2";
    //
    $('th').on("click.DT", function (event) {       
        event.stopImmediatePropagation();
    });

    var table = $('#example').DataTable({
        "processing": true,
            "serverSide": false,
            "ajax": url
    });
    //
    //$('th').off('click.DT');
    // sort internally
    table.column('2').order('asc');
});

UPDATE-1:

JSFIDDLE: http://jsfiddle.net/bababalcksheep/mae29pau/14/

I was able to go one step ahead by adding a sortMask and then bind a click on it. sortMask is a div which id added to each column <thead> -> <tr> -> <th>

enter image description hereCSS:

.sortMask {
    width:19px;
    height:19px;
    float:right;
    display:inline-block;
    z-index:0;
    margin-right: -19px;
    /*background:red;*/
}

JS:

    $('th').on("click.DT", function (e) {
        //stop Propagation if clciked outsidemask
        //becasue we want to sort locally here
        if (!$(e.target).hasClass('sortMask')) {
            e.stopImmediatePropagation();
        }
    });
like image 411
django Avatar asked Dec 05 '14 14:12

django


1 Answers

I think the better solution here is to wrap the text not the icon:

<th><div>First name <div>abc</div></div></th>

And:

$('th').on("click", function (event) {
    if($(event.target).is("div"))
        event.stopImmediatePropagation();
});

Please note: you should use normal click even instead of click.DT because in this case it will be fired before DataTables one.

http://jsfiddle.net/mae29pau/38/

like image 151
Daniil Ryzhkov Avatar answered Sep 28 '22 19:09

Daniil Ryzhkov