Category Archives: Javascript - Page 2

Code of the day: Check to see if a element has a event.

// hasEvent checks to see if a element contains a event.
// @requires jQuery 1.3.2+
// @params el: string, jQuery object, node element.
// @params eventName: string, name of the event.
// @returns boolean
var hasEvent = function( el, eventName ){
	if( !$( el ).length || !$( el ).data( 'events' ) ){
		return false;
	}
	return !!$( el ).data( 'events' )[ eventName ];
};

Demo: (requires firebug or google chrome)

var el = $( '<div/>' ).click( $.noop );
console.clear();
console.log( hasEvent( el, 'click' ) );// returns true;
 
console.log( hasEvent( el, 'focusNow' ) );// returns false;
el.bind( 'focusNow', $.noop );
console.log( hasEvent( el, 'focusNow' ) );// returns true;
 
console.log( hasEvent( document.body, 'onload' ) );// returns false;
$(document.body).bind( 'onload', $.noop );
console.log( hasEvent( document.body, 'onload' ) );// returns true;

jQuizMe Example: Simple Math Quiz

Here’s an example of jQuizMe.
Goal: Make a quiz for Addition, Subtraction and Multiplication for two digit numbers.

Steps:

  1. Make a random number generator.
  2. Make a function to form a question and answers.
  3. Form the quiz.
  4. Call jQuizMe

Step 1:
I wrote a random number generator in javascript here.

1
2
3
4
var getRandomNum = function( i, decLen ){
	var powOf10s = Math.pow( 10, decLen || 0 );
	return i ?  Math.floor( powOf10s * Math.random() * i ) / powOf10s : Math.random();
};

Or.. you could just use Math.floor( Math.random() * number ).

Step 2 & 3: (Due to time constraints I combined step 2 and 3.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var link = "http://bateru.com/news/2011/04/learn-sig-figs-in-no-time/";
var ops = operations = [ " + ", " - ", " * ", " / " ];
var precision = 2;
 
var arrOfRandomNum = function( arrLength, max, decLen ){
	if( arrLength < 0 ){ return false; }
	var arr = [], i = arrLength;
	while( i-- ){
		arr[ i ] = getRandomNum( max, decLen );
	}
	return arr;
};
var makeQuiz = function(){
	var quiz = { "fill":[] };
	var question = '', nums = [];
	var i = questionLength = 10;
	while( i-- ){
		nums = arrOfRandomNum( 2, 19 );
		question = nums.join( ops[ getRandomNum( ops.length ) ] );
		quiz.fill.push({
			ques: question,
			ans: eval( question ).toPrecision(precision)
		});
	}
	return quiz;
}

Step 4:

1
2
3
$( "#quiz" ).jQuizMe( makeQuiz(), {
	intro: ops.join(',') + " quiz.<br>Note: Your answer must have " + precision + " <a href='"+link+"'>sig figs</a>."
});

Here’s the working demo.

Code of the Day: Javascript Fibonacci Numbers the fast way

1
2
3
4
5
6
7
8
//Programmer: Larry Battle
//Date: April 18, 2011
//Purpose: Get Fibonacci numbers in O(1) time.
var getFibonacciNum = function( n ){
    var s5 = Math.sqrt(5);
    var phi1 = (1+s5)/2, phi2 = (1-s5)/2;
    return Math.round((Math.pow( phi1, n ) - Math.pow( phi2, n) )/s5);
};

Demo: Here
Output for 0 to 4

F(0) = 0
F(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3

Code of the Day: Javascript Significant Figures

Did you know that JavaScript automatically trims off trailing zeros on numbers with decimals?
Well now you do, and in order to save precision you must wrap the number inside a string.
Example:

1
2
3
4
5
6
var a = "0.0100";
var b = 0.0100;                           // To save space the interpreter cuts off the last two zeros.
console.log( a === b.toString() );	// displays false because a = "0.0100" and b = 0.01
 
console.log( 1000 === 1000.000 );	// displays true
console.log( 0.1 === 0.1000 );		// displays true

Some might argue that you can use num.toPrecision() to save the trailing zeros. But what most are unaware of is that toPrecision() returns a string.

1
2
3
4
5
var num = (120.0).toPrecision(8);
console.log( num );                      // displays 120.00000
console.log( typeof num );            // displays string
console.log( +num );                    // displays 120
// +num is a shortcut for parseInt( num, 10);

Now let’s see what happens with leading zero’s.

1
2
3
4
5
6
7
//A leading 0 in front of a number converts it base 8.
// a.k.a. parseInt( num, 8);
console.log(0011);		// Displays 9
console.log( 010.1000 );		// Error! Octals can only be whole numbers.
console.log( 00000.1000 );	// Error for the same reason.
// The problem is that a leading zero will cause the number to be converted to octal.
// Thus, an error is generated because the decimal point is neither an operation nor semicolon.

Using numbers as strings can be useful when trying to find the Significant Digits, like in the following function.

1
2
3
4
5
6
7
8
9
10
11
12
//Function: getSigFigFromNum( num ), provides the significant digits of a number.
//@num must be a number (base 10) that is a string. example "01"
var getSigFigFromNum = function( num ){
	if( isNaN( +num ) ){
		throw new Error( "getSigFigFromNum(): num (" + num + ") is not a number." );
	}
	// We need to get rid of the leading zeros for the numbers.
	num = num.replace( /^0+/, '');  
	// re is a RegExp to get the numbers from first non-zero to last non-zero
	var re = /[^0](\d*[^0])?/;	
	return ( /\./.test( num ) )? num.length - 1 : (num.match( re ) || [''])[0].length;
};

Usage:

1
getSigFigFromNum( "0.01230" );		//returns 4

DEMO: http://jsbin.com/okide4

Can you think of any other useful examples for number wrapped in strings?

Bad Behavior has blocked 984 access attempts in the last 7 days.

FireStats icon Powered by FireStats