PHP’s print_r() for JavaScript

PHP offers print_r() and var_dump() methods that can print the values of arrays and objects recursively with values indented so it’s easy to debug code. There’s no print_r for JavaScript but OpenJS has an equivalent function for dumping variables in a structured format.

JavaScript Trim Method

The trim() methods in JavaScript removes spaces and other whitespace characters from both ends of a string. It is supported in all modern browsers else you can add the trim() method to the String prototype object.

The \s represent whitespace characters while “\uFEFF” represents the zero-width no-break space.

Extract Name and Email Address from Gmail Header

The Gmail Extractor will soon let you extract both the name and the email address of the sender from the email message. Here’s a JavaScript regex that parses the name (if available) and the email address from the sender / to field of an email message.

The email addresses can be available in the email message header fields in multiple formats. If the name is present, the email is enclosed in angle brackets. There is also an alternate simple form, specified in RFC 2822 spec, where the email address appears alone, without the recipient’s name or the angle brackets. The regex takes care of them both.

How to Validate Date Input in JavaScript

A Date instance can be created in JavaScript by passing the date time string as the parameter in yyyy-mm-dd format as in Date(“2015-01-31″). There’s something important to note here though.

If you pass an invalid date string, the Date instance would still be created. For instance, “2015-02-30″ is not a valid date but the Date instance would still be created. The date will however be adjust to point to the next logical date and in this case, our Date will be set as “2015-03-02″.

Thus you’ll have to verify the month, year and day of a Date separately to detect an invalid date. A regex is not enough.

Export Phone Numbers and Profile Pictures from WhatsApp

The JavaScript bookmarklet for extracting WhatsApp Contacts traverses through the DOM of the WhatsApp Web client and gets the profile picture, the name and the phone number (with the country code) of all your WhatsApp contacts.

The list can be saved as a CSV file for importing into Google Contacts, you can send it to the printer or you can use download the entire web page to save the higher resolution profile pictures of your WhatsApp contacts on the desktop. You can manually upload these later to your Google Contacts.

Create the Loading Dots Animation with CSS & Javascript

If you happen to a click a link pointing to the Apple apps store on your desktop, the browser opens a temporary web page with a message saying “Connecting to the Mac App Store..” and then redirects to the actual page. It tries to open the Apps Store or iTunes software on your desktop and while the program loads, the dots in the message animate indicating that a task is in progress.

These dots are animated using simple CSS and JavaScript. It runs in forever loop and in every iteration, the number of dots is incremented by 1 and resets at 3. So it goes from 0, 1, 2 and then back to 0, 1, 2 and so on.

Show Trimmed Content in Gmail

The Gmail Bookmarklet will add a unique string to the email signature to prevent Gmail from trimming the content. The hex color code for the appended text is #444 so it will not be prominently displayed in Gmail.

Embed a Tweet with JavaScript Programmatically

You can embed any tweet on your website easily using the embed code from the Twitter website but a downside is you do not have any control over the embedded IFRAME widget. You can neither customize the style of elements nor can you hide elements (like the Follow button) that you do not want in the embedded tweet.

As an alternative, you can use JavaScript to embed tweets programmatically and here you will be able to decide how the elements are styled and which elements are displayed or stay hidden.

To get started, paste this snippet anywhere in your HTML web page and change the tweetID. You can cards option in the createTweet() method to “visible” and then the photos and cards in the tweet would be auto-expanded.

Scrape Twitter Data with JavaScript

You can use YQL and JavaScript to quickly scrape tweets from Twitter search results on the client side. The tweets are returned as JSON that can be easily parsed using regular expressions.

The advantage with this approach is that it requires no OAuth (authorization) and even old tweets can be returned when the search request is combined with the since: and until: search operators.

YQL allows 2000 requests / per hour / per IP so you are also unlikely to hit the usage limit.

Encode and Decode Strings with Base64 in JavaScript

Google Scripts offer the Utilities.base64Encode() and base64Decode() methods to easily encode and decode strings in base64 respectively. You can do Base64 encoding and decoding in plain Javascript as well. Here’s the un-minified code to help you understand what happens behind the scene.

Detect AdBlock with JavaScript

If you would like to know whether a visitor on your website is blocking Google AdSense and other online advertising networks or not, you can easily do that with the help of some JavaScript. Here are some approaches:

