Thursday, August 24, 2017

Bind Some Event to Element and trigger that function when click the element

Scenario:

Suppose if we used same click event function in various web pages. if you want do some logic some page button for that need to register the event

for buttons


Register events to button:

 $(document).ready(function(){
        $('.apply-filter').bind('beforeClick',function(event) {           
            if ($(this).data("value")=="10") {
                return true;
            }
            else return false;
        });
    });

Trigger the Registered function inside click event:

- creat event object using $.Event() metod and then trigger event by trigger(); method
- check the event prevented or not using event.isDefaultPrevented() based on that we can handle click event
- Button creations

 <div class="col-md-12" style="clear:both;">
            Button1 <button class="apply-filter" data-value="5">Five</button>
        </div>
        <div class="col-md-12">
            Button2 <button class="apply-filter" data-value="10">Ten</button>
        </div>
         <div class="col-md-12">
            Button2 <button class="apply-filter" data-value="15">Fifteen</button>
</div>

Sunday, August 6, 2017

Find Charts from web page and convert chart to Png using jquery

Find highcharts which are loaded in the page and then convert chart into png using  jquery

Charts are loaded through the ajax

See the example code:

create four php files for rendering charts one by one those file names are page1.php, page2.php, page3.php and page4.php

page1.php
---------

<?php
sleep(12);
$id = $_GET['key'];
?>
<div id="container<?php echo $id; ?>" style="">           
        </div>

 <script type="text/javascript">
      var chart =   Highcharts.chart('container<?php echo $id; ?>', {
    chart: {
        type: 'bar'
    },
    title: {
        text: 'Stacked bar chart'
    },
    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Total fruit consumption'
        }
    },
    legend: {
        reversed: true
    },
    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },
    series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2]
    }, {
        name: 'Jane',
        data: [2, 2, 3, 2, 1]
    }, {
        name: 'Joe',
        data: [3, 4, 4, 2, 5]
    }]
});     
 </script>

page2.php
---------

<?php
$id = $_GET['key'];
?>
<div id="container<?php echo $id; ?>" >           
        </div>
<script type="text/javascript">
Highcharts.chart('container<?php echo $id; ?>', {

    chart: {
        type: 'column'
    },

    title: {
        text: 'Total fruit consumtion, grouped by gender'
    },

    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },

    yAxis: {
        allowDecimals: false,
        min: 0,
        title: {
            text: 'Number of fruits'
        }
    },

    tooltip: {
        formatter: function () {
            return '<b>' + this.x + '</b><br/>' +
                this.series.name + ': ' + this.y + '<br/>' +
                'Total: ' + this.point.stackTotal;
        }
    },

    plotOptions: {
        column: {
            stacking: 'normal'
        }
    },

    series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2],
        stack: 'male'
    }, {
        name: 'Joe',
        data: [3, 4, 4, 2, 5],
        stack: 'male'
    }, {
        name: 'Jane',
        data: [2, 5, 6, 2, 1],
        stack: 'female'
    }, {
        name: 'Janet',
        data: [3, 0, 4, 4, 3],
        stack: 'female'}]
    });      
 </script>

page3.php
---------
<?php
$id = $_GET['key'];
?>
<div id="container<?php echo $id; ?>">           
</div>

 <script type="text/javascript"> 
$(document).ready(function () {
    // Build the chart
    Highcharts.chart('container<?php echo $id; ?>', {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'Browser market shares January, 2015 to May, 2015'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: true
            }
        },
        series: [{
            name: 'Brands',
            colorByPoint: true,
            data: [{
                name: 'Microsoft Internet Explorer',
                y: 56.33
            }, {
                name: 'Chrome',
                y: 24.03,
                sliced: true,
                selected: true
            }, {
                name: 'Firefox',
                y: 10.38
            }, {
                name: 'Safari',
                y: 4.77
            }, {
                name: 'Opera',
                y: 0.91
            }, {
                name: 'Proprietary or Undetectable',
                y: 0.2
            }]
        }]
    });
});     
</script>

page4.php
---------
<?php
$id = $_GET['key'];
?>
<div id="container<?php echo $id; ?>" >    
        </div>
 <script type="text/javascript">
      var chart =   Highcharts.chart('container<?php echo $id; ?>', {
    chart: {
        type: 'bar'
    },
    title: {
        text: 'Stacked bar chart'
    },
    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Total fruit consumption'
        }
    },
    legend: {
        reversed: true
    },
    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },
    series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2]
    }, {
        name: 'Jane',
        data: [2, 2, 3, 2, 1]
    }, {
        name: 'Joe',
        data: [3, 4, 4, 2, 5]
    }]
});     
</script>

