Quick Summary of What's new in jQuery 3.0

Quick Summary of What's new in jQuery 3.0

jQuery 3.0 is the newest version of jQuery and it’s already out. There are many new features, bug fixes and deprecations of old methods. In this post, find a quick and short summary of some of the newest features and bug fixes.

  • For loop syntax changed
    jQuery 3.0 introduces new syntax for “for loop”. With this new syntax, you will get DOM element, instead of jQuery collection. So here you don’t need to use index to get the element as you are already having direct access to the element.

var $dvElements = $("div");
var i = 0;
for(var elm of $dvElements) {
   elm.addClass("dummy");
}
  • jQuery.Deferred is now Promises/A+ compatible
Deferreds have been updated for compatibility with Promises/A+ and ES2015 (a.k.a ES6) Promise. Use the new then and catch methods for Promises/A+ compliance.  
In jQuery 1.x and 2.x, an uncaught exception inside a callback function halts code execution. The thrown exception bubbles up until it is caught inside a try/catch or reaches window and triggers window.onerror. But with jQuery 3.0, any uncaught exception can be caught with in catch block. See below code.

$.ajax("/status")
   .then(function(data) {
      whoops();
   })
   .catch(function(arg) {
   });

  • New signature for jQuery.get() and jQuery.post()
Now you can set settings parameters for jQuery.get() orjQuery.post() like jQuery.ajax(). 

var settings = {
...
}

$.get(settings)
$.post(settings)

  • New method jQuery.escapeSelector()
The new jQuery.escapeSelector(selector) method takes a selector string and escapes any character that has a special meaning in a CSS selector. For example, an element on the page has an id of “abc.xyz” it cannot be selected with $("#abc.xyz") in prior version of jQuery. But with jQuery 3.0, it can be selected 
$("#" + $.escapeSelector("abc.xyz"));

  • :visible and :hidden Behavior change
jQuery 3.0 modifies the behavior of :visible and :hidden filters. Prior to jQuery 3.0, the version will not select elements with no content. For example, for following HTML

<div></div>
<br />

jQuery 1.x and 2.x will return count as 0, though these elements are visible. But with jQuery 3.0, things are changed. Elements will be considered :visible/:hidden if they have any layout boxes, or of zero width and/or height. For the above HTML, jQuery 3.0 will return count as 2.

  • Changes in .data()
There is also a change in the behavior of .data() with jQuery 3.0. It is now more align with new specification of Dataset API. Now, the property key name is transformed to camelCase. While in old version it was in lower case with dash (if exists in key name). For example,

<div data-foo-name="bar"></div>
Prior to jQuery 3, the property name is "foo-name" but with 3.0, it is "fooName". However if there are any digit present in the key name then it remain same as the previous version.
  • jQuery 3.0 runs in Strict mode
Now that most of the browsers supported by jQuery 3.0 have "use strict", jQuery is being built with this directive. Your code is not required to run in Strict Mode, so most existing code should not require any changes.

  • Cross-domain script requests must be declared
When making a request via jQuery.ajax() or jQuery.get() for a script outside your domain, you must now explicitly specify dataType: "script" in the options. This ensures the possibility of an attack where the remote site delivers non-script content but later decides to serve a script that has malicious intent.

  • width() and height()
jQuery 3.0 now returns decimal values for .width() and .height() methods. In previous version of jQuery, they return nearest value but that is in integer. For following HTML,

<div style="width:100px;">
  <div id="dvFirst">Some text..</div>
  <div id="dvSecond">Some text..</div>
  <div id="dvThird">Some text..</div>
</div>
</pre>
And below jQuery code,
<pre class="brush:javascript">
  $('#dvFirst').width();

will return 33 but with jQuery 3.0, returned value is 33.3333333. So you get more accurate results.
  • unwrap() Method
unwrap() method allows you to remove the parents of the matched elements from the DOM. But there was no way to unwrap based on certain conditions as it did not accept parameters earlier. With jQuery 3.0, you can pass a selector to it.
  • RequestAnimationFrame() for animation
jQuery 3.0 will use requestAnimationFrame() on platforms/browser which supports this property. This will ensure smooth animation and consume less CPU power.

  • load(), unload() AND error() methods are removed
jQuery 3.0 removes all above deprecated method. These methods were deprecated in jQuery 1.8 but still available to use. But now, they are removed.

  • bind(), unbind(), delegate() AND undelegate() are deprecated