1. You can check for the existence of window.google_jobrunner after the page has finished loading. We are using setTimeout to take care of asynchronous Google AdSense that may not load immediately.

2. The other more popular approach is that you create a file called /ads.js in your server and inside that file, set a variable as false. AdBlockers routinely block JavaScript files that have *.ads* in the name and hence, the variable will not be set if the ad blocker is active.

Now put this somewhere inside the HTML of your main web page.

3. Here’s another option that works with the new Asynchronous Responsive Google Ads.

In the new format, the ads are inserted using the INS tag. The snippet checks for the length of the tags that are contained inside the INS tag. If it is 0, Google Ads were blocked and the user is shown a custom message.

We also need to set the CSS display property as block as AdBlock may be blocking ads with the “adsbygoogle” class by simply hiding them on the screen with CSS.

Convert HTML Content into Plain Text

Say you have an HTML snippet and you would like to extract the plain text from the snippet without any of the HTML tags. This may come handy when you are sending mail through a program that doesn’t support HTML Mail.

The easiest way would be to strip all the HTML tags using the replace() method of JavaScript. It finds all tags enclosed in angle brackets and replaces them with a space.

The problem with the above approach is that it may fail for malformed HTML or when the HTML content contains entities like dashes, ampersands and other punctuation codes. The workaround is simple though.

How to Use the Web Speech API in HTML5

The Voice Dictation app uses the Web Speech API to convert your spoken words into text. There’s a simple JavaScript API that lets you integrate Speech Recognition on any website.

The Web Speech API is currently implemented in Chrome and Firefox.

Create HTML Elements with JavaScript

You can create HTML elements directly with JavaScript /jQuery and also assign data attributes, CSS style, click handlers, classes and IDs to these elements through chaining.

Here’s an example.

Turn an Entire DIV into a Clickable Link

If you have been to a Pinterest like site that uses the grid masonry style layout, you may have noticed that one can hover over any region inside the box and its clickable.

A typical DIV is written using the following markup

There’s a outer DIV and it has elements like the title, description and a link. The requirement is that when someone hovers their mouse over the DIV, it should point to the hyperlink that’s contained inside the DIV.

This can be done in two ways – using CSS or using jQuery.

The CSS approach – Make the Whole DIV clickable

Here we assign an absolute position to the inner <a> tag such that it occupies the entire DIV and we also set the z-index property to 10 to position the link above all the other elements in the DIV. This is the easiest approach and the semantic structure is maintained.

jQuery – Make Div Clickable

Here we use jQuery to determine the hyperlink of the first a element inside the DIV and redirects the user to that link when the DIV is clicked.

The cursor properties of the DIV are sent to “pointer” on hover to indicate to the user that the DIV is clickable. Similarly, the text in the status bar is changed to the URL that the DIV is pointing to.

Image Fade on Hover Effect with jQuery

I am using the Pinterest style grid layout for Podcast Gallery and Zero Dollar Movies. When you hover your mouse over any image thumbnail, it fades with a slow transition and goes back to its original state as soon you move the mouse out.

Internally, the fade-in on mouse-over effect is achieved by changing the opacity parameter of the image which the slow speed is achieve using CSS3 transitions. Here’s the code:

Detect a Touch Screen with JavaScript

If your website includes features that should only be available to devices with a touch screen, or vice-versa where you would like certain features to be disabled on a touch device, JavaScript can help.

You need no external libraries like jQuery or Modernizr.

The following snippet will hide the element with ID as ‘touchOnly’ if the web page is viewed on a device that doesn’t have a touch screen. This should work on all desktop and mobile devices including iOS, Android, Opera, Chrome, IE, Safari and Windows Phone.

Microsoft has stated that starting with Internet Explorer 11, Microsoft vendor prefixed version of this property (msMaxTouchPoints) may be removed and recommends using MaxTouchPoints instead.

[*] MaxTouchPoints = The maximum number of supported touch points (for IE)

Find Videos with the YouTube Search API

The instant search feature at Zero Dollar Movies uses the YouTube data API to find free movies on the YouTube website.

When the user enters a search query, the script makes a request to the (YouTube data API) for search results. The resultset is returned in JSON format. The code uses YouTube API v2 and, while optional, it may be a good idea to include a developer key in the API requests.

Generate a YouTube Developer Key