Now Create Index.html.

First Load the necessary libraries of JQuery and highcharts

 <head>
        <script src="https://code.highcharts.com/highcharts.js"></script>
        <script src="https://code.highcharts.com/modules/exporting.js"></script>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
 </head>


and charts through the ajax using loop:

var ajax = [1,2,3,4,1,2,3,4,1,2,3,4];
        for(var k in ajax){ // loop
            //console.log();
// create div container for load charts dynamically and append it to body tag
            html = '<div id="cont'+k+'"style="min-height:400px;min-width:800px;border-width: 2px; border-style: solid; border-color: red; "></div>';
            $("body").append(html);
// scope function handling multiple ajax
         (function(key,ajax){
            // passing ajax to chart php files        
            $.ajax({
                method: 'get',
                url:'page'+ajax+'.php?key='+key+'&rand='+Math.random(),
                success: function(data) {
                   // load ajax response
                   $("#cont"+key).html(data);
// image conversion method
                   charttoimage(key);
                }
            });            
          
    })(k,ajax[k]);            
              
} });

Next charttoimage method explantion:

1) We can get highcharts objects using Highcharts.charts
2) We can get svg string from objects getSvg() method(highcharts native method)
3) we can convert svg into image using canvas element and canvas drawimage method
4) Create Image Object and render into highchart render element
5) Canvas to png binary using canvas toDataUrl methods
6) Image onload event load image.

code below:

var chartToImgArr = [];
    function charttoimage(key){
        // loop highchart     
        for(chart in Highcharts.charts){
            //check and skipe already converted
            if($.inArray(chart,chartToImgArr)>-1){ continue;  }             
            chartToImgArr.push(chart);
            // get chart obeject
            chart = Highcharts.charts[chart];
           // get SVG String
            var svg = chart.getSVG({
                exporting: {
                    sourceWidth: chart.chartWidth,
                    sourceHeight: chart.chartHeight
                }
           });
       // create canvas
            var canvas = document.createElement('canvas');
            canvas.width = chart.chartWidth;
            canvas.height = chart.chartHeight;
            // create image           
            var image = new Image;
            image.onload = function() {
            // drawimage into canvas
            canvas.getContext('2d').drawImage(this, 0, 0);
            // convert into png
            var data = canvas.toDataURL("image/png");
            image.src = data;           
            }; 
            // set svg into image tag         
            image.src = 'data:image/svg+xml;base64,' + window.btoa(svg);
            $(chart.renderTo).html(image);           
        } 
    }

Index.html:

<html>
    <head>
        <script src="jquery-3.2.1.min.js"></script>
        <script src="highcharts.js"></script>
        <script src="exporting.js"></script>
        <script type="text/javascript">
$(document).ready(function(){
    var chartToImgArr = [];
    function charttoimage(key){      
        for(chart in Highcharts.charts){
            if($.inArray(chart,chartToImgArr)>-1){ continue;  }             
            chartToImgArr.push(chart);
            chart = Highcharts.charts[chart];
          
            var svg = chart.getSVG({
                exporting: {
                    sourceWidth: chart.chartWidth,
                    sourceHeight: chart.chartHeight
                }
           });
            var canvas = document.createElement('canvas');
            canvas.width = chart.chartWidth;
            canvas.height = chart.chartHeight;
                      
            var image = new Image;
            image.onload = function() {
            canvas.getContext('2d').drawImage(this, 0, 0);           
            var data = canvas.toDataURL("image/png");
            image.src = data;           
            };           
            image.src = 'data:image/svg+xml;base64,' + window.btoa(svg);
            $(chart.renderTo).html(image);           
        } 
    }

           var ajax = [1,2,3,4,1,2,3,4,1,2,3,4];
           for(var k in ajax){         
            html = '<div id="cont'+k+'"style="min-height:400px;min-width:800px;border-width: 2px; border-style: solid; border-color: red; "></div>';
            $("body").append(html);
            (function(key,ajax){
            kkey = parseInt(key)+1;           
            if(kkey>=4) { kkey = kkey%4; if(kkey==0) kkey = kkey+1; }
            console.log("chart==="+key);
            $.ajax({
                method: 'get',
                url:'page'+ajax+'.php?key='+key+'&rand='+Math.random(),
                success: function(data) {
                  
                   $("#cont"+key).html(data);
                   charttoimage(key);
                }
            });            
          
    })(k,ajax[k]);    
}
});
        </script>
    </head>
    <body>
       
    </body>
</html>

OutPut:

Bind Some Event to Element and trigger that function when click the element

Scenario: Suppose if we used same click event function in various web pages. if you want do some logic some page button for that need to re...