Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Friday, June 28, 2019

Crop and Resize Images Using (Mouse Or Touch Capable) With This Simple jQuery Plugin

The Cropper plugin requires a copy of jQuery and it comes with two files: a CSS stylesheet and the JavaScript plugin library. Just add these files to your page and it should be good to go!
Download plugin file from here
var options = {
  aspectRatio: 0,
  preview: '.img-preview',
  ready: function (e) {
    console.log(e.type);
  },
  cropstart: function (e) {
    console.log(e.type, e.detail.action);
  },
  cropmove: function (e) {
    console.log(e.type, e.detail.action);
  },
  cropend: function (e) {
    console.log(e.type, e.detail.action);
  },
  crop: function (e) {
    var data = e.detail;

    console.log(e.type);
    data.x = Math.round(data.x);
    data.y = Math.round(data.y);
    data.height = Math.round(data.height);
    data.width = Math.round(data.width);
    data.rotate = typeof data.rotate !== 'undefined' ? data.rotate : '';
    data.scaleX = typeof data.scaleX !== 'undefined' ? data.scaleX : '';
    data.scaleY = typeof data.scaleY !== 'undefined' ? data.scaleY : '';

    console.log(data);
  },
  zoom: function (e) {
    console.log(e.type, e.detail.ratio);
  }
};
var cropper = new Cropper(image, options);

Monday, June 17, 2019

JavaScript | JQuery | Check if a variable is type of String | Number | Null | Undefined | Array | Object

console.log(Object.prototype.toString.call("This is string"));
console.log(Object.prototype.toString.call(undefined));
console.log(Object.prototype.toString.call(0));
console.log(Object.prototype.toString.call(null));
console.log(Object.prototype.toString.call([]));
console.log(Object.prototype.toString.call({}));
And respective output is as below:
[object String]
[object Undefined]
[object Number]
[object Null]
[object Array]
[object Object]

Saturday, May 25, 2019

jQuery Resize and Compress Image

This is a jQuery technique to resize image using canvas and Image object. You can resize image as you wanted.
Below is a jQuery class that will actually convert file to blob after resize done:
class ImageResizer {
  "use strict"

  static _initDone = false;

  static resize(file, options, callback) {
    this._init();

    var thisOptions = {
      maxWidth: 1200
    };
    $.extend( thisOptions, options );

    var width = thisOptions.maxWidth;
    var fileName = file.name;
    var fileType = file.type;

    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(event) {
      const img = new Image();
      img.src = event.target.result;
      img.onload = function() {
        if (width > img.width) {
          width = img.width;
        }
        const elem = document.createElement('canvas');
        elem.width = width;
        const scaleFactor = width / img.width;
        elem.height = img.height * scaleFactor;
        const ctx = elem.getContext('2d');
        // img.width and img.height will contain the original dimensions
        ctx.drawImage(img, 0, 0, width, img.height * scaleFactor);

        // function(callback_function, file_type, quality_0_to_1)
        ctx.canvas.toBlob(function(blob) {
          blob.lastModifiedDate = Date.now();
          blob.name = fileName;
          blob.width = width;
          blob.height = img.height * scaleFactor;

          callback(undefined, blob);
        }, fileType, 1);
      },
        reader.onerror = function(error) {
          callback(error);
        };
    };
  }

  static _init() {
    if (!this._initDone) {
      this._initDone = true;

      if (!HTMLCanvasElement.prototype.toBlob) {
        Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
          value: function (callback, type, quality) {
            var dataURL = this.toDataURL(type, quality).split(',')[1];
            setTimeout(function() {
              var binStr = atob( dataURL ), len = binStr.length, arr = new Uint8Array(len);
              for (var i = 0; i < len; i++ ) {
                arr[i] = binStr.charCodeAt(i);
              }
              callback( new Blob( [arr], {type: type || 'image/png'} ) );
            });
          }
        });
      }
    }
  }
}
And you can use this from html page as below:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Image Resize Component</title>
  <script src="//code.jquery.com/jquery-1.7.2.min.js"></script>
  <script src="image-resizer.js"></script>
  <script type="text/javascript">
    $(document).on('ready', function() {
      var image = $("#PhotoPicker");
      image.on('change', function(e) {
        $("canvas").remove();

        ImageResizer.resize(e.target.files[0], {maxWidth: 300}, function(error, blob) {
          const canvas = document.createElement('canvas');
          canvas.width = blob.width
          canvas.height = blob.height;
          const context = canvas.getContext('2d');

          var img = new Image();
          img.onload = function(){
            context.drawImage(img, 0, 0, blob.width, blob.height);
          };
          img.onerror = function(e){
            console.log('Error during loading image:', e);
          };
          img.src = URL.createObjectURL(blob);

          document.body.appendChild(canvas);
        });
      });
    });
  </script>
