10
X

Intermediate

jQuery.parseJSON vs JSON.parse

JSON.parse() and jQuery.parseJSON(), both are used to parse a JSON string and returns resulting JavaScript value or object described by the string. jQuery.parseJSON() is available only when jQuery library is used where JSON.parse() is JavaScript’s standard built-in JSON object method. So the question is if jQuery library is used, then which one should be used or both gives same performance and result?

Well, the answer is that both are equal. As you know, jQuery’s library is written on top of JavaScript. So  jQuery.parseJSON() makes use of JSON.parse() internally. Here is the code of jQuery.parseJSON() method from jQuery 1.9.1 library. As you can see, it first checks if JSON.parse is supported or not. If supported, then it makes use of JSON.parse only. Otherwise, it tries to evaluate string data with new Function.

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}

if ( data === null ) {
return data;
}

if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {

return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
}

This was done as JSON.parse is natively available on some browsers, and jQuery is browser independent. So if JSON.parse is not available, then it falls back to jQuery implementation.

JSON.parse was not supported in old browsers like IE 7 and Safari 3, but over the period of time, browsers have also evolved. And now most of the browsers support JSON.parse. Therefore, the implementation of jQuery.parseJSON() is also changed after jQuery 2.0 release. Here is the code of new implementation from jQuery 2.2.4 library:

// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
return JSON.parse( data + "" );
};

And the big news is that with jQuery 3.0, jQuery.parseJSON is deprecated. So now to parse JSON objects, use the native JSON.parse method instead.

Snippets: Disable Scroll Using jQuery

Most developers probably wouldn’t want to disable scroll on their pages, but of course, there are always exceptions to any rule, and there are a number of reasons that scroll may need to be disabled. It could be for design or functionality reasons, or it could just be the result of a click event or some other trigger. If you’re looking to disable scroll, all you need to use is this small snippet of jQuery code:

$(document).bind("touchmove", function(event){
    event.preventDefault();
})

That’s all it takes! 3 little lines of code and scrolling will be completely disabled on your site. Add it to your next project to see how it works in action, but make sure you remember to remove it if you want scroll functionality to be accessible to your users.

jQuery: Enable Click Event for Some Anchor Elements

jQuery provides a very easy way to disable click events for any DOM element. And you can also disable click event for all Dom elements with few lines of code. But then what if you want to enable click event for some elements? For example, if a click event is disabled for all anchor elements, but there is a situation where you need to enable click event for one or more anchor elements. How do you implement it?  In this post you’ll see how to address this requirement.

HTML

For this demo, there are 2 anchor tags. One with a class “allowClick,” for which click should be allowed. For all other anchor tags, click should be disabled.

   <a href="#">Click Me!!!!</a>
   <a href="#">No Click</a>

jQuery

First, here is jQuery code to disable click event for all anchor tags. The following jQuery code will disable the click event for all anchor tags present in the page.

$('a').click(function(e) {
    console.log('Click Disabled!!!.');
   e.preventDefault();
 });

Now, how do we allow the click event for some anchor elements? To allow the click event, you need to attach click events again to that element. Following jQuery code will attach click event to all elements with css class named “allowClick”.

$('.allowClick').click(function(e) {
    console.log('allowClick Worked!!!.');
 });

So the complete jQuery code is:

$('a').click(function(e) {
    console.log('Click Disabled!!!.');
    e.preventDefault();
 });
$('.allowClick').click(function(e) {
    console.log('allowClick Worked!!!.');
 });

In this case when element with CssClass “allowClick” will be clicked, then first $(‘a’).click() would be called and then its own attached click event. Here is the screenshot:

Screen Shot 2016-11-14 at 12.00.41 PM

jQuery: Showing/Hiding HTML Elements Based on Scroll Position

Showing/hiding any HTML DOM element is a common scenario based on various business requirements. Since the time of SPA (single page application) is evolved, you will find that on scroll position of browser, new elements are shown and previous elements are hidden. There are tons of jQuery plugins available which can show/hide any HTML element based on the scroll position but it’s not advisable to use jQuery plugins for things which you can do with simple jQuery code. So in this post, let’s see how to show/hide any HTML element based on the scroll position in the browser window using jQuery.

First, we need to get the scroll position. Out of the box jQuery provides a function scrollTop() which gets the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.

HTML

For the demo, there are some empty div elements at the top and bottom so that scroll bar appears in the browser. And there are 2 div elements dvContent and dvContent2 which will be shown/hidden based on the scrollbar position.

<div style="height:100px;">
</div>
<div id="dvContent" style="height:100px;">
  your HTML content
  <br />your HTML content
  <br />your HTML content
  <br />your HTML content
  <br />
</div>

<div id="dvContent2" style="height:100px;">
  your HTML content 1
  <br /> your HTML content 2
  <br /> your HTML content 3
  <br /> your HTML content 4
  <br />
</div>
<div style="height:800px;">
</div>

jQuery

Here is the jQuery code, which first hides the dvContent2 and then binds the scroll event to window object. Within the scroll event, first check for scrollTop() function returned value. If it’s greater than or equal to 100, then hide the dvContent and show the dvContent2 div. And in the other part, do the opposite.

$(function() {
  $('#dvContent2').hide();
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll >= 100) {
      $('#dvContent').hide();
      $('#dvContent2').show();
    } else {
      $('#dvContent').show();
      $('#dvContent2').hide();
    }
  });
})

As you can see, it’s pretty easy to show/hide any DOM element based of the browsers scroll bar position.

Using Method Chaining in jQuery

When you use method chaining in jQuery, it ensures that you never have to use the same selector more than once. Over-using a selector can seriously slow down your code, as every time you call on a selector you’re forcing the browser to go looking for it. By combining or “chaining” multiple methods, you can seriously cut down on the amount of times you make your browser look for the same elements without having to set any variables.

Here’s an example of what your jQuery could look like before you employ method chaining:

$("#header").css('color', '#333");
 $("#header").addClass("bigger");
 $("#header").toggle();

To chain all of these methods so you only have to use the $(“#header”) selector once, you simply need to connect them using a period “.”:

$("#header").css('color', '#333").addClass("bigger").toggle();

Now, when whatever your event will be to trigger this code occurs, the header will change color, add the .bigger class and whatever CSS properties come along with it, and it will toggle from view — all while the browser only has to find the selector once, rather than three times. Method chaining is a great way to clean up your code, keep things concise, and make sure your code is running as quickly as it possibly can.

Create a Simple Back to Top Button with jQuery

We’ve all seen those handy little “back to top” buttons, the one that usually appear at the bottom of a page once a user starts scrolling that, when clicked, will smoothly return the page back to the top position.

Screen Shot 2016-08-29 at 4.37.50 PM

Insert the following snippet into your projects to add a back to top button to your own pages. The code works by having the button (in this case it’s the element with the class .back-to-top) initially hidden, with instructions to .fade-in() once the user has scrolled past 100px. Have fun styling your button any way you like!

$(document).ready(function(){
var $backToTop = $(".back-to-top");
/* this hides the back to top button when the page first loads */
$backToTop.hide();
/* now we need to write a function that makes the back to top button appear after the user has scrolled a certain amount */
$(window).on('scroll', function() {
 if ($(this).scrollTop() > 100) { /* back to top will appear after the user scrolls 100 pixels */
 $backToTop.fadeIn();
 } else {
 $backToTop.fadeOut();
 }
});
/* this function activates a smooth scroll to the top of the page when the back to top button is clicked */
$backToTop.on('click', function(e) {
 $("html, body").animate({scrollTop: 0}, 500);
});
})