You can go to the Google API console to create a developer key for your project. Go to and start a new project. Give your project a unique name and then choose APIs to turn on the YouTube Data API. Next create a new key under Public API access, set the type as Browser key and the website referrer as your website address (to prevent abuse).

YouTube Data API Quota Limits

YouTube Data API v3’s quota is 50,000,000 units per day. The quota cost of making a single search request to YouTube is just 2 units and thus a normal web application is unlikely to exceed the quota anytime soon.

You can also enable billing the Google Cloud console to further increase your quota.

Find on Page – Bookmarklet

This JavaScript bookmarklet will perform case-sensitive search in Google Chrome or any other browser include mobile Safari.

YouTube Player API for Partial Embeds

You can embed a part of YouTube video using the YouTube Player API. The API offers loadVideoById and cueVideoById function both of which allow you to specify a start and end time for the embedded video.

Embed YouTube Videos with JavaScript

This explains how you can embed YouTube videos using the Google+ approach – only the video thumbnail is loaded along with the page and the actual player loads when the user hits the play button.

HTML5 Speech Input with Voice Recognition

HTML5 support speech input (x-webkit-speech) and this has been implemented in the newer versions of Google Chrome. Dictation is an online speech recognition app that uses Google’s Chrome speech engine to help you convert your spoken words into text.

This piece of jQuery / JavaScript code powers the Dictation app.

How to Submit Forms in Background using JavaScript

When a user submits an HTML form, all the data entered into the form by the user is sent as either a GET or POST request to the URL specified in the “ACTION” attribute of FORM.

In the above example, an HTTP POST request is issued to the sendmail.php script on form submission. You can add target=”_blank” to the FORM tag to process the request in a new window.

However, if you would like to submit a FORM on the page in the background without directing the browser to another page (document.location.href changes on form submit), you have two options:

Option #1. You can either create an invisible IFRAME inside your HTML page and set that as a target for the Original FORM. This will submit the form but without reloading the parent window.

Option #2: There’s another method that allows you create custom payloads before submitting the form. Unlike the IFRAME based form submission, the following code makes a standard form submit request and thus your browser location will change and the current page will get added to the browser history. Credit: Rakesh Pai.

How to Check Required Fields on Form Submit [JavaScript]

Say you have an HTML form contain multiple fields – a mix of textarea, text input, radio button, drop downs (SELECT) and/or check boxes – and some of these fields are required. That is, if the user submits the forms, the browser should display an alert (or an inline message) saying that required fields are missing.

How do you check the submitted form for missing fields? There’s an easy way. Wrap all the required form fields in the HTML with the “ss-item-required” class as show below:

As you can see, the above form has four fields and except for the email address, all fields are required. Next we write a simple JavaScript function that will execute when the user submits the form.

The .serializeArray jQuery function will put all the filled form values into an Array. We are limiting this array to “required” fields only by using the find() function with the item selector.

Next, we iterate through all the fields in the array and if anyone is blank (or has no value), the user is alerted with a message box.

The last console.log will print the content of the form in the Console windows thus making it easy for you to debug input fields. Please note that this only check for missing fields but does not validate the user input.

Google AdSense JavaScript – Introduction

The Google AdSense Sandbox uses standard JavaScript code to display Google AdSense ads in various formats. The various parameters are passed through google_* variables and the ads are rendered through the google_ad_request_done function.

The following snippet explains the working of the Google AdSense code:

Screen Capture Web Pages with JavaScript

The following JavaScript code will help you convert any web URL into a PNG image from the command line. The script renders the page using Webkit, the same engine that’s used inside Google Chrome and Apple Safari browser. See demo at

Add Favicons to External Links – Bookmarklet

This little JavaScript bookmarklet will add favicons and some CSS styles to all external hyperlinks on a web page. The favicon images of a website are fetched using Google’s favicon generator that was originally part of Google Reader. And here are some more useful bookmarklets for your browser.

Geocoding Addresses with Google Maps API

The reverse geocoding feature of Google Maps API lets you convert latitude and longitude into a physical address. Here’s a snippet of code that implements address lookup in Google Maps using JavaScript.

Encrypting Data in JavaScript Using the SHA-1 Algorithm

Password Chameleon, the offline generator for site-specific passwords, uses the SHA-1 algorithm implemented in JavaScript to generate the hash (or the unique password).