21 JavaScript Tips and Tricks for JavaScript Developers

javscript-tips-viralpatelnet

If you are doing lot of JavaScript programming, you might find below list of code snippets very useful. Keep it handy (bookmark it) and save it for future reference.


Here are 20 very useful JavaScript tips and tricks for you.


Disclaimer: Not all these snippet are written by me. Some of them are collected from other sources on Internet.


1. Converting JavaScript Array to CSV


First one goes like this. You have a javascript array of strings (or numbers) and you want to convert it to comma separated values (csv). We’ll below is the code snippet:

Reference: Array to CSV in JavaScript



var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];

var str = fruits.valueOf();

//print str: apple,peaches,oranges,mangoes

The valueOf() method will convert an array in javascript to a comma separated string.


Now what if you want to use pipe (|) as delimeter instead of comma. You can convert a js array into a delimeted string using join() method. See below:



var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];

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

//print str: apple|peaches|oranges|mangoes

The join() method will convert the array into a pipe separated string.



2. Convert CSV to Array in JavaScript


Now what if you want to convert a comma seprated string into a JavaScript array? We’ll there is a method for that too. You can use split() method to split a string using any token (for instance comma) and create an array.


Reference: Array to CSV in JavaScript


In below example we split string str on comma (,) and create a fruitsArray array.



var str = "apple, peaches, oranges, mangoes";

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

//print fruitsArray[0]: apple


3. Remove Array element by Index


You have an array. You want to remove a perticular element from array based on its index. We’ll you can do so using splice() method. This method can add as well as removes element from an array. We will stick to its removal usage.

Reference: Remove element by array index



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 Array element by Value


This one is very useful. You have an array and you want to remove an element based on its value (instead of index).

Reference: Remove element by array index