</head>
<body>
<input type="file" id="PhotoPicker" accept="image/*" capture="camera"><br/><br/>
</body>
</html>

Friday, June 22, 2018

jQuery AJAX fetch only headers and decide wheather to get the content | Use jQuery to send a HEAD request with AJAX and get the size of a file | Getting response headers data from an AJAX request with javascript

Response headers can contain valuable information and may help to keep your API responses simpler by separating the actual response data from accessory metadata.
For instance, when querying the API for a list of posts, the response body includes just the content but there are also some other valualbe information sent as headers:
The jQuery code for the AJAX request would look something like this:
$.ajax({
    type: 'HEAD',
    url: 'http://example.com/api.php',
    complete: function (xhr) {
        var contentLength = xhr.getResponseHeader('Content-Length');
        // OR YOU CAN SEE ALL INFORMATION USING
        var headers = xhr.getAllResponseHeaders();
    }
});
Which will output as below:
http://localhost/text-finder/download.pdf >> application/pdf
date: Fri, 22 Jun 2018 06:35:52 GMT
last-modified: Sun, 11 Feb 2018 16:39:41 GMT
server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35
etag: "5ae6f-564f2687e28f8"
content-type: application/pdf
connection: Keep-Alive
accept-ranges: bytes
keep-alive: timeout=5, max=100
content-length: 372335



http://localhost/text-finder/test2.html/forum >> text/html; charset=utf-8
date: Fri, 22 Jun 2018 06:35:52 GMT
server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35
vary: accept-language,accept-charset
content-language: en
connection: Keep-Alive
accept-ranges: bytes
content-type: text/html; charset=utf-8
keep-alive: timeout=5, max=97

Saturday, June 16, 2018

jQuery UI Dialog > Disable Auto Focus > Prevent jQuery UI Dialog From Setting Focus To First Textbox > Disable Auto Focus Of First Input Box > Prevent Auto Scroll To Top Of Dialog Box

There are several problems related to auto focus of jQuery UI Dialog. Some of them are below:

> Opening jQuery Date picker automatically on focus of dialog, because of first element get auto focused.

> If dialog has scrollbar visible, its auto scrolled to top to auto focus first element of dialog.
So to disable auto focus input element inside UI dialog, add the following code before you call dialog. This will clear out the autofocus code.
$.ui.dialog.prototype._focusTabbable = function(){};

Friday, June 8, 2018

$(window).width() AND $(window).outerWidth() excluding the scrollbar width > Window and viewport width in CSS and Javascript

It is very unpleasant that $(window).width() or $(window).outerWidth() does not return actual view port width scroll bar width. Especially when trying to match the window width to the CSS media queries.
Currently if you have a media query for responsive design with the CSS like:
@media screen and (max-width: 1600px) {
  body {background: red;}
}
When the background color is actually applied to the document by the browser, jQuery tells the window width is less than 1600px (1600 - scrollbar width). But you know its not the expected result.
This is very unpleasant situation cases where there are some mobile-specific stuff that needs to be done in both, CSS and JS. And they would need to be done at the exactly same width of the document/window.
However, plain JavaScript returns 1600 as the window width when asked using below code snippet:
window.innerWidth

Monday, May 7, 2018

JQuery Custom Popup Example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Custom Popup</title>
    <meta name="viewport" content="user-scalable=yes, initial-scale=1, maximum-scale=1,minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi"/>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="custom-popup.js?v=<?= time() ?>"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            console.log(CustomPopup.getAvailableOptions());
            var body = $(document.body), html = body.find(".move-container").clone(true);
            // to get or check initial config of CustomPopup just console log below
            // CustomPopup.getAvailableOptions()
            // and all available events shown in "triggers" array
            // so what you need to do popup.trigger("close") to close popup
            body.find(".open-popup-html").click(function() {
                CustomPopup.fromHTML($("<div>Are you sure want to delete?</div>"));
            });
            body.find(".open-popup-url").click(function() {
                CustomPopup.fromURL("popup.php", {id: 0}, {
                    // you also can set all below function and variables
                    // as html data attribute
                    onOpen: function(p) {
                        console.log("POPUP OPENED");

                        // disabling popup
                        p.trigger("disable");

                        setTimeout(function() {
                            // enabling popup
                            p.trigger("enable");
                        }, 2000);
                    },
                    onClose: function(p) {
                        console.log("POPUP CLOSED");
                    },
                    onSubmit: function(p) {
                        p.trigger("show-loading");
                        console.log("POPUP SUBMITTED");
                        // return false will not close popup immediately
                        // you have to close manually by popup.trigger("close")
                        setTimeout(function() {
                            p.trigger("close-loading");
                            setTimeout(function() {
                                p.trigger("close");
                            }, 2000);
                        }, 2000);
                        return false;
                    },
                    popupTitle: "POPUP TITLE",
                    yesText: "YES TEXT",
                    noText: "NO TEXT",
                    showTitle: true,
                    showClose: true,
                    popupClass: "some-class",
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader('X-Test-Header1.1', 'test-value1');
                        xhr.setRequestHeader('X-Test-Header2.1', 'test-value2');
                    },
                    xhrFail: function(jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR);
                        console.log(textStatus);
                        console.log(errorThrown);
                    }
                });
            });
        });
        function formSubmitted() {
            alert("POPUP SUBMITTED");
        }
    </script>