jQuery 1.7 introduced .on() method to replace .bind(), .live() and .delegate(). And they encourage developers to use .on() method for better handling of binding the events to dynamic objects. But these methods are still available to use. But with jQuery 3.0, these methods are deprecated with the intention of removing them in future.

Converting Your Scripts Into a jQuery Plugin

Converting Your Scripts Into a jQuery Plugin
We feature a lot of plugins on this site, so chances are if you're looking for a particular type of plugin, you'll be able to find that here. Just in case, the following is some code that will help you convert your jQuery scripts into a plugin that can be used by other developers on other sites and projects. If you spend a lot of time writing a particular script to create a functionality, it's definitely worth it to convert that code into a plugin, either for your own future use, for the future use of others, or both.

The basic code to create a plugin is actually very straightforward. Really, all you have to do is create a $.fn object and extend it with your own custom function. Check out the code below:

(function($){ $.fn.yourCustomPluginName = function(){ // insert your script here return this; }; })(jQuery);

As you can see, it only takes a few extra lines of code to create your own unique jQuery plugin. When converting your own code into a plugin, make sure your code is clean, organized, and well documented (especially if you intend to make it available for the use of other developers).

8 Handy jQuery Code Snippets For Handling Images

8 Handy jQuery Code Snippets For Handling Images

Here are 8 handy jQuery code snippets for handling images. These snippets show how to handle broken images, showing loading images when the main image is downloading, preloading images, adding hyperlinks to your images, and changing images extensions.

1. Hide Broken Images

If the image path is changed then the image will not load. So you can hide such images from your webpage using following jQuery code.

<pre class="brush:javascript">
$(document).ready(function() {
  $('img').error(function() {
    $(this).hide();
  });
});
</pre>

2. Remove Broken Images

You can also remove such images from DOM using following code:

<pre class="brush:javascript">
$(document).ready(function() {
  $('img').error(function() {
    $(this).remove();
  });
});
</pre>

3. Replace Broken Image URL with Other Image URL

And if you don’t wish to hide/remove the images and want to replace with any other image source, then use following code. This will set the src attribute of image a to newer path.

<pre class="brush:javascript">
$(document).ready(function() {
  $('img').error(function() {
    $(this).src = "/images/noimage.gif";
    $(this).onerror = "";
  });
});
</pre>

4. Add Hyperlinks to All Images

If you want to add hyperlinks to images then use below code:

<pre class="brush:javascript">
$(document).ready(function() {
  $('img').each(function ()
  {
     var currentImage = $(this);
     currentImage.wrap("<a href='" + currentImage.attr("src") + "' </a>");
  });
});</pre>

5. Show Loading Image when Main Image is Loading

If you have large images on your websites and that take time to load, then you can display a small loading image until the time image is fully loaded. The below jQuery code will display a single loading image for all large images.

<pre class="brush:javascript">
$(document).ready(function(){
   $('#imgLoader').show();
   var totalImages = $(".imgClass").length;
   var iLoaded = 0;
   $(".imgClass").each(function ()
   {
     $(this).bind("load", function()
     {
       iLoaded++;
       if(iLoaded == totalImages)
       {
          $('#imgLoader').hide();
       }
       $(this).attr('src', $(this).attr("src"));
    });
  });
});
<pre>

6. Change All Image Extensions from PNG to JPG

If the extensions of all your images are changed (for any reason) then changing extension in source code will be a nightmare. To change the extension of all your images from png to jpg, use following code.

<pre class="brush:javascript">
$(document).ready(function(){
  $('img[src$=".png"]').each(function(index,element) {
    element.src = element.src.replace('.png,'.jpg);
  });
});
</pre>

7. Preloading Images

The jQuery code below will preload the images which you may need to use later on.

<pre class="brush:javascript">
$.preloadImages = function() {
  for (var i = 0; i < arguments.length; i++) {
    $("<img />").attr("src", arguments[i]);
  }
}
$(document).ready(function() {
  $.preloadImages("hoverimage1.jpg", "hoverimage2.jpg");
});
</pre>

8. Resizing Images Proportionally 

The jQuery code below will resize the image based on resolution. Here the max_size variable is set to the maximum height or width.

<pre class="brush:javascript">
$("img").each(function(i) {
  if ($(this).height() > $(this).width()) {
    var h = max_size;
    var w = Math.ceil($(this).width() / $(this).height() * max_size);
  } else {
    var w = max_size;
    var h = Math.ceil($(this).height() / $(this).width() * max_size);
  }
  $(this).css({ height: h, width: w });
});
</pre>

12 jQuery Image Cropping Plugins

In this post, find a compiled list of 12 jQuery image crop or resize plugins. These plugins comes with easy to use interfaces to crop images, and they also support responsive cropping, image uploading and drag and drop of selected area for cropping, live preview and touch gestures.



Cropper is a jQuery plugin for image cropping which supports live previews and custom aspect ratios. The plugin displays a resizable grid on top of an image, allowing to visually resize and crop the image.



Responsive Cropper is a jQuery plugin that lets you select an area from an image and prepare crop information to send it to the server. You don't need to trigger any event to update the crop area when an image is resized: this plugin is fully responsive. Crop area uses percentages to guarantee full responsiveness, while crop data is stored separately in absolute values.

3. CropIt


CropIt is a jQuery plugin for image cropping and zooming. It loads images locally via FileReader, and crops them using canvas. It works on desktop and mobile with touch support.



Cropbox is a lightweight jQuery image cropping plugin that creates a viewport around a given image allowing to move, zoom, resize and crop an image.



Select Areas is a jQuery plugin that let you select multiple areas of an image, move them and resize them.



easyCrop is a jQuery plugin used to effectively resize and crop an image. It doesn't allow the user to crop the image but based on the settings it displays the cropped image on screen.




imgFitter is a lightweight jQuery plugin used to resize and crop images dynamically. This allows images to fit any web layout while maintaining aspect ratio & centering.



Simple Cropper is a jQuery plugin which gives you ability to add cropping functionality to your web application. It uses HTML5 canvas and CSS3 to create cropped images, so it only works on latest browsers.



Drag'n'Crop is a jQuery plugin for cropping images by dragging, inspired by Facebook cover photo. It aims to be minimalistic and very easy to use for the end-user. It allows to crop the image only in one dimension (no zooming!)

10. Croppic


Croppic is an image cropping jQuery plugin that will satisfy your needs and much more. It is supported on all current browsers, such as Chrome, Firefox, IE, Safari and Opera.



Smartcrop.js implements an algorithm to find good crops for images. It can be used in the browser, in node or via a CLI. It uses fairly simple image processing and a few rules to attempt to create better crops of images.



PhotoClip is a jQuery image cropping plugin that allows to zoom, rotate and crop your image with support for touch gestures.



10 jQuery Plugins for EU Cookie Law Notification Popup


These days almost all the websites are using cookies to store information in your browser. And as per the EU cookie law, it is advisable to let your user know that your website is creating cookie. In this post, find a complied list of 10 lightweight and customizable jQuery plugins to display cookie law notification. These plugins allows you to display notification on top of the page or on bottom of the page.


herbyCookie is a simple, customizable jQuery plugin that displays an animated EU cookie disclaimer bar at the bottom of the web page and stores the 'Accept' state in the local storage using HTML5 web storage API.


A jQuery based EU Cookie Law Notification Plug-in for alerting the users about the use of cookies on your website that help you comply with the EU Cookie Law.


Qookies is a jQuery plugin that displays your cookies disclaimer in a popup window to make your website comply with the EU cookie law.


Cookie Disclaimer is a lightweight jQuery plugin which loads a disclaimer bar where you can show some custom text and buttons. You can choose style, buttons classes and id, cookie expire time, cookie name and more. This plugin provide also some useful methods and ready to use buttons for several uses.


CookieBanner is a jQuery plugin that displays customizable and dismissible EU Cookie Law Notice on your web page.


Cookies Message is a really simple and fully customizable jQuery plugin to easily show the EU Cookies Law banner on the website. It is responsive and supports custom cookie expire time to remember the user's choice.


An easy-to-install jQuery plugin to create EU Cookie Law popups. It supports multiple layouts out of the box. Works well with Bootstrap 3. Easy to customize markup and CSS.


Divas Cookies is EU Cookie Policy Banner generator as a jQuery plugin. The quickest and most elegant solution to be compliant with EU Cookie Policy. Easily and fully customizable to get the look & feel of any website.


cookieBar is a simple, lightweight jQuery plugin for creating a notification bar that is dismissible, and  the dismiss is saved by cookie. Perfect for implementing the new EU cookie law!


CookieCuttr is a tailorable jQuery plugin to deal with the EU Cookie Law.