function removeByValue(arr, val) {
for(var i=0; i<arr.length; 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"

See how in above code we defined a method removeByValue that takes serves the purpose. In JavaScript you can define new functions to classes at runtime (although this is discourage) using prototypes.


In below code snippet, we create a new method removeByValue() within Array class. So now you can call this method as any other arrays method.



Array.prototype.removeByValue = function(val) {
for(var i=0; i<this.length; 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. Calling JavaScript function from String


Sometime you want to call a Javascript method at runtime whos name you know. Let say there is a method “foo()” which you want to call at runtime. Below is a small JS snippet that helps you calling a method just by its name.


Reference: Call Function as String



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. Generate Random number from 1 to N


Below little snippet helps you in generating random number between 1 to N. Might come handy for your next JS game.



//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. Capture browser close button event or exiting the page in JavaScript


This is a common use case. You want to capture the browsers close event so that you can alert user if there is any unsaved data on webpage that should be saved. Below javascript snippet will help you in that.


Reference: Capture Browser Close Event



<script language="javascript">
function fnUnloadHandler() {
// Add your code here
alert("Unload event.. Do something to invalidate users session..");
}
</script>
<body onbeforeunload="fnUnloadHandler()">
<!-- Your page content -->
</body>

8. Warn user if Back is pressed


This is same as above. Difference is instead of capturing close event here we capture back button event. So that we know if user is moving awaw from this webpage.

Reference: Capture Browser Back Button



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

9. Check if Form is Dirty


A common usecase. You need to check if user changed anything in an HTML form. Below function formIsDirty returns a boolean value true or false depending on weather user modified something within the form.



/**
* 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} <code>true</code> if the form is dirty, <code>false</code>
* 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. Disable Back button using JavaScript


This one is tricky. You want to disable the browsers back button (Dont ask me why!!). Below code snippet will let you do this. The only catch here is that you need to put this code in page where you dont want user to come back. See below reference for more details.

Reference: Disable Browsers Back Button



<SCRIPT type="text/javascript">
window.history.forward();
function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
onpageshow="if (event.persisted) noBack();" onunload="">

11. Deleting Multiple Values From Listbox in JavaScript


You have a SELECT box. User can select multiple OPTIONS from this SELECT box and remove them. Below Javascript function selectBoxRemove let you do this. Just pass ID of SELECT object you want to remove OPTIONS in.


Reference: Delete Multiple Options in Select



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. Listbox Select All/Deselect All using JavaScript


You can use below JS snippet to select/deselect all the OPTIONS from a SELECT box. Just pass the ID of select box you want to perform this operation on and also a boolean value isSelect specifying what operation you want to perform.

Reference: Select All/None using Javascript



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


13. Listbox Move selected items Up / Down


This one is useful if you are playing a lot with multi options select box in your application. This function let you move select OPTIONS in a SELECT box to UP or DOWN. See below reference for more details.

Reference: Move Up/Down Selected Items in a Listbox



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. Listbox Move Left/Right Options


This javascript function lets you move selected OPTIONS between two SELECT boxes. Check below reference for details.

Reference: Move Options Left/Right between two SELECT boxes



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. Initialize JavaScript Array with series of numbers


Sometime you want to initialize a Javascript array with series of numbers. Below code snippet will let you achieve this. This will initialiaze array numbers with numbers 1 to 100.



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


16. Rounding Numbers to ‘N’ Decimals


This one is quite useful. It will let you round off a number to ‘N’ decimal places. Here in below example we are rounding of a number to 2 decimal places.



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

Note that we use toFixed() method here. toFixed(n) provides n length after the decimal point; whereas toPrecision(x) provides x total length.



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


17. Check if String contains another substring in JavaScript


Below code snippet (courtesy Stackoverflow) let you check if a given string contains another substring.


Reference: stackoverflow



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);
};
}

The code will add two new methods to String, indexOf and contains. Once this is done, you can use contains method to check weather a substring is present in a given string.


var hay = "a quick brown fox jumps over lazy dog";

var needle = "jumps";

alert(hay.contains(needle));



18. Remove Duplicates from JavaScript Array


Aha!! You know this one comes quite handy. Just call removeDuplicates method and pass the array, it should remove all duplicate elements from the array.



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. Trim a String in JavaScript


Below code will add a method trim() to String which 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 webpage in JavaScript


This javascript code should perform http redirect on a given URL.



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

21. Encode a URL in JavaScript


Whenever you are making an http request and passing some parameters. You should encode the URL string. Use encodeURIComponent function for encoding a url parameter.

Reference: w3scools



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








via ViralPatel.net http://feedproxy.google.com/~r/viralpatelnet/~3/7Txp1SIlKas/

SAP to crunch and sell carriers' data on mobile use

uTorrent 3.3.1 RC2

µTorrent is a small and incredibly popular BitTorrent client.





via FileHippo.com http://www.filehippo.com/download_utorrent/ [[ We are also giving web service. Email:wasim.akh2@gmail.com]]

Wi-Host: Freeware to Turn Your Windows PC or Laptop into Wi-Fi Hot Spot to Share Internet Connection

Imagine a situation when you have a mobile phone or a tablet and you want to download some apps or games in it or you want to update existing apps. But you don't have an Internet connection in the device or you don't want to use the Internet connection provided by your mobile operator. What [...]



Read rest of this article at AskVG.com



via Tweaking with Vishal http://feedproxy.google.com/~r/AskVG/~3/NWXDoBY71fQ/

Dwindling MacBook Air Supply Points to New Version Coming

I’ve always loved the saying “Once you go Mac, you’ll never go back”. I want to think I came up with that, but I probably heard it somewhere. In any case, I would go one step further and come up with something witty about going the MacBook Air route, but I just can’t find the right words to match. The bottom line, though, is this: I think that once you start using the 13-inch MacBook Air, it’s really hard to even think about using any other laptop.


Dwindling MacBook Air Supply Might Point To A Refresh At WWDC


That being said, I’ve gone through two MacBook Airs, and I really have no intentions of getting a new laptop anytime soon. Then again, we’re hearing rumors about the dwindling MacBook Air supply everywhere you look.


From the US to the UK, stores are reporting a dwindling MacBook Air supply, leading people – experts and curious consumers alike – to think that the upcoming WWDC has something in store for MacBook Air fans. While most people are spending considerable time wondering what iOS 7 will bring, there is something worth looking at in terms of a MacBook Air refresh.


Apple Insider listed popular stores that are out of stock of the popular 13-inch MacBook Air (1.8 GHz, 256 G SSD): Amazon, B&H, MacConnection, and MacMall.


If you remember, the last MacBook Air refresh was in June 2012 – during WWDC as well. We also can’t overlook the fact that Intel Haswell chips are supposed to be launched in June. These chips are exciting because they offer more processing ability using less power, which in turn leads to longer battery life – something anyone using an ultra-portable laptop appreciates. Then there’s the integration of Intel HD 5000 graphics on the chips, which are supposed to improve performance by 50 percent.


Taking these individual factors into consideration and putting them together – dwindling MacBook Air supply, new Intel chips, last MacBook Air refresh date – I dare say it’s safe to get excited about seeing a sleek, shiny new Air soon. Now, about a Retina screen, I don’t think I’ll get my hopes up that much.


What’s your prediction?


[Image via appledistrict]


The post Dwindling MacBook Air Supply Points to New Version Coming appeared first on TechBeat.






via TechBeat http://techbeat.com/2013/05/dwindling-macbook-air-supply-points-to-new-version-coming/?utm_source=rss&utm_medium=rss&utm_campaign=dwindling-macbook-air-supply-points-to-new-version-coming

Amazon Web Services gets FedRAMP certification for US government cloud use

Boutique PC seller laughs all the way to the bank on the back of Windows 7

[Changelog] What’s New in Google Chrome 140 and Later Versions

UPDATE: Addition of Google Chrome 147.0 version. In this exclusive changelog article, we are providing information about all versions of Goo...