Sunday, January 5, 2014

21 Tips And Tricks For JavaScript Programmers

21 Tips And Tricks For JavaScript Programmers  
 
If you work on the popular JavaScript programming language, we bring you some useful tips and tricks. Read on...  

 Have you been programming in JavaScript? It's an important language, but you may be missing out on some of the important tips and tricks here. Use them to make your webpages better and more advanced!
JavaScript, Java programming, JS programming, programming tips, JavaScript tips and tricks, JavaScript tutorials, JS tutorials, JS tips and tricks, JS news, JS tips, JS programming tips




1. Convert a JavaScript Array into the Comma Seperated Value (CSV) format

The valueOf() method is used to convert a javascript array into the CSV format.

var arr = ['abc', 'bcd', 'cde', 'def'];

var str = arr.valueOf();

//print str: abc,bcd,cde,def


You can also use the pipe (|) instead of commas. For this you have to use the join() method.

var arr = ['abc', 'bcd', 'cde', 'def'];

var str = arr.join("|");

//print str: abc|bcd|cde|def


2. Converting CSV into Javascript array

For this you will use the split() method. The method can be used to split a string separated by any token into a Javascript array.

var str = "a, b, c, d";

var arr = str.split(",");

//print arr[0]: a


3. Remove elements of an array by their index

Use the splice() method for this. The splice method can add and remove elements from an array.

function removeByIndex(arr, index) {
arr.splice(index, 1);
}

test = new Array();
test[0] = 'Apple';
test[1] = 'Ball';
test[2] = 'Cat';
test[3] = 'Dog';

alert("Array before removing elements: "+test);

removeByIndex(test, 2);

alert("Array after removing elements: "+test);


4. Remove elements of an array by value

function removeByValue(arr, val) {
for(var i=0; i if(arr[i] == val) {
arr.splice(i, 1);
break;
}
}
}

var somearray = ["mon", "tue", "wed", "thur"]

removeByValue(somearray, "tue");

//somearray will now have "mon", "wed", "thur"


A method (removeByValue in example) has to be defined for removing elements by their value. New functions can be defined to classes at runtime in Javascript using prototypes.

In the code fragment given below, a removeByValue() method has been created inside the Array class.

Array.prototype.removeByValue = function(val) {
for(var i=0; i if(this[i] == val) {
this.splice(i, 1);
break;
}
}
}
//..

var somearray = ["mon", "tue", "wed", "thur"]

somearray.removeByValue("tue");

//somearray will now have "mon", "wed", "thur"


5. Call a JavaScript function as a string

The code fragment given below allows you to call a function simply by its name.

var strFun = "someFunction"; //Name of the function to be called
var strParam = "this is the parameter"; //Parameters to be passed in function

//Create the function
var fn = window[strFun];

//Call the function
fn(strParam);


6. Generating a random number between 1 to n

This code is useful in generating random numbers for games etc.

//random number from 1 to N
var random = Math.floor(Math.random() * N + 1);

//random number from 1 to 10
var random = Math.floor(Math.random() * 10 + 1);

//random number from 1 to 100
var random = Math.floor(Math.random() * 100 + 1);


7. Capturing a browser close button event or to exit the page in JavaScript

The browser’s close event is usually captured in order to tell the user about unsaved data that they may need to save.





8. Capture a back button

The usage is quite similar to above, except you capture the back button event rather than close.

window.onbeforeunload = function() {
return "You work will be lost.";
};


9. Check if the form is dirty

For this, forsIsDirt is used. The function returns a Boolean value (true of false) based on whether the user has made any virtual changes to the HTML form of a website,