</head>
<body>
<button class="open-popup-html">Open popup from HTML</button><br/>
<button class="open-popup-url">Open popup from URL</button><br/>
<button
    type="button" data-popup-url="popup.php"
    class="my-popup-opener" data-popup-class=""
    data-yes-text="Save" data-on-submit="formSubmitted"
    data-popup-title="MY POPUP" data-on-open="formOpened"
    data-no-text="Close" data-show-title="1">
    Open Popup On Click Html Element (.my-popup-opener)
</button>
</body>
</html>

On popup submit there will be an overlay shown above.
You can download full source code from here

Saturday, May 5, 2018

JQuery TreeView Example And Stylish Select DropDown

Create TreeView example:
Here container is the boundary within tree dropdown will contains.
If you open this tree view in popup, container will be popup body.
var tree = $("div.tree-inside-this-div").treeView({
    json: r,
    openAll: 0,
    noText: "Select...",
    change: function (value) {
        console.log(value);
    },
    value: "1.1.2.2.3.2",
    container: $(document.body)
});
To set specific value or to select desired tree node:
tree.value("100");
You can put a attribute named "selected": true to auto select node when create tree.

"children": [
  {
    "id": "1.1.2.2.3.2.4.1",
    "text": "Label - 4.1",
    "selected": true
  },
  {
    "id": "1.1.2.2.3.2.4.2",
    "text": "Label - 4.2"
  }
]

You can also convert select to stylish dropdown:
$(document.body).find("select").selectView();

You also can use this tree view for custom action menu using below command


$(document.body).find("select.action_menu").actionView({
    actionWidth: 140
});

And finally you download source code from here.

Friday, March 30, 2018

jquery select first x number of elements | Selecting the first “n” items with jQuery

Quick jQuery snippet to select first x number of elements. You can also use the jQuery .slice() function which can chop up element groups into a range for you with a combination of .get();
$("a").slice(0,20)
lso you can use lt pseudo selector: This matches the elements before the nth one (the nth element excluded). Numbering starts from 0
$(“a:lt(n)”)
Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead

What's the best way to retry an AJAX request on failure using jQuery | The best way to retry an AJAX request on failure using jQuery | jQuery AJAX retry

$.ajax({
    url: 'http://',
    type: 'POST',
    data: {},
    tryCount: 0,
    retryLimit: 3,
    success: function (response) {
        //do something
    },
    error: function (xhr, textStatus, errorThrown) {
        this.tryCount++;
        if (this.tryCount <= this.retryLimit) {
            //try again
            $.ajax(this);
            return;
        }
        if (xhr.status == 500) {
            //handle error
        }
        else {
            //handle error
        }
    }
});

Friday, January 12, 2018

Print the contents of specific DIV using javascript | jQuery Print Specific div Content demo | How to print selected div instead complete page JQuery | Print specific element using jquery | jQuery Plugin To Print Any Part Of Your Page - Print | Printing selective DOM elements on a page

HTML Element
<div>
  <h1>Header</h1>
  <div class="printable">
    <div>Body 1</div>
    <div class='c2'>Body 2</div>
    <div class='c2'><h1>Body 3 Inside Printable</h1></div>
  </div>

  <div style="margin-top:10px;border-top:1px solid;">&nbsp;</div>
  <button>Print</button>
</div>
Styling
body >div { margin:20px;border:2px solid;padding:7px; }
.printable .c2 { padding-left: 30px; }

@media print {
  @page { size: A4 landscape; padding:1cm; }
  body * { visibility: hidden; }
  .printable { 
    border:2px solid green;margin:0;left:0;top:0;position:absolute;
    width:calc(100% - 20px);padding:8px; 
  }
  .printable, .printable * { visibility: visible; }
}
JavaScript / JQuery part
document.title = "Need to print some specific area";
$("button").click(function() {
    var title = document.title;
    document.title = "Going to print";
    window.print();
    document.title = title;
});
And finally LIVE DEMO on JSFiddle

Friday, January 5, 2018

JQuery | Resizable Table Example | Table Column Resizing | Resizable Table Columns Using jQuery UI | Resizable table columns with jQuery

Core Part of Code I am Using to Resize Table Columns with Percentage Value

