getButterfly Logo getButterfly

How to declare a global variable inside a jQuery function

A jQuery (or Javascript) global variable is a variable with global scope, meaning that it is visible and accessible throughout the program, unless shadowed. This article deals with a problem I used to bang my head about the other day.

jQuery (or Javascript) global variables

I needed to declare a global variable inside a jQuery function (it works with regular JavaScript, too), and read it inside another function. If the first function isn’t called/initiated, the second function doesn’t know the value of the global variable.

For example, this function sets the sort order of a column of a table, nothing really interesting:

function clickMe(sortOrder) {
    sortOrderNew = sortOrder;

When the function is executed, a global Javascript variable is set. Notice there is no var in the declaration.

This line:

var sortOrderNew = sortOrder;

would set a local variable inside the said function.

Now, a second function needs this global variable. If it is set, it will automatically pick it up, if not, it will set a local variable with a fallback value:

function chipPaginate(page) {
    if (typeof sortOrderNew === 'undefined')
        var sortOrder = 3;

    if (typeof sortOrderNew !== 'undefined')
        var sortOrder = sortOrderNew;


Notice I’m doing some checks to see if sortOrderNew is defined. If not, it will assign it the value of 3 (it makes sense inside my function). Again, notice I’m using var in front of my variables, to set them locally.

Global variables conclusion

if (typeof myVariable === 'undefined') checks if myVariable is defined or not.

var myVariable = 5;

Omitting var will make myVariable global (i.e. readable among functions and available to other code).

Generate a unique string based on timestamp

This small function generates a unique string and, optionally, adds a prefix:

function generateUniqueString() {
    var out = '',
        ts = String(new Date().getTime()),
        i = 0;

    for (i=0; i<ts.length; i+=2) {
        out += Number(ts.substr(i, 2)).toString(36);

    return ('prefix' + out);

JSFiddle Demo

Hint: Replace the prefix with another unique string and you will get a stronger unique string. Note that in some very rare instances, 1 in cases with high-traffic web apps, the string might be identical.

Demistifying JavaScript history.back() and history.go() methods

One of my clients needed his online shop customers to be able to go back several steps with one click and keep the current session variables in memory. The obvious solution was the browser’s back button. But I couldn’t instruct the customer to click it one time or 3 times or 5 times. So, I chose to add a link with a JavaScript history object.

back() – Go to the previous URL entry in the history list. This does the same thing as the browser’s back button.

forward() – Go to the next URL entry in the history list. This does the same thing as the browser’s forward button. This is only effective when there is a next document in the history list. The back function or browser’s back button must have previously been used for this function to work.

go(position) – This function will accept an integer or a string. If an integer is used, the browser will go forward or back (if the value is negative) the number of specified pages in the history object (if the requested entry exists).

<a href="javascript:history.back()">Go back</a>


<a href="javascript:history.go(-3)">Go back to step X</a>

The back() and go() methods are supported in all major browsers.

History is one of the subobjects of Windows, and an interface to the history stored by your browser. Properties and methods apply to the object history of windows or to each frame in the window.

history.go(0) acts like pressing the reload button.

The length property returns the number of URLs in the history list.

Note: Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1.

console.log("Number of URLs in history list: " + history.length);

Character counter for text areas

I’ve been searching for a character counter for one of my link directories. The description field is supposed to hold about 400 characters. More than that looks like spam.

Here’s the solution I have come up with:

1. Feedback message

function txtshow(txt2show) {
    var viewer = document.getElementById('txtmsg');

    viewer.innerHTML = txt2show;

function keyup(what) {
    var maxKeys = 50;
    var str = new String(what.value);
    var len = str.length;
    var showstr = len + " characters of " + maxKeys + " recommended";

    if (len > maxKeys) {
        showstr += '<br>Some information will be lost, please revise your entry';


The form with the text area and the feedback container:

      <textarea cols="40" rows="5" onkeyup="keyup(this);"></textarea>

<div id="txtmsg">0 characters of 50 recommended</div>

2. Simple message

function textCounter(textarea, counterID, maxLen) {
    cnt = document.getElementById(counterID);
    if (textarea.value.length > maxLen) {
        textarea.value = textarea.value.substring(0, maxLen);
    cnt.innerHTML = maxLen - textarea.value.length;

The form with the text area:

    <textarea name="text_area" cols="50" rows="5" onkeyup="textCounter(this, 'count_display', 3500);" onblur="textCounter(this, 'count_display', 3500);"></textarea>

And the message:

<span id="count_display">3500</span> characters remaining.

3. Multiple text areas

function textCounter(field,cntfield,maxlimit) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
    } else {
        cntfield.value = maxlimit - field.value.length;

And the form:

<form name="myForm">
    <textarea name="message1" cols="28" rows="5" onkeydown="textCounter(document.myForm.message1, document.myForm.remLen1, 125);" onkeyup="textCounter(document.myForm.message1, document.myForm.remLen1, 125);"></textarea>
    <input readonly="readonly" type="text" name="remLen1" size="3" maxlength="3" value="125"> characters left
    <textarea name="message2" cols="28" rows="5" onkeydown="textCounter(document.myForm.message2, document.myForm.remLen2, 125);" onkeyup="textCounter(document.myForm.message2, document.myForm.remLen2, 125);"></textarea>
    <input readonly="readonly" type="text" name="remLen2" size="3" maxlength="3" value="125"> characters left

That’s all. Remember to place the JavaScript code in <head> section or, better, in an external file.

JavaScript terminal

Today’s tutorial is about creating a terminal screen together with lime terminal characters in JavaScript.

Let’s start with the CSS:

textarea {
    background-color: #000000;
    color: #14FC03;
    border: 1px solid #111;

JavaScript is next:

var tl=new Array(
    "Initializing script",
    "Activating engine",
    "Running queries...",
    "Throwing errors...",
    "Catching errors",
var speed = 60,
    str_length = tl[0].length,

function type_text() {
    contents = '';
    row = Math.max(0, index-7);
    while (row<index)
        contents += tl[row++] + '\r\n';
    document.forms[0].elements[0].value = contents + tl[index].substring(0, text_pos) + "_";
    if (text_pos++==str_length) {
        if (index!=tl.length) {
            str_length = tl[index].length;
            setTimeout("type_text()", 1500);

And, finally, the HTML:

    <div align="center">
        <textarea rows="10" cols="80" wrap="soft"></textarea>

Random JavaScript tutorials

I needed some structural updates for a site, and among them, I added some JavaScript snippets. I will show you 3 of them in this article.

The simplest, most lightweight clock ever written in JavaScript

1. Use this JavaScript code where you want the clock to appear:

var now=new Date();
console.log(now.getDate() + ' ' + "JanFebMarAprMayJunJulAugSepOctNovDec".substr(now.getMonth()*3,3)+', '+now.getFullYear());

Form field hints using a bit of CSS

1. Add this CSS code to your document:

dl {
    position: relative;
    width: 350px;
dt {
    clear: both;
    float: left;
    width: 130px;
    padding: 4px 0 2px 0;
    text-align: left;
dd {
    float: left;
    width: 200px;
    margin: 0 0 8px 0;
    padding-left: 6px;
.hint {
    display: none;
    position: absolute;
    right: -250px;
    width: 200px;
    margin-top: -4px;
    border: 1px solid #c93;
    padding: 10px 12px;
    background-color: #ffc;
.hint .hint-pointer {
    position: absolute;
    left: -10px;
    top: 5px;
    width: 10px;
    height: 19px;
    background: url(_images/pointer.gif) left top no-repeat;

2. Add this JavaScript code to your document:

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {

function prepareInputsForHints() {
    var inputs = document.getElementsByTagName("input");
    for (var i=0; i<inputs.length; i++) {
        // test to see if the hint span exists first
        if (inputs[i].parentNode.getElementsByTagName("span")[0]) {
            // the span exists! on focus, show the hint
            inputs[i].onfocus = function () {
                this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
            // when the cursor moves away from the field, hide the hint
            inputs[i].onblur = function () {
                this.parentNode.getElementsByTagName("span")[0].style.display = "none";
    // repeat the same tests as above for selects
    var selects = document.getElementsByTagName("select");
    for (var k=0; k<selects.length; k++) {
        if (selects[k].parentNode.getElementsByTagName("span")[0]) {
            selects[k].onfocus = function () {
                this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
            selects[k].onblur = function () {
                this.parentNode.getElementsByTagName("span")[0].style.display = "none";

3. Add this HTML code to your document:

    <dt><label for="firstname">First Name:</label></dt>
        <input name="firstname" id="firstname" type="text">
        <span class="hint">This is your firstname.<span class="hint-pointer"> </span></span>
    <dt><label for="lastname">Last Name:</label></dt>
        <input name="lastname" id="lastname" type="text" />
        <span class="hint">This is your last/family name.<span class="hint-pointer"> </span></span>
    <dt><label for="email">Email:</label></dt>
        <input name="email" id="email" type="text" />
        <span class="hint">This is your regular e-mail address.<span class="hint-pointer"> </span></span>
    <dt><label for="year">Birth Year:</label></dt>
        <select id="year" name="year">
            <option value="">Year</option>
            <option value="2007">2007</option>
            <option value="2006">2006</option>
            <option value="2005">2005</option>
            <option value="2004">2004</option>
            <option value="2003">2003</option>
        <span class="hint">This is your birth year.<span class="hint-pointer"> </span></span>
    <dt><label for="username">Username:</label></dt>
        <input name="username" id="username" type="text" />
        <span class="hint">This is your username/nickname (5 to 9 characters).<span class="hint-pointer"> </span></span>
    <dt><label for="password">Password:</label></dt>
        <input name="password" id="password" type="password" />
        <span class="hint">This is your secret password (5 to 9 characters).<span class="hint-pointer"> </span></span>
    <dt class="button"> </dt>
    <dd class="button">
        <input type="submit" class="button" value="Submit" />

Show/Hide switch function for an HTML element (DIV)

1. Place this code snippet in the HEAD element:

#mylayer {
    visibility: hidden;
    width: 400px;
    height: 370px;
function ShowHide(id) {
    obj = document.getElementsByTagName("div");
    if (obj[id].style.visibility == 'visible') {
        obj[id].style.visibility = 'hidden';
    } else {
        obj[id].style.visibility = 'visible';

2. Place this code snippet in the BODY element:

<a href="javascript:ShowHide('mylayer')">Show/Hide DIV switch</a>
<div id="mylayer">This is dummy content this is dummy content this is dummy content this is dummy content this is dummy content this is dummy content</div>

JavaScript centered popup window

This tutorial is about JavaScript popups and how to show a window in the center of the screen and focus on it. The trick is easy and the containing function is small. Here is the JavaScript code:

function window_popup(content, x, y, title) {
    var thisWindow;
    thisWindow =, title, "width="+x+", height="+y+", scrollbars=auto, screenX=0, screenY=0, toolbar=no, location=no, menubar=no");

And here is the caller function:

<a href="#" onclick="window_popup('mypage.html', 400, 300, 'mypage')">Open My Page</a>

Remember to quote the page name and title, otherwise the script will generate an error. Popup window attributes can be changed in the second line of the function

"scrollbars=auto, screenX=0, screenY=0, toolbar=no, location=no, menubar=no"

depending on what the role of the window is.

Funnel page load optimisation snippet

Here’s a quick snippet to preload the next step in a theoretical funnel/workflow:


* Preconnect/Prefetch/Prerender in HTML5
if (stripos(getPageUrl(), 'funnel/step-one') !== false) {
    // Firefox
    echo '<link rel="prefetch" href="' . str_replace('funnel/step-one', 'funnel/step-two', getPageUrl()) . '">';
    // Chrome
    echo '<link rel="prerender" href="' . str_replace('funnel/step-one', 'funnel/step-two', getPageUrl()) . '">';


 * Preconnect/Prefetch/Prerender in JS
function preconnectTo(url) {
    var hint = document.createElement('link');
    hint.rel = 'preconnect';
    hint.href = url;

// Usage
if (window.location.href.indexOf('funnel/step-one') > -1) {
    preconnectTo(window.location.href.replace('funnel/step-one', 'funnel/step-two'));

// Usage (alternative)
if (/step-one/.test(self.location.href)) {
    preconnectTo(self.location.href.replace('funnel/step-one', 'funnel/step-two'));

Numerical integration using JavaScript


  • Use * to indicate multiplication: Type 4*x for 4x;
  • Use ^ to indicate powers: Type 4*x^3 for 4×3; 12*x^-6 for 12x?6.
  • Use parentheses to delimit the argument of a function; i.e., type sin(x) rather than sin x.
  • Use parentheses to define the scope of an operation: For example, type 4*x*(x^2+1)^3 for 4x(x2+1)3; 4^(2*x+1) for 42x+1; (sin(x))^2 for (sin(x))2.
  • Do not type sin^2(x) for sin2(x), type (sin(x))^2 instead.
  • Do not use brackets [ ] or braces { }, use only parentheses to delimit a mathematics expression.
  • Functions you may use:

Trig: sin, cos, tan, cot, sec, csc;

Inverse Trig: asin, acos, atan;

Log/exponential: ln (natural log), or use log; exp, the natural exponential; Note: You can also enter the natural exponential exp(x) as e^x for ex.

Misc: sqrt, usage sqrt(x) for ?x (or, use exponential notation: x^(1/2)).

Copy web page content using innerHTML

I need to extract some data from a web page and place it on a fishing site. The source web page is updated frequently, and I don’t have the necessary time to update it. So, I’ll use the Javascript innerHTML function.

First of all, I should identify the element I’m trying to copy, let’s say a div with the #info ID:

<div id="info">
This information updates daily.

The next step is to include the source web page as an iframe with width and height equal to 0:

<iframe name="thief" width="0" height="0" frameborder="0" src="source.html"></iframe>

The final code should read from the IFRAME and display the content on the destination page, in a specially created div:

<div id="destination">
This content will be replaced.
// this script will copy the ontent of the 'info' div into the 'thief' div in the destination page
parent.document.all('thief').innerHTML = document.all('info').innerHTML;

Interactive panels with lightbox and email overlays

Interactive Panels

I’d like to share one of my recent creations, CSS/JS interactive panels. Each panel contains an image, content and two call-to-action buttons. In addition, there is a lightbox link opening a second image. Each call-to-action button opens a transparent overlay with an email form. The panels use pure JavaScript and FontAwesome. See code and demo.

JavaScript bookmarklets collection

Bookmarklet 1: Show Password

A simple JavaScript snippet can be used to view passwords in web browsers. To use the code, open your web browser and open the webpage for which the password is hidden in asterisks.

Use the Show Password bookmarklet to instantly view hidden passwords at the click of a button.

Create a new bookmark and add the code below:

javascript: var p=r(); function r(){var g=0;var x=false;var x=z(document.forms);g=g+1;var w=window.frames;for(var k=0;k<w.length;k++) {var x = ((x) || (z(w[k].document.forms)));g=g+1;}if (!x) alert('Password not found in ' + g + ' forms');}function z(f){var b=false;for(var i=0;i<f.length;i++) {var e=f[i].elements;for(var j=0;j<e.length;j++) {if (h(e[j])) {b=true}}}return b;}function h(ej){var s='';if (ej.type=='password'){s=ej.value;if (s!=''){prompt('Password found ', s)}else{alert('Password is blank')}return true;}}

Bookmarklet 2: Show Coordinates

Google Maps does not offer a menu option for obtaining the coordinates – latitude and longitude – of a location. However, you can use another bookmarklet to extract the coordinates.

  1. Find the location for which you would like to obtain coordinates in Google Maps.
  2. Right click on your chosen location, and select “center map here.”
  3. Click on the Show Coordinates Bookmark.

This will activate a small pop-up window that will show the coordinates for the centered location in decimal format. You may copy and paste these coordinates wherever needed.

Create a new bookmark and add the code below:


Bookmarklet 3: Fun 3D Browser

This bookmarklet will turn the current page into a 3D parallax-enhanced page.

Create a new bookmark and add the code below:

javascript:if(!window.ThreeDit){ThreeDit=function(a,b){function G(a){p=a.clientX+g.scrollLeft;q=a.clientY+g.scrollTop}function F(){var a=g.scrollLeft-t;var b=g.scrollTop-u;p=v=g.scrollLeft+r;q=w=g.scrollTop+s;n+=a;o+=b;x=v+l.clientLeft-e.pageXOffset;y=w+l.clientTop-e.pageYOffset;t=g.scrollLeft;u=g.scrollTop}function E(){r=e.innerWidth/2;s=e.innerHeight/2;p=v=g.scrollLeft+r;q=w=g.scrollTop+s;x=v+l.clientLeft-e.pageXOffset;y=w+l.clientTop-e.pageYOffset}function D(){n+=(p-n)*.05;o+=(q-o)*.05;var a=(n-v)/r*5;var b=-(o-w)/s*5;for(var e=0;e<d.length;e++){var f=d[e].node;var g=f;var h=0;var k=0;var l=d[e].z;[i]=x-h+"px "+(y-k)+"px";[j]="rotateY("+a+"deg) rotateX("+b+"deg)translate3d(0px,0px, "+l*c.zDepth+"px)"}}function C(){var a;for(var b=0;b<d.length;b++){d[b][j]="none"}delete d;d=[];A(g,0);d.push({node:g,z:0});d.sort(function h(a,b){return a.z-b.z});var c=0;var e=[c];d[0].z=c;for(var b=1;b<d.length;b++){e.push(c=d[b].z==d[b-1].z?c:c+1)}var f=e[e.length-1];for(var b=0;b<d.length;b++){d[b].z=e[b]/f}}function B(a){c.perspective=a;k[h+"Perspective"]=c.perspective+"px"}function A(a,b,e){if(d.length>=c.maxElems-1)return;if(!e&&a.tagName=="DIV"&&a.childNodes.length>0){d.push({node:a,z:b})}for(var f=0;f<a.childNodes.length;f++){A(a.childNodes[f],b+1,a.childNodes.length<2)}}function z(a){f=a;g=f.body;h="webkitTransform"in"webkit":"MozTransform"in"Moz":null;i=h+"TransformOrigin";j=h+"Transform";l=f.documentElement;;m=e.getComputedStyle;t=g.scrollLeft;u=g.scrollTop;k[h+"Perspective"]=c.perspective+"px";k.backgroundImage=m(g).getPropertyValue("background-image");k.backgroundColor=m(g).getPropertyValue("background-color");C();if(!c.initialized){E();n=p;o=q;e.addEventListener("resize",E);e.addEventListener("scroll",F);f.addEventListener("mousemove",G);setInterval(D,1e3/60)}c.initialized=true}var c={zDepth:300,maxElems:100,perspective:500,initialized:false};var d=[];var e=a;var f=b;var g;var h;var i;var j;var k;var l;var m;var n;var o;var p;var q;var r;var s;var t;var u;var v;var w;var x;var y;c.init=z;c.recollectElems=C;c.render=D;c.changePerspective=B;return c}(window,document);ThreeDit.init(document);}else{ThreeDit.recollectElems();}

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

20 thoughts on “JavaScript

  1. Well, your solution is scriptic, however my example is browser-based. The popup window is a physical one, while your example is JavaScript based.

    I guess both are 100% cross-browser compatible.

  2. Hi, how cross-browser compatible is this solution? And does it put it in the centre of the window, regardless of vertical scroll position?

    I’ve struggled a bit with this, and thought I might just use a solution like lightwindow.


  3. Hi,

    I was looking for a way to do pop up windows in wordpress. Do you know if your code will work in the wordpress HTML post section? I’ve been having difficulty making any type of javascript work in WP.


  4. It should work like a charm, by putting the JavaScript code into a separate .js file, include it in the header (use correct path specification), and then use my example links.

    Although I would recommend using a LightBox plugin for WordPress which has the ability to load images, HTML, iframes, AJAX content, videos, DIVs (actually these are HTML). I did not use LightBox, but you should be able to find some discussions on it on forums.

  5. I don’t understand – are these native functions of javascript, or are you discussing some framework or some such?

  6. No, it’s just examples on how to use mathematical functions. I am working on some JavaScript game and I’m using mathematical calculations. Here are some examples of mistakes, I’ve run into, and how to use parentheses, groups, and delimitations.

  7. Ah, ok – I got confused when you said, ‘The only variable used is x; do not enter any other undefined symbols into your answer’ – do you mean you can use x without defining it?

  8. No. You should define ‘x’ first. The formulas will calculate different results (based on what you need), based on the value of ‘x’.

  9. Do you know if Google’s bot will see the link you want to pop up and index it?

    I’m worried that when Google sees href=”#”, it will stop there and not see what is located on mypage.html

  10. No, Google won’t see the pop-up, unless you use this:

    < a href = "linkhere.html" onclick = "popup stuff here; return false;" >bla bla< / a >

  11. I am feeling pretty slow here…cant seem to make this work. Where do you refernce the “destination” id in the code?

  12. The “destination” id should be a placeholder for the data you want copied.

    For example if you want to copy a sentence from another page on page x.html, you place the “destination” id div into x.html. Got it?

  13. Search Engines Parser is enormously fast, 100% automatic search engine results extractor you were dreaming about for many times. Search Engines Parser can extract results from all search engines at the same time, parse titles, descriptions and links automatically. You can specify which search engine(s) to use and what kind of data to parse. Search Engines Parser can output results to screen, export to MySQL database and write to CSV file.

  14. Ba frate ai explicat k curu aici , nu merge de nicio culoare ce povestesti tu pe aici

  15. @Raulz: mie mi-a mers, ai gresit tu ceva. Incerci local sau de pe net?

  16. this opens a popup, but also opens the popup in the the main window.

    does not work. confirmed.

  17. @Derrick: Try replacing the ‘#’ with ‘javascript:return false’.

    @Carlos: Again, you shouldn’t place content you want indexed by Google in popups.

  18. I used your snippets in a plugin I did for WordPress to open an image when a link is clicked on in the sidebar. It works great in Firefox and Google Chrome but for the life of me I can’t get it to work in IE (I have version 8 and have popups allowed). When I click on the link in IE I just get an “error on page” message at the bottom of the browser.

    Any ideas?

    1. Well, you should double click on that error icon and tell me what it says.

      Or, send me a copy of your plugin.

      Anyway, IE is not really supported, be it version 6 or 8.

Leave a Reply

Your email address will not be published. Required fields are marked *