/**
- Determines if a form is dirty by comparing the current value of each element
- with its default value.
=*
* @param {Form} form the form to be checked.
* @return {Boolean} true if the form is dirty, false
* otherwise.
*/
function formIsDirty(form) {
for (var i = 0; i < form.elements.length; i++) {
var element = form.elements[i];
var type = element.type;
if (type == "checkbox" || type == "radio") {
if (element.checked != element.defaultChecked) {
return true;
}
}
else if (type == "hidden" || type == "password" ||
type == "text" || type == "textarea") {
if (element.value != element.defaultValue) {
return true;
}
}
else if (type == "select-one" || type == "select-multiple") {
for (var j = 0; j < element.options.length; j++) {
if (element.options[j].selected !=
element.options[j].defaultSelected) {
return true;
}
}
}
}
return false;
}
window.onbeforeunload = function(e) {
e = e || window.event;
if (formIsDirty(document.forms["someForm"])) {
// For IE and Firefox
if (e) {
e.returnValue = "You have unsaved changes.";
}
// For Safari
return "You have unsaved changes.";
}
};


10. Disabling Back button

For this, you have to put the code in the page that you don’t want the user to go back to.



onpageshow="if (event.persisted) noBack();" onunload="">


11. To delete multiple values from the listbox

You have to create a function to remove multiple values.

function selectBoxRemove(sourceID) {

//get the listbox object from id.
var src = document.getElementById(sourceID);

//iterate through each option of the listbox
for(var count= src.options.length-1; count >= 0; count--) {

//if the option is selected, delete the option
if(src.options[count].selected == true) {

try {
src.remove(count, null);

} catch(error) {

src.remove(count);
}
}
}
}


12. Select or Deselect All from Listbox

The code fragment below allows you to do this.

function listboxSelectDeselect(listID, isSelect) {
var listbox = document.getElementById(listID);
for(var count=0; count < listbox.options.length; count++) {
listbox.options[count].selected = isSelect;
}
}


13. To move selected items up or down

To do this, make a function like below.

function listbox_move(listID, direction) {

var listbox = document.getElementById(listID);
var selIndex = listbox.selectedIndex;

if(-1 == selIndex) {
alert("Please select an option to move.");
return;
}

var increment = -1;
if(direction == 'up')
increment = -1;
else
increment = 1;

if((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length-1)) {
return;
}

var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text

listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;

listbox.selectedIndex = selIndex + increment;
}
//..
//..

listbox_move('countryList', 'up'); //move up the selected option
listbox_move('countryList', 'down'); //move down the selected option


14. Move options to the left or right using Listbox

function listbox_moveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);

for(var count=0; count < src.options.length; count++) {

if(src.options[count].selected == true) {
var option = src.options[count];

var newOption = document.createElement("option");
newOption.value = option.value;
newOption.text = option.text;
newOption.selected = true;
try {
dest.add(newOption, null); //Standard
src.remove(count, null);
}catch(error) {
dest.add(newOption); // IE only
src.remove(count);
}
count--;
}
}
}
//..
//..

listbox_moveacross('countryList', 'selectedCountryList');


15. To initialize an Array using the series of numbers

The code fragment given below will help with this.

var numbers = [];
for(var i=1; numbers.push(i++)<100;);
//numbers = [0,1,2,3 ... 100]


16. Rounding off numbers to ‘x’ decimal places

var num = 2.443242342;
alert(num.toFixed(2)); // 2.44

The toFixed(x) method used here provides x length after the decimal point. On the other hand, toPrecision(x) provides x total length.

num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2


17. To check if a string contains a substring

Use the code below.

if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}

if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~this.indexOf(arg);
};
}


18. Removing duplicates

Use the removeDuplicates method for this.

function removeDuplicates(arr) {
var temp = {};
for (var i = 0; i < arr.length; i++)
temp[arr[i]] = true;

var r = [];
for (var k in temp)
r.push(k);
return r;
}

//Usage
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
//print uniquefruits ['apple', 'orange', 'peach', 'strawberry'];


19. Trimming a string

This can be used to remove spaces from both sides of a string.

if (!String.prototype.trim) {
String.prototype.trim=function() {
return this.replace(/^\s+|\s+$/g, '');
};
}

//usage
var str = " some string ";
str.trim();
//print str = "some string"


20. Redirect a webpage

window.location.href = "http://viralpatel.net";

21. Encoding a URL

The envodeURIcomponent function should be used for this.

var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);


Sourceviralpatel.net 

No comments:

Post a Comment