var table = $("#table-css-border-1"), tw = table.width();
table.find("tr").each(function() {
 var tr = $(this), c = 0;
  tr.find("td, th").each(function() {
   var te = $(this), ew = ((te.width() * 100) / tw);
   te.css("width", ew + "%").addClass("resizable column-" + (++c));
    te.data("cc", ".column-" + c);
    te.data("nc", ".column-" + (c + 1));
  });
 tr.find("td:last-child, th:last-child").removeClass("resizable");
});

var r = $("#table-css-border-1 .resizable"), mw = 50;
r.resizable({
  handles: 'e',
  maxWidth: mw,
  start: function(e, ui) {
   var td = $(ui.element);
    var nd = td.next() || td.previous();
    r.resizable( "option", "maxWidth", gw(td) + gw(nd) - mw);
    table.find(td.data("cc")).css("width", "");
    table.find(td.data("nc")).css("width", "");
  },
  stop: function(e, ui) {
   var td = $(ui.element);
    var nd = td.next() || td.previous();
    table.find(td.data("cc")).css("width", (((td.width()+5) * 100)/tw)+"%");
    table.find(td.data("nc")).css("width", ((nd.width() * 100)/tw)+"%");
  }
});
function gw(e) {
 return parseFloat(e.css("width").replace(/px/g, ''));
}



JSFiddle link to play

Saturday, December 2, 2017

jQuery.noConflict() | Avoiding Conflicts with Other Libraries


(function() {
    function loadJQuery() {
      var startingTime = new Date().getTime();
      var script = document.createElement("SCRIPT");
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
      script.type = 'text/javascript';
      script.onload = function() {
        var $j = jQuery.noConflict();
        jQuery = $;
        $(function() {
              var endingTime = new Date().getTime();
              var tookTime = endingTime - startingTime;
              window.alert("jQuery previous version=" + $.fn.jquery + ", version=" + $j.fn.jquery);
          });
      };
      document.getElementsByTagName("head")[0].appendChild(script);    
    }
    loadJQuery();
})();


Check here for JSFiddle

Load jQuery with Javascript and use jQuery | Load jQuery dynamically




(function() {
    function loadJQuery() {
      var startingTime = new Date().getTime();
      var script = document.createElement("SCRIPT");
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
      script.type = 'text/javascript';
      script.onload = function() {
        var $ = window.jQuery;
        $(function() {
              var endingTime = new Date().getTime();
              var tookTime = endingTime - startingTime;
              window.alert("jQuery is loaded, after " + tookTime + " milliseconds!, version=" + $.fn.jquery);
          });
      };
      document.getElementsByTagName("head")[0].appendChild(script);    
    }
    if (window.jQuery) {
     alert("JQuery loaded");
    }
    else {
     alert("JQuery not loaded");
      loadJQuery();
    }
})();


Check here for JSFiddle



Monday, November 20, 2017

Query UI Tabs: Changing selected tab | Remembering Active Tab in JQuery UI Tabs | Select last tab by default on Page load, jQuery Ui Tabs | how to set a tab active in jQuery ui tab on page load | Set Jquery ui active tab on page load/reload

Query UI Tabs: Changing selected tab | Remembering Active Tab in JQuery UI Tabs | Select last tab by default on Page load, jQuery Ui Tabs | how to set a tab active in jQuery ui tab on page load | Set Jquery ui active tab on page load/reload

I'm using a basic implementation of Jquery UI Tabs that are working fine but I want to set (or reset) the active tab dynamically based on a user action.



<div id="tabs">
    <ul>
        <li><a href="#tabs-1">Tab 1</a></li>
        <li><a href="#tabs-2">Tab 2</a></li>
        <li><a href="#tabs-3">Tab 3</a></li>
    </ul>
    <div id="tabs-1">
        First tab
    </div>
    <div id="tabs-2">
        Second tab
    </div>
    <div id="tabs-3">
        Third tab
    </div>
</div>
<div class='log'></div>



$(function ($) {
    $("#tabs").tabs({
        active: 1,
        create: function (event, ui) {
            var newIndex = ui.tab.parent().children().index(ui.tab);
            $(".log").prepend("<div>Created fired for child=" + newIndex + "</div>");
        },
        activate: function (event, ui) {
            //  Get future value
            var newIndex = ui.newTab.parent().children().index(ui.newTab);
            $(".log").prepend("<div>Activate fired for child=" + newIndex + "</div>");
        },
        beforeActivate: function (event, ui) {
            var newIndex = ui.newTab.parent().children().index(ui.newTab);
            $(".log").prepend("<div>Before activate fired for child=" + newIndex + "</div>");
        }
    });
});







You can manually active a tab using below code (2 is index of tab):
$("#tabs").tabs("option", "active", 2);