Let’s suppose we have a simple array containing 5 strings. The .sort() method sorts them in ascending order and the .reverse() method sorts them in descending order, as demonstrated below.
var simpleArray1 = ["Paul", "Peter", "Mary"];
// .sort() will sort the array to become "Mary", "Paul", and then "Peter".
simpleArray1.sort();
// .reverse() will sort the array to become "Peter", "Paul", and then "Mary".
simpleArray1.reverse();
In the case of numbers, we should be aware that they are sorted in a similar fashion as strings. In the following example, 100 appears before 32 when using .sort() because 1 comes before 3.
var simpleArray2 = [100, 999, 32];
// .sort() will sort the array to become 100, 32, and then 999.
simpleArray2.sort();
// .reverse() will sort the array to become 999, 32, and then 100.
simpleArray2.reverse();
To sort an array of numbers by their numeric values, we should pass in a function into the .sort() method as follows.
// .sort(function(a, b) {return a - b}) will sort the array to become 32, 100, and then 999.
simpleArray2.sort(function(a, b) {return a - b});
// .sort(function(a, b) {return b - a}) will sort the array to become 999, 100, and then 32.
simpleArray2.sort(function(a, b) {return b - a});
We can sort an array of objects, ie. each element of the array has its own set of properties, on any of the properties as well. In the following example, each object in the array has a property called “id”, which we are using to sort.
The sample Javascript delay() function below performs a delay for X milliseconds. During the time specified, users can proceed to perform actions on the particular web page.
function delay(milliseconds) {
var cmd = 'alert("Hello World! This should have appeared after ' + milliseconds + ' milliseconds.");';
setTimeout(cmd, milliseconds);
}
Below is a live example, followed by the HTML/Javascript code used.
If you are looking for a way to “freeze” the browser during the wait time, try the Javascript pause() method.
The sample Javascript pause() function below performs a pause for X milliseconds. During the time specified, the browser would appear “frozen” to the user.
First, let us establish a sample select object as below. The Javascript object “objSelect” will also be established to refer to this HTML object.
The following Javascript code can be used to display which option has been selected by the user. If you choose “Blue”, for example, you will get alert dialogues “b”, “Blue”, and then “2”.
alert(objColors.value); // Display the value; in this example, red is "r", green is "g", and blue is "b"
alert(objColors.options[objColors.selectedIndex].text); // Display the text; in this example, "red", "green", and "blue"
alert(objColors.selectedIndex); // Display the index number; in this example, red is 0, green is 1, and blue is 2
The following Javascript code provides you the means to add a new option to the HTML select object. “Yellow” is going to be added to the end of the list, and “White” is going to be added as the third choice.
var newOption1 = document.createElement('option');
newOption1.text = "Yellow";
newOption1.value = "y";
var newOption2 = document.createElement('option');
newOption2.text = "White";
newOption2.value = "w";
try {
// For standard browsers
objColors.add(newOption1, null);
}
catch (ex) {
// For Microsoft Internet Explorer and other non-standard browsers.
objColors.add(newOption1);
}
try {
// For standard browsers
objColors.add(newOption2, objColors.options[2]);
}
catch (ex) {
// For Microsoft Internet Explorer and other non-standard browsers.
objColors.add(newOption2, 1);
}
The code below removes an option. The first example removes index #1, or the second option. The second example removes whatever the last option is.
objColors.remove(1); // Removes index #1, or "Green" in our original example.
objColors.remove(objColors.length-1); // Removes whatever the last option is.
Finally, the code below selects a particular option.
<
pre class="code">
objColors.options[1].selected = true; // Selects the second option, or “Green” in our original example
You may see the running examples below.
Complete code to the running examples is shown below.
I come from a database background, so I have always taken Oracle’s trim() functions for granted. In short, the trim() function removes spaces at the start and end of a string, the ltrim() function removes spaces at the start (ie. left side) of a string, and finally the rtrim() function removes spaces at the end (ie. right side) of a string. As I dabble into web development nowadays, I thought it would be handy to have similar functions in Javascript at my disposal.
function trim(txt) {
return txt.replace(/^s+|s+$/g,"");
}
function ltrim(txt) {
return txt.replace(/^s+/,"");
}
function rtrim(txt) {
return txt.replace(/s+$/,"");
}
Below are some usage examples.
alert(trim(' hello '));
// This should return 'hello'; spaces on both sides is removed
alert(ltrim(' hello '));
// This should return 'hello '; only space on left side is removed
alert(rtrim(' hello '));
// This should return ' hello'; only space on right side is removed
To do so, simply make use of the toUpperCase() or toLowerCase() methods. For example:
: To Upper
: To Lower
Below is the working sample:
To Upper
To Lower
If you do not wish to run it for each key-up such as in this example, try the onChange event, which will only fire when the user leaves the input field.
First, create a Javascript file that we will call “lorem.js”. Copy/paste the following code into that file.
// Lorem ipsum generator
// @author C. Peter Chen of http://dev-notes.com
// @date 20080812
function loremIpsum(elem) {
var loremIpsumWordBank = new Array("lorem","ipsum","dolor","sit","amet,","consectetur","adipisicing","elit,","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua.","enim","ad","minim","veniam,","quis","nostrud","exercitation","ullamco","laboris","nisi","ut","aliquip","ex","ea","commodo","consequat.","duis","aute","irure","dolor","in","reprehenderit","in","voluptate","velit","esse","cillum","dolore","eu","fugiat","nulla","pariatur.","excepteur","sint","occaecat","cupidatat","non","proident,","sunt","in","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum.","sed","ut","perspiciatis,","unde","omnis","iste","natus","error","sit","voluptatem","accusantium","doloremque","laudantium,","totam","rem","aperiam","eaque","ipsa,","quae","ab","illo","inventore","veritatis","et","quasi","architecto","beatae","vitae","dicta","sunt,","explicabo.","nemo","enim","ipsam","voluptatem,","quia","voluptas","sit,","aspernatur","aut","odit","aut","fugit,","sed","quia","consequuntur","magni","dolores","eos,","qui","ratione","voluptatem","sequi","nesciunt,","neque","porro","quisquam","est,","qui","dolorem","ipsum,","quia","dolor","sit,","amet,","consectetur,","adipisci","velit,","sed","quia","non","numquam","eius","modi","tempora","incidunt,","ut","labore","et","dolore","magnam","aliquam","quaerat","voluptatem.","ut","enim","ad","minima","veniam,","quis","nostrum","exercitationem","ullam","corporis","suscipit","laboriosam,","nisi","ut","aliquid","ex","ea","commodi","consequatur?","quis","autem","vel","eum","iure","reprehenderit,","qui","in","ea","voluptate","velit","esse,","quam","nihil","molestiae","consequatur,","vel","illum,","qui","dolorem","eum","fugiat,","quo","voluptas","nulla","pariatur?","at","vero","eos","et","accusamus","et","iusto","odio","dignissimos","ducimus,","qui","blanditiis","praesentium","voluptatum","deleniti","atque","corrupti,","quos","dolores","et","quas","molestias","excepturi","sint,","obcaecati","cupiditate","non","provident,","similique","sunt","in","culpa,","qui","officia","deserunt","mollitia","animi,","id","est","laborum","et","dolorum","fuga.","harum","quidem","rerum","facilis","est","et","expedita","distinctio.","Nam","libero","tempore,","cum","soluta","nobis","est","eligendi","optio,","cumque","nihil","impedit,","quo","minus","id,","quod","maxime","placeat,","facere","possimus,","omnis","voluptas","assumenda","est,","omnis","dolor","repellendus.","temporibus","autem","quibusdam","aut","officiis","debitis","aut","rerum","necessitatibus","saepe","eveniet,","ut","et","voluptates","repudiandae","sint","molestiae","non","recusandae.","itaque","earum","rerum","hic","tenetur","a","sapiente","delectus,","aut","reiciendis","voluptatibus","maiores","alias","consequatur","aut","perferendis","doloribus","asperiores","repellat");
var minWordCount = 15;
var maxWordCount = 100;
var randy = Math.floor(Math.random()*(maxWordCount - minWordCount)) + minWordCount;
var ret = "";
for(i = 0; i < randy; i++) {
var newTxt = loremIpsumWordBank[Math.floor(Math.random() * (loremIpsumWordBank.length - 1))];
if (ret.substring(ret.length-1,ret.length) == "." || ret.substring(ret.length-1,ret.length) == "?") {
newTxt = newTxt.substring(0,1).toUpperCase() + newTxt.substring(1, newTxt.length);
}
ret += " " + newTxt;
}
document.getElementById(elem).innerHTML = document.getElementById(elem).innerHTML + "
Lorem ipsum " + ret.substring(0,ret.length-1) + ".
";
}
Next, in your HTML page, include the Javascript file as follows.
To populate some random text, call the Javascript function “loremIpsum(‘elementName’)”, where “elementName” is the ID of an element you wish to populate the text to. The following code illustrate how we can use this function to populate automatic lorem ipsum text into a DIV.
Lorem Ipsum generator
Written by C. Peter Chen of dev-notes.com
Finally, the following section is a live demo of how the code should behave.
The Javascript code below provides a sample of how the user’s mouse cursor position, displayed as X- and Y-coordinates in relation to the top left corner of the page. In this example, I put the X- and Y-coordinate values in an input box, but you can tweak that to fit your needs.