Monday, July 20, 2015

JavaScript - Pinch and Zoom using Hammer JS

How to zoom content and not header or footer. Follow as below

Its simple with Hammer JS, download from here http://hammerjs.github.io/  or from Nuget package.

HTML Page:

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
...
<script src="~/Scripts/hammer.min.js"></script>
...
<div id="someContainer">
..Some Content goes here
</div>

<script type="text/javascript">
    $(document).ready(function () {
        //Regisister here
        var element = $('#someContainer');
        contentPinchIntializer(element[0]);
    });

</script>


JavaScript to Pinch and Zoom content:
- Here i created max scale as 5, you can customize it
- Here i added Margin left and Margin Right to avoid space issue while on zooming, you can adjust the pixels however you want
- Added touch-action to enable horizontal scrolling

var contentPinchIntializer = function (element) {
    var scale = 1;
    var currentScale = null;
    var currentMarginLeft = null;
    var currentMarginRight = null;

    var pinchInHanlder = function (e) {
        scale = event.gesture.scale == null ? scale : event.gesture.scale;
        currentScale = currentScale == null ? scale : currentScale;
        currentMarginLeft = currentMarginLeft == null ? $(this).css("margin-left") : currentMarginLeft;
        currentMarginRight = currentMarginRight == null ? $(this).css("margin-right") : currentMarginRight;

        if (scale < currentScale) {
            scale = currentScale + 0.1;
            $(this).css({ "margin-left": currentMarginLeft, "margin-right": currentMarginRight });
        }

        scale = ('scale(' + (scale - 0.1).toString() + ')');

        $(this).css({ 'transform': scale, '-ms-transform': scale, '-webkit-transform': scale });
    };

    var pinchOutHandler = function (e) {
        scale = event.gesture.scale == null ? scale : event.gesture.scale;
        currentScale = currentScale == null ? scale : currentScale;
        currentMarginLeft = currentMarginLeft == null ? $(this).css("margin-left") : currentMarginLeft;
        currentMarginRight = currentMarginRight == null ? $(this).css("margin-right") : currentMarginRight;

        if (scale <= 5) {
            $(this).css({ "margin-left": "200px", "margin-right": "100px" });
            scale = ('scale(' + (scale + 0.1).toString() + ')');
            $(this).css({ 'transform': scale, '-ms-transform': scale, '-webkit-transform': scale });
        }
    };

    var hammertime = Hammer(element).on("pinchin", pinchInHanlder).on("pinchout", pinchOutHandler);

    $(element).css("touch-action", "manipulation");


}