10
X

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’s .attr() Method

In jQuery, the attribute or .attr() method is used to set the attributes values of selected elements. It works similarly to the .css() method, except with .attr(), you're not setting or changing the style rules, but the inline HTML attributes of a particular element. Common HTML attributes that can be altered are width and height, which are often applied to image (img) tags. Check out the example below to see how the .attr() method works.

JAVASCRIPT:
  1. <br />
  2. $(".main-img).click(function(){ $(this).attr("width","350px"); })<br />

The code above will change the width of the .main-img class to 350px when that class is clicked. The syntax for setting or changing the attribute of an HTML element is putting the attribute in quotations as the first parameter of the method, and then your desired value in quotations as the second parameter of the method, like this: .attr("attribute","value").

If you want to use the .attr() method to set more than one value, the syntax changes a bit. The syntax actually becomes more similar to a CSS style rule, like this: .attr({attribute: value, attribute: value}). Here's what it looks like in action:

JAVASCRIPT:
  1. <br />
  2. $(".main-img).click(function(){ $(this).attr({width: 350px, height: 450px}); })<br />

jQuery’s .find() Method

In jQuery, the .find() method is used to return descendent elements of the selected element. Basically, you can use it when you want to apply jQuery to all the descendants of a particular element. You can also do this by selecting them by classes and ids, but sometimes if there are many different classes, ids, or elements involved, this way is the simplest.

To use it, place the parent element in the selector, and pass the descendant elements you'd like to apply your jQuery to through the parameters. See how it works below:

$(".main").find("p", "a").css("font-size", "18px");

So the code in the example above will change the font-size of all of the p and a elements that are children of the .main element to 18px.

You can use this method to return as many descendants as you like, just make sure you pass them through the .find() method, place them in quotations, and separate them with a comma.

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.