JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.

Share tech news, updates, or what's on your mind.

Sign up to Post

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single site I looked at has always said "no, it can't be done". Even the most advanced sites I could find said "no, it can't be done". So here you go.

A little background before we get into the code:
I've been using frame-sets for my applications for some time. I like the security of passing all form data into an iframe rather than showing url variables in the browser window url. It just looks cleaner to me, and I use very sophisticated menu systems that I'd prefer not to have to re load after every mouse click in my applications. So I have an application that consists of three frames topHeader, leftMenu and mainFrame. In the mainFrame is where most of the reporting and drilling etc... regular work stuff... goes. The topHeader and leftMenu both contain more specific navigation and information related to getting around and knowing where you are within the scope of the application.

Quite a while ago I devised a method using the below script to print any open window in the mainFrame without all the menu system:

function printMainWindowFrame() {
if (window.mainFrame) {
window.mainFrame.print();
}	else if (window.frames['mainFrame']) {
window.frames['mainFrame'].focus();
window.frames['mainFrame'].print();
}	else if 

Open in new window

3
In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know:

$.ajax({
    type: "POST",
    url: "MyPage.aspx/MyWebMethod",
    data: "{parameter:value,parameter:value}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        //function called successfull
    },
    error: function(msg) {
        //some error happened
    }
});

Open in new window

I don't know if for you it's the same, but for me is soooo tedious to write the calls with this syntax. Moreover, previously it's necessary to build the string with the parameters to pass to the WebMethod, following the known rules: strings must be passed in quotes, numbers do not, etc.

So I decided to create a small but useful JavaScript class to help me with this particular issue, and now that I've done the jQuery Ajax calls are much friendly to me.

In the class constructor I pass the page name, the method name, and the success and error functions. Later, I do as many calls to the addParam method as I need. And finally I call the run method to do the Ajax call. The success and error functions must be written separately.

The parameters are treated according to their type. If the parameter is a string, I use quotes; if it's a number, I do not. A special case are date parameters. In this case, I use the getTime() function of the JavaScript date object, which gives me the number…
0
LVL 75

Expert Comment

by:Michel Plungjan
Why not use the built-in .get and .getJSON?

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "cat",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#images");
      if ( i == 3 ) return false;
    });
  });

Open in new window

0
In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields.
Sorting on two fields of the record (Object)

Basic Sorting of Arrays

First, let's look at the basics.  It's all about the sort() method of the Array object.  The following example defines an array of person names, sorts them using the default handling, and displays the result:
var aNames= [ "Bob", "Jim", "Sam", "Al" ];
alert( aNames.toString() ); // (unsorted) shows: Bob,Jim,Sam,Al
aNames.sort();              // sort the array
alert( aNames.toString() ); // (sorted) shows: Al,Bob,Jim,Sam

Open in new window

As shown in that example, the sort is a "lexical" sort -- it sorts alphabetically in ascending (A-Z) order.  That's great for sorting names, but not so wonderful when sorting numbers or other data types.  For instance:
var aNumbers= [ 900, 17, 3, 1002 ];
alert( aNumbers.toString() );  // (unsorted) shows: 900,17,3,1002
aNumbers.sort();               // sort the array
alert( aNumbers.toString() );  // (sorted???) shows: 1002,17,3,900 

Open in new window

About the only thing that's good about that result is that it makes it easy for your JavaScript professor to give you a failing grade!  It's even worse if you are sorting date fields.  The default sort turns a Date value into words, like:

    "Sun Nov 1..." which will be sorted after
    "Mon Nov 2..."

But that's just the default behavior.  Array.sort() lets you customize the action by specifying a function that it will use as it sorts.  In the next example, we provide a comparison function so that the sort will work for numeric values:

Open in new window

6
When you need to keep track of a simple list of numbers or strings, the Array object is your most direct tool.  As we saw in my earlier EE Article, typical array handling might look like this:
var aNames= [ "Adam", "Bill", "Carl" ]; // create an array

alert( aNames[0] ); // Adam  --  look it up by its index number

// iterate through them
for ( var j=0; j< aNames.length; j++ ) {
    alert( aNames[j] );  // 
}

Open in new window

But JavaScript also supports Associative Arrays (aka Maps or Dictionaries) -- providing a way to access list items not just by position, but by an associated key.
The Associate Array is a "bag of properties" of the base Object objectHowever, this support might not work exactly the way that you might think it should...  
// this seems reasonable...

var aNames= new Array();  
aNames[ "Anderson" ]= "Adam";
aNames[ "Browne"   ]= "Bill";
aNames[ "Crawford" ]= "Carl";

alert( aNames[ "Anderson" ] );  // shows Adam (as expected)

// ... but this might not seem reasonable:

alert( aNames.length ); // shows 0 !!! (why not 3?)

Open in new window

The above code creates an Array and then puts nothing into any of the array elements!

Here's what's going on:  Every JavaScript variable (including Array variables) is an object with the underlying features of the Object object.  It is that base class that supports the key/value pair handling of associative arrays.  So, for instance:
var mapNames= new Object();     // or:  var mapNames= {};
mapNames[ "Anderson" ]= "Adam";
mapNames[ "Browne"   ]= "Bill";
mapNames.Crawford     = "Carl"; // alternate syntax
mapNames[ 2          ]= "Two";

alert( mapNames.length ); // undefined (it is not an Array)

for ( var j in mapNames ) { // show the keys
    alert( j );             // Anderson, Browne, Crawford, 2
}
for ( var j in mapNames ) { // show the data associated with each key
    alert( mapNames[j] );   // Adam, Bill, Carl, Two
}

Open in new window

These key/value pairs are often called properties of the object.

The Object object supports a syntax option that allows you to define the key and the value at the same time:
var mapNames= {
   "Anderson" : "Adam",    // syntax is key:value
   "Browne"   : "Bill",
   "Crawford" : "Carl"
};
for ( var n in mapNames ) {        // show the keys and values
    alert( n+ "=" + mapNames[n] ); // Anderson=Adam, Browne=Bill, etc...
}

Open in new window

The key is on the left and the value is on the right.  The value does not need to be a string or other simple value.  It can be an array, or it can be another object that has its own map of key/value pairs (properties).  You can make the object as complex as you want.  See JSON for some related information and examples.


An Object as a Function Parameter

4
LVL 50

Author Comment

by:DanRollins
Ah, yes, the cryptic OR-op-idiom technique which leverages the fact that that "undefined" equates to "false" so the second part executes only if the first has no value.  I shy away from syntax that is prone to parentheses mistakes and/or takes deep mental calculus to read ... especially in tutorial articles.  Even the "ternary" x?y:z was a break from the simple code that I really like :-)

=====================
One issue I hit on that "constructor issue" (and did not discuss in the article) is what happens when the caller skips a parameter in the middle of the list:

     PersonRec("Rollins", "Dan", ,true, ['Ace','Spike'] ) ;

It seems to be a JavaScript compile-time syntax error to use two consecutive commas that way in a function call.  I guess it's like with C++ where one needs to put the seldom-used parameters at the end.  One could actually send in the string 'undefined', I suppose.
0
LVL 75

Expert Comment

by:Michel Plungjan
I would send null
0

1

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:
  • Look-up is performed every time a variable is accessed.
  • Variables are resolved backwards from most specific to least specific scope.
  • Any variable created without the var keyword is created at the global scope and is not
     garbage collected when the function returns (because it doesn’t go out of scope), presenting the
     opportunity for a memory leak. Therefore, use variables in the same scope whenever possible,
     and avoid global variables at all costs.

2

Use a global array, global object, or namespace prefix. If you need global variables, use a global object that contains all of the global variables, like this:
var myBulletinBoardAppGlobals = {
    foo: "some value",
    bar: null
};

Open in new window

Or consider using a namespace prefix (a.k.a., a special naming convention):
CPWFoo = "some value";
CPWBar = null;

Open in new window

These practices prevent your global variables from colliding with global DOM objects present in the runtime.

3

Use {} instead of new Object().
For instance:
var o = {         // better than var o= new Object; o.name= ... (etc.)
   name: 'Jeffrey',
   lastName = 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};
var o = {};

Open in new window

4

Use [] instead of new Array().
var a = ['Joe','Plumber'];  // better than var a= new Array()

Open in new window

5

Use The Unary + Operator To TypeConvert To Number
In JavaScript, the + operator is used for both addition and concatenation. This can cause problems when adding up form field values, for example, since JavaScript is a non-typed language.  Form field values will be treated as strings, and if you add them with +
1
LVL 50

Expert Comment

by:DanRollins
There are a number of useful tips here.  Thanks for posting this.  However...

As a long-time JavaScript programmer, I'd like to say that I take issue with many of the tips above.   For most of them, there is no background or explanation as to why they should be used, and in fact, the "performance optimization" that can (or I really should say might under some circumstances) be obtained is often so trivial as to be not worth mentioning.

It is too bad that you did not provide documentation, benchmark timing tests, or other information that would be so helpful.  That would have made this a much better article.
0
LVL 9

Expert Comment

by:iGottZ
i support DanRollins comment. some of your listings just dont make sense.

why should i as example avoid recursion?
recursion can be even more performant in some cases if it is done right then you think.
have you ever tryed using call() or apply()?
sharing the same scope with theese methods would result in a single scope for a whole recursion.

also some of your code like 22 is not correct. why should i write with a loop into a -variable-?
your function there overrides the same variable on each loop run.

also your code example at 20 does not make sense. just look at it and you see what i mean.

your point 18 does not make sense because for the javascript core its no efford to convert that to a real expression.
if you mentioned this then why didnt you told us to remove all unneeded spacing and new lines? and specialy comments?


sorry but i just cant feel the love to javascript in your article.
you talk about scopes but do not even talk about prototypes.
0
Today I would like to talk about localizing (Internationalization) JavaScript applications.

Introduction

When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speaks English (specially in Mexico, where I am from), so we have to code our app to support at least two languages and be prepared to include more when needed.

We have two worlds, Server and Client side and both of them need to know how to name for example, a title: EN Title ES Titulo, and so on. This is quite simple if we have static forms that are loaded from the server, because most of the server-side frameworks out there are already prepared for localization (CodeIgniter, Cake PHP).

In these frameworks we can define all of the expressions used in our application and their template engines do the rest. But, that's on the server side.  How can we pass that information to the client? Very simple.

Let's Get started

In CodeIgniter for example, we can retrieve the files at runtime. Each of the localized entries are in a hashed array like this:

//file EN.php
$locale['welcome'] = 'Welcome to our site';
$locale['alert'] = 'Why you do this?';

Open in new window

//file ES.php
$locale['welcome'] = 'Bienvenido al Sitio';
$locale['alert'] = '¿Porque Haces esto?';

Open in new window

In order to use these variables, we can load the right array depending on the user locale, convert it to JSON (json_encode()) and send it to the client.  The result will be:

{welcome : 'Welcome to our site', alert: 'Why you do this?'}

Open in new window

2
LVL 88

Expert Comment

by:leakim971
porque doing mas complicated? thanks por tu time!
0
This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers.

Introduction

A 2D array is a matrix of information.  Each element has two indexes: a row (y) and a column (x).   A matrix is handy whenever you have rows and columns of data.  For instance, if you need to output a month-by-month amortization table, you probably want to show it with a row for each year and a column for each month.  If you have a company sales chart, you might have a matrix with each regional branch represented as a row and have columns to break down sales for widgets, gadgets and gizmos.
Checkerboard as an arrayThink of a chessboard.  There are 8 rows (numbered 0,1,...7) and 8 columns (also 0,1,...7). If you want to check what piece is on the top left corner, you access chessboard[0][0].  The next square to the right of that is [0][1], varying the x value until you get to [0][7] as you go left-to-right.  Vary the y value to move from the top to the bottom; for instance, [6][1] is the second square on the seventh row.

The notation I'm using matches that of JavaScript -- two sets of bracketed integers: [y][x]  All arrays start with element 0; the easy way to think of that is "how much distance from the left" a …
16
LVL 61

Administrative Comment

by:Kevin Cross
DanRollins:

Great work! Your article has qualified for the Community Pick and the EE Approved awards. Thanks for your efforts and continued contribution to the community.

Congratulations!

Respectfully yours,

mwvisa1
EE Page Editor
0
LVL 75

Expert Comment

by:Michel Plungjan
Seems you covered everything - I would personally add the word JSON somewhere next to the
x = [
[],
[],
[]
]

notation
0
This article shows how to read a single webpage's HTML into a string variable, and it also shows how to automate a sequence so you can read and process a list of webpages.  I was tasked with reading and parsing a series of webpages to collect some statistics, and I thought that the techniques I used would be helpful to other Windows programmers.

XMLHttpRequest

The tool of interest is the XMLHttpRequest object that is a member of the window object of your browser's DOM (Document Object Model).  This object is at the core of Ajax operations and is often used for "delayed load" or "asynchronous include" operations in which additional information is obtained from a web server after a page is loaded.  It is commonly used to obtain data in response to a user action, without needing to do a full "submit" and loading a new page.

The basic page-reading operation is simple, as illustrated here:
var gfPgDone;

function ProcessPage(sPgTxt) {
    alert( sPgTxt );
} 
function CollectPageInfo( sURL ) {
    gfPgDone= false;
    var req = new XMLHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            ProcessPage( req.responseText );
            gfPgDone= true;
        }
    }
    req.open( "GET", sURL, true ); // true for async operation
    req.send();
}

Open in new window

The critical (and possibly confusing) factor is that the operation is asynchronous; that is, when you call CollectPageInfo, control resumes immediately -- but the new data is not yet available.  So lines 7 and 12 manipulate a globally-visible Boolean flag variable so that your program can know when the page has been loaded.  That whole asynchronous issue is covered in detail, below.

For my purposes, I decided to write an HTA to contain the processing logic.  An HTA is flexible and easy-to-develop.  See my article, HTA - Hypertext Application tutorial
2
LVL 50

Author Comment

by:DanRollins

Addendum to the article:

The XMLHttpRequest object might not be available if you have an old enough system (if your IE is stil in the 6.x range).  It is still possible to accomplish all of the above by using the related ActiveX object that does the same thing.  Check out this great EE article that shows how to instantiate that object on older systems:

   Reading Files Into Your Web Page With JavaScript
   http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_3327.html

See the getRequestObject()  function in the first code snippet.

0
LVL 9

Expert Comment

by:iGottZ
luckily nowdays exist frameworks like jQuery.
http://api.jquery.com/category/ajax/
this makes creating ajax easyer and even cross browser compatible.
0
Introduction
The Google Maps API offers various ways to draw dynamic and static maps.  Using a combination of PHP and JavaScript, you can draw active JavaScript maps that allow pan-and-zoom in the client browser window.  You can also draw "static" maps that are rendered in the form of PNG images (see below).  Each approach has its advantages.  This E-E question inspired the following example that uses a JSON object of map points to place markers on an active map.

A key concept in mapping is the "geocode," a numerical designation of a location on the earth.  A geocode is part of a GPS coordinate.  The geocode gives the latitude and longitude in the form of a pair of signed decimal numbers, separated by a comma.  The latitude is always given first.  Here is an example of a geocode that shows the location of my house: 38.930445,-77.148075.  Six digits to the right of the decimal point is generally considered to be "rooftop accuracy" in mapping.  The geocode can have greater accuracy, but as a practical matter, greater accuracy doesn't matter much to map applications.

Zoom, Center and Size
The usefulness of your maps and markers will depend on three principal components. …
7
LVL 36

Expert Comment

by:Loganathan Natarajan
@Ray
Could you please suggest which one to use Static map or javascript based map? I have a requirement like display multiple address with custom icon (it is simlar airbnb browse & display location details?)
0
LVL 111

Author Comment

by:Ray Paseur
@logudotcom: I think the choice would have a lot of dependencies on the application design.  You might want to cross-post a question in the PHP and JavaScript Zones to get some variety of opinions from the EE community.
0
"That which we persist in doing becomes easier, not that the task itself has become easier, but that our ability to perform it has improved."

Ralph Waldo Emerson

1. Introduction


One of the wonderful things about the web is that it makes it so easy to look up information.  This is especially true when it comes to finding an answer to a web design problem.  For every problem, it seems, there are hundreds code examples on dozens of sites showing how other developers have solved the problem.  If you look closely you may find there are really only a few ways to solve a certain problems and most of the code snippets rehash the same old solutions.

When looking for code samples on how to read files with JavaScript you will find the same few methods used over and over. Some of those examples are outdated, contain hacks which are no longer needed or are just plain wrong. There are web developers even today who advise that you can not read files with JavaScript. They are wrong! There is a modern, cross browser and elegant solution available in the remote scripting object.

All modern browsers now support remote scripting.  The remote scripting object is also slated for inclusion in the W3C's DOM 3 specification for the next generation of web browsers. Thus it is a firmly established technology.  As long ago as IE 7, you could use the same syntax to create a remote scripting object as is used by …
2
LVL 50

Expert Comment

by:DanRollins
Great article!  Got my YES vote.

BTW, did you know that EE itself uses this technique extensively?  For instance, on a Zone Landing page, when you click the tabs (such as "Recent Activity", "Awaiting Answer", and "Articles") the script calls a function named AsyncInclude() to populate the listviews.  Among other things, the result is a speed up in page load (as measured by, say, Alexa) since all that "hidden stuff" does not weigh down the initial load time.
0
LVL 29

Author Comment

by:rdivilbiss
But do they test for try - catch? LOL
0
Both jQuery and Mootools offer some nice, easy to use scripts. Mootools is best known for their interactive slideshows and jQuery for their menus, but both have many other uses as well.  

jQuery is basically a toolkit with many DOM-related features while Mootools is more modular. They conflict because they have a few identically named functions and namespaces and as a result one or both scripts don't work, or at least don't work properly. In my experience it usually it is Mootools that loses out in this deal.

There are several workarounds available to make jQuery and Mootools work together. Some call for editing the core scripting of jQuery and others call for modifying your script, mostly just to avoid conflict with the "$" function that both rely on heavily. I tried several of these in the past, none worked that well and most just plain broke the script entirely. Maybe it was my fault for not implementing the changes properly, I dunno. I would post those here but it may confuse some who, like me, sometimes just skim pages looking for code snippets to fix what they already have.

After trying the hard way numerous times I found a very simple addition to jQuery scripts that makes it free up constants and variables so that other modules, like Mootools, can use them. In the simplest of terms you tell jQuery to not conflict.

Just add the following little line to the very top of your Jquery script(s), right after the script tag.

Open in new window

0
Regular Expressions with JavaScript
By Ivo Stoykov

Regular Expression is a very useful object that allows developers to apply variety of patterns on a text object. Combination of different metacharacters, switches and modifiers allows creation of complicated patterns that helps reducing the necessary code to manipulate different string sources, like user input to mention one. Often Regular expressions can substitute other string handling functionality which otherwise will need complicated loops. Each JavaScript execution thread has one RegExp object pre-initialized.


Syntax

Regular Expressions construction consists of two parts.

First part is the pattern, which is mandatory one. It follows Perl regular expression syntax, but implements less features than available in Perl. Pattern acts as a template describing what will be sought in the text.

Second part consists of optional modifiers, which describe how pattern must be applied. If used, they can be placed in any combinations.

In JavaScript Regular expressions are handled by RegExp Object. As any object it has a constructor for explicit declaration.
var re = new RegExp(“pattern”, “modifiers”);

Open in new window

RegExp constructor accepts two string parameters – first for the pattern and second for the modifiers. Because parameters are strings if quotation marks are between characters they must be escaped by a backslash.

RegExp could be created implicitly by assigning a pattern and optional modifiers to a variable.
var re = /pattern/modifiers;

Open in new window

0
Hello EE members,

I'm proud to propose to you this article which will demonstrate to you how to import and export data between an Oracle Database and a basic JSON string.

As you read, please keep in mind this is not regarding the storing of the JSON object as a CLOB, but rather the using of each key as a column name and the root element as the table name for import.

I'm neither a Java nor an Oracle guru, but in my opinion it would be long work to write a full JSON library with PL/SQL able to support import and export of a JSON String; therefore, I choose to use Java Stored Procedures instead.

1

Prepare the database
What we need :

An Oracle database with Java enabled so goodbye if you're using Oracle XE database because, as you know, it doesn't support Java Stored Procedure

You don't know Java Stored Procedure ?
Some links :
  - Oracle8i
  - Oracle9i
  - Oracle 10g
  - Oracle 11g

A user with sufficient  privilege to create, delete and replace procedures and the java.net.SocketPermission

SCOTT/TIGER reactivated (non-production server!)

The table bindings which receive or extract data from JSON String

Last time I did some programming on Oracle, it was on the 8i : I decided to install Oracle 11g on my favourite OS, windows 2000 which run on a virtual machine.
I found the user SCOTT disabled and I needed to enable it by using the SYS account. I needed to change its password too :

Open in new window

1
This article is for ASP.net programmers with little experience in JavaScript.

As an ASP.net programmer, probably you have noticed that writing JavaScript code is an important part of your daily work.  This is a fact.  In today’s world, when ultra-fast running is a requirement in all applications, including (of course) web applications, doing the most possible tasks in JavaScript – and taking advantage of execution of those tasks in the client browser - will relieve a lot of server workload.

The bad news are that writing JavaScript (specially good & simple JavaScript) is not easy.  JavaScript code syntax is complex, especially for VB programmers that had never written code in C or C# languages and are not familiar with case-sensitive source code or case-sensitive strings management.  And Visual Studio’s Intellisense doesn’t work as well in JavaScript as in server code (this has been improved in VS2008, but in VS2005 JavaScript Intellisense is almost nonexistent).

Hence the need for a good JavaScript code base library.  There are many ways in which we can minimize the difficulty in writing JavaScript code.  The purpose of all this is to write a good JavaScript code base library (usually called “common.js”) to include in all or almost all of the ASP.net pages that we develop.

Naturally, each one of us will have a preference on which of these facilities will help us more on writing JavaScript.  I’ll focus this article on 3 ways to attack the problem: all-purpose …
1
LVL 75

Expert Comment

by:Michel Plungjan
#1 asked question by ASP developers starting JavaScript is how to set the client ID in ASP so it can be retrieved again in JS.
Could you add that to your article?
0
In this article I'll describe cross-browser techniques for using the mouse wheel (or "scroll wheel") in your JavaScript programming for HTML pages.  I'll show example Javascript for option selection and image zooming.

The mouse wheel is generally used for scrolling, but it can also be convenient for other U/I functionality.  Image zooming is a common use; for instance in Google Maps, spinning the mouse wheel zooms you in or out.  I've seen the mouse wheel used to raise or lower the "camera viewpoint" in first-person 3D games.  Another use I've seen is to cycle though a series of objects.  In HalfLife, et al., you can choose a weapon with the wheel -- though it's a bit awkward (it's better to use the direct choice keys [1,2,3...] if you want to avoid becoming fragmeat by the time you find the weapon you want.)

I was revising an old JavaScript program I'd written years ago (when mouse wheels were uncommon) and I realized that I could improve the UI by supporting mousewheel events.
Pentomino piece selection with the mouse wheel.The application is a fascinating puzzle/game called Pentominos.  For some background, see the Wikipedia entry.  You can see my revised (but unfinished) recreational programming project  here.

The goal of Pentominos is to place all 12 pieces into the puzzle board.  But each piece can be rotated and/or flipped in various ways, so there are a total of 62 …
3
LVL 75

Expert Comment

by:Michel Plungjan
I would change

//-------- set up to handle wheel events on object: oImage
function DoSetup() {
    if (oImage.addEventListener) {

to
//-------- set up to handle wheel events on object: oImage
function DoSetup() {
  var oImage = document.getElementById('oImage');
  if (oImage.addEventListener) {1

Open in new window

0
LVL 75

Expert Comment

by:Michel Plungjan
0
I needed a confirmation window that was not an actual popup window. I wanted this window to be modal, like any of the LightBox clones, and to persist until the Poor User made her choice. I also wanted to specify the caption of the buttons. Most important, I did not want to have to use an external JavaScript library.

After investigating several possible candidates, I found none of them to my liking. So I did what I always do - I created my own, and I call it "GROX" (short for "GRaybOX").

Even if you have no need for something like this, tThere are aspects of the code behind GROX that might be of interest: the concept of a class; the act of binding methods to objects; closures.

GROX has been tested in:
Internet Explorer 8.0.6001.18702
Firefox 3.5.6
Opera 10.10, build 1893
Safari 4.0.4 (531.21.10)

1. Components

GROX generates DOM elements and stuffs then into a wrapper <div/> on the web page. It uses a tiny .PNG image to create the modal background, like Lightbox.

The popup "window" contains:
a Title section
a Message section
a Button section
I separated the JavaScript into two external files, the first of which is germane to GROX but not the focus of this article:
helper.js    Generic methods
grox.js       GROX-specific methods

Open in new window

GROX requires a place in which to build itself. This wrapper is an empty <div/> with a CSS style rule on "grox.htm" (or your own page):
CSS:
#div_modal_wrapper { display:block; }

HTML:
<div id="div_modal_wrapper"></div>

Open in new window

Here is GROX in action with the light background:
 GROX in action (light background)
Here is GROX in action with the dark background:
 GROX in action (dark background)

2. Walkthrough

2

Expert Comment

by:Aks001
Hello Badotz,

I found this can be very helpful for one of my requirement, but unable to edit it.

I have one web page. while accessing the webpage I require this popup to load with Accept and Decline button with dark background.

On clicking accept, it will show the page normally.
On clicking decline button it should redirect to a page to show, "plz accept the agreement to navigate the page."


Plz will you be able to help me out on this ?
0
After investigating several CAPTCHA solutions, I found none of them to my liking. Some were web services, susceptible to downtime; others were too costly, or required image manipulation or PHP on the server (I'm a staunch JavaScript fan - I use it on the client and the server. Don't even get me started).

So I did what I always do - I created my own version of CAPTCHA called KAFKA that requires:

No images
No reliance on external servers (except your own ISP)
No PHP

DISCLAIMER: I honestly do not know if this actually thwarts screen readers. While the displayed characters may [b]look like[/b] letters drawn by a font, they are a [b]representation[/b] of characters drawn by a font. They are human readable, but I do not know whether or not they are machine readable. Caveat emptor.

Some clarification
The meaning of the acronym CAPTCHA is "Completely Automated Public Turing test to tell Computers and Humans Apart". Does KAFKA fall into this catgory? Perhaps.

Traditional CAPTCHA implementations rely on images of words that the user must decipher and enter, often within a short period of time. KAFKA uses a grid of zeroes and ones to display letters and numbers, not images. One could call KAFKA a "meta-CAPTCHA generator" because letters and numbers are shown without using actual letters and/or numbers.

KAFKA generates pseudo-random strings of capital letters and/or numbers. There is no …
11
LVL 9

Expert Comment

by:Bob Stone
> borrow away. Out of curiousity, though, I'd like to know where you plan to use it? <

I am going to put it in a shopping cart admin page as a confirm big change thing, to make certain they really want that change.
0
LVL 111

Expert Comment

by:Ray Paseur
A newer article about CAPTCHA is available here, and importantly, please see the Addendum:
https://www.experts-exchange.com/articles/9849/Making-CAPTCHA-Friendlier-with-Simple-Number-Tests-or-PHP-Image-Manipulation.html

Given the advances in computer vision and machine learning, the old ways of CAPTCHA are rapidly becoming obsolete.  Anyone with some basic CS skills and an NVidia GEForce card can do image recognition.  Facebook can identify and tag your friends in your pictures.  So "reading" a CAPTCHA image is well within the scope of modern computability.  More and different methods are needed.
0
This article is aimed at those who are newcomers to Javascript.   Most if not all of this information can be found on the web, however, it's not all in one place, and it may not be under a "best practice" heading or written in a way that those new to Javascript may understand, so I have decided to create this article to consolidate some of those findings.

Many of us who begin programming in Javascript start by using code copied from the web.  The issue with this is a lot of Javascript code is, unfortunately, poorly written, or no longer current.  This can lead to a lot of bad practices for a lot of new Javascript programmers.  Hopefully this article will point out a few of the biggest "no-no"'s and show you how to do it the correct way.

Eval is Evil
Those are Douglas Crockford's words, not mine.  However, that doesn't make them any less true.  There are two reasons eval is evil: Performance and Security.
Every time eval is called, the javascript interpreter must be started and evaluate the code.  This is an intensive process, although you may not notice it.  If the eval was in a loop, or was called a number of times, the overhead would definitely be noticeable.
Since eval will evaluate code that is passed to it, it is a potential security risk, especially if you are eval'ing code that contains user input.

The most common misuse of eval I regularly see is the following:
eval('document.' + someElementInAVariable + '.someproperty = whatever');

Open in new window

5
This EE article provides JavaScript examples of conversion from string to integer, string to floating-point, and number to string.  We'll also look at some related topics, including how to format numeric output with two decimal places, and one way to do right-justification of numeric text.

0. First... The Short Answer

//------------------ convert number to string
var n= 123;    // n is a number -- value is one hundred-twenty-three
var s= ''+n;   // s is a string with three characters -- value is '123'

//------------------ convert string to number
var s= '12 days';     // s is a string
var n= parseInt( s ); // n is a number -- value is twelve

Open in new window

Thus, the simplest technique for number-to-string is to let the string concatenation operator do it for you.  And the parseInt() function is the most reliable way to break out a numeric value that's at the start of a string (or is the entire string).

0. Automatic Conversion

JavaScript will do most conversions for you automatically:
var n=1234;
alert(n);
alert( 'The value is: ' + n );

Open in new window

The first example uses the fact that the alert function (or WScript.Echo) displays textual (string) data, so the parameter is converted automatically for you.  The second example uses the fact that concatenating a number to a string forces an automatic conversion.

However, there are cases where the built-in conversion might not work as hoped.  For instance,  
var nHundreds=1;
var nTens=2;
var nOnes=3;
alert( 'The answer is ' + nHundreds+nTens+nOnes  );  // The answer is 123
alert( 'The answer is ' + (nHundreds+nTens+nOnes) ); // The answer is 6 
alert( nHundreds+nTens+nOnes + ' is the answer' );   // 6 is the answer
var s= '7';
alert( nHundreds+nTens+nOnes +s+ ' is the answer' ); // 67 is the answer

Open in new window

These examples illustrate now certain automatic type-conversions are performed.    JavaScript's +
6
This began as a thought experiment while waiting for patches to install on my system.

The Morse Code is an effective means with which to change ASCII data into binary bits. We assume that a "dot" is a zero and a "dash" is a one. Translating an ASCII character into its binary value is accomplished with a lookup table.

It is not enough to convert from ASCII to binary; we must further convert from binary into hexadecimal. This reduces the length of the encoded string, and effectively hides the content of the original plaintext.

This is still not enough. We need a means of converting from a string of hexadecimal digits back to the original plaintext. This adds overhead to the final encoded string, but experience has shown this makes the encoding that much more formidable.

We could have used SHA-1 and AES for true encryption, but that would be overkill.

I am the only person I know who uses JavaScript on both the client and the server. All of the script for the Morse Encoder is written in JavaScript, so if you wish to use PHP, Perl or some other server-side language, you will have to translate it from JavaScript.


1. How It Works

This discussion uses the name of my beloved cat, Phoebe, as the plaintext. We begin with the outcome of the encoding process.

It may seem odd to start with an encoded string, but this allows us to explain how we arrived at a given point. The complete code is included, but we will refrain from showing code during …
0
LVL 29

Author Comment

by:Badotz
There is a working example at

http://www.over-engineering.com/test_morse_code.htm

should anyone be interested...
0
There are times when an Internet Protocol (IP) address needs to be verified/validated.  What are examples of valid IP addresses?

127.0.0.1
1.2.3.4
192.168.1.100

The pattern is that we have 4 integer values (from 0 to 255) separated by periods. Can we use a really simple regular expression (RegExp) like this?

var ipRE = new RegExp( '^\d+\.\d+\.\d+\.\d$' );

What does this RegExp mean, and how is it supposed to work?

^ - This symbol matches the beginning of the string.
\d - This meta-character matches a single digit (i.e., 0 to 9).
+ - This symbol says to repeat the preceding pattern or symbol 1 or more times (i.e., 1 or more digits).
\. - This sequence is needed to match a period.  Since a period has special meaning in a RegExp, we have to precede it with the backslash to indicate that we don't want the special meaning, we really want to match a period.
$ - This symbol matches the end of the string.

So, this RegExp will match a string containing 4 integer values, separated by periods.  How can we check it out to see if it satisfies our requirements?

<html>
<head>
<title>IP address validation</title>
<script type='text/javascript'>
  function validate( value ) {
    var ipRE = new RegExp( '^\d+\.\d+\.\d+\.\d+$' );
    alert( ( ipRE.test( value ) ? '' : 'in' ) + 'valid' );
  }
</script>
</head>
<body>
Address: <input type='text' onchange='validate(this.value)'>
</body>
</html>

Open in new window


  When we try this simple page, and enter the simplest of IP addresses, (i.e., "0.0.0.0"), and press the Tab key to have the validate()
2
LVL 61

Administrative Comment

by:Kevin Cross
Hi HonorGod,

Your Article has been awarded the Community Pick bonus points and has EE Approval.
Congratulations!

--mwvisa1, EE Page Editor
0
LVL 41

Author Comment

by:HonorGod
Wow, thanks.
0
No!  Not that kind of date. :-)  That wasn't meant to be a pick up line.

This article is about displaying dates in different formats regardless of the browser being used.  If you let the browser's JavaScript engine format a date object for you, there is a wide variation of the output.  For example:

document.write( new Date( '12:34:56 7/8/9' ) )

Open in new window


Results in the following variations (at least on my machine):

  Chrome (2.0.172.28) = Wed Jul 08 2009 12:34:56 GMT-0400 (Eastern Daylight Time)
  IE (8.0.6001.18702IC) = Thu Jul 8 12:34:56 EDT 1909
  FireFox (3.5)    = Thu Jul 08 1909 12:34:56 GMT-0400 (Eastern Daylight Time)

Note: The different browsers interpret a single digit year differently!

What's an easy way to have the output include:

- The day of the week
- The month of the year, and
- Two digit values (where appropriate)?

This seems to work in a fairly straight-forward way:

function formatDate( val ) {
  function D2( val ) {
    return ( val < 10 ) ? '0' + val : val
  }

  var DoW = 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split( ',' )
  var MoY = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split( ',' )

  return DoW[ val.getDay() ]    + ' ' +
         MoY[ val.getMonth() ]  + ' ' +
         D2( val.getDate() )    + ', ' +
         val.getFullYear()      + ' ' +
         D2( val.getHours() )   + ':' +
         D2( val.getMinutes() ) + ':' +
         D2( val.getSeconds() )
}

Open in new window


Consequently, the altered example document.write( formatDate( new Date( '12:34:56 7/8/9' ) ) ) results in:

Wed Jul 08, 2009 12:34:56

Open in new window

or
Thu Jul 08, 1909 12:34:56

Open in new window

5
LVL 18

Expert Comment

by:Rajar Ahmed
Hi honorgod ,

i dint find these files in the articles .
FormatDate.js
FormatTest.html

0
LVL 41

Author Comment

by:HonorGod
@meeran03 : I don't know what happened to the attachments.

I have reported them missing, and will work to get them replaced.

Thanks for pointing this out!
0
A common challenge, or question, when working with two calendar dates is:

What is the difference between the specified days?

As is frequently the case, the answer is: It depends...

What kind of difference do you want?

Given two date objects, you can simply subtract one from the other to get a difference.

  var day1 = new Date( '2/29/2000 23:59:58' );
  var day2 = new Date( 'Feb 27, 2009 00:00:00' );
  alert( day2 - day1 )

Open in new window


This causes us to ask: What does the displayed value (283824002000) represent?
It's the number of milliseconds between the specified dates & times.

Is there an easy way to convert this into something useable?
Sure.  This works reasonably well:

Technique #1
  var day1 = new Date( '2/29/2000 23:59:58' );
  var day2 = new Date( 'Feb 27, 2009 00:00:00' );
  var units = 'Years,Days,Hours,Minutes,Seconds'.split( ',' );
  var vals = [ 365 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60 ];
  var msg  = '';
  var secs = Math.abs( Math.floor( ( day2 - day1 ) / 1000 ) );
  for ( var i = 0; i < vals.length; i++ ) {
    var result = Math.floor( secs / vals[ i ] );
    if ( result ) {
      msg += '\n' + units[ i ] + ' ' + result;
    }
    secs -= result * vals[ i ];
  }
  if ( secs ) {
    msg += '\n' + units[ i ] + ' ' + secs;
  }
  alert( msg.substr( 1 ) );

Open in new window


Wait a minute... (pun intended) This does provide an accurate difference, but it really isn't the kind of value that people expect.  If you use this code to display the difference between 1/28/2009 and 2/28/2009, the result is "31 days".  Although accurate, this is not always pleasing to people, who might be expecting something like "1 month".

Can we expand this simple loop to include the calculation of the difference in months? Well, the answer to that question is "not without a bit more work".  Why not? Because the length of each month is not a fixed value, that's why.

So, how do we compute a difference between two dates that takes months into consideration?
5
LVL 41

Author Comment

by:HonorGod
Michel:

  I had not realized that setHours() also had optional parameters for minutes, seconds & milliseconds!

Thanks
Bob
0

Expert Comment

by:websss
this is great, thanks.  What about when the dates are in "short" format, providing time in 12-hour AM/PM format?  (e.g. dd/mm/yyy hh:mm TT -  01/06/16 01:43 PM)  How would you subtract date and time in that case?
0
I developed my own JavaScript library I call "apex". It is no better or worse than any other library; it is simply tailored to fit my needs.

In developing this library, I borrowed heavily from both Douglas Crockford and Daniel Brockman. Without their insight into JavaScript, my library would never have seen the light of day. I owe both these men a deep debt of gratitude.

That being said, neither Douglas Crockford nor Daniel Brockman are in any way responsible for the code that follows. If you decide to use any or all of the code, you alone bear the burden of responsibility. It is provided "as is" with no warranty or guarantee.


In this article, I will discuss the core functions of "apex". I will discuss the add-in modules in other articles when time permits.

The code is shown in sections, and a discussion follows.

Note: the "" tags at the beginning of each code snippet are artifacts from the article creation process provided by Experts-Exchange; they are not part of my article nor my code.
 

1. Declaration


"apex" begins with a header block, followed by a few functions and declarations:
 
/*
 ######################################
 apex.js
 Universal properties and methods
 
 Components
 ==========
 .core		Core services
 .ajax		AJAX methods
 .event		Event management
 .json		JSON "to_string" and "to_object"
 .string	LTrim, RTrim, Trim, Pad, Chop
 
 ######################################
 */

// If the "apex" namespace does not exist, create 

Open in new window

1
User input plays a big role on webpages. It acts as an interface between users and the server. Handling user inputs is important as we need to ensure what data can be sent to the server and we cannot expect what the user will send. One of the most common things need to be checked is the input strings.

Strings in javascript is not hard but also not easy to be managed. String is an object in javascript and so a lot of methods have been designed to manipulate it but on the other hand, as an input type, it provides the most freedom to users. As a result, checking is also the most complicated with text input type.

This time, we take the start and trailing space in text input as an example. Users, mostly casual ones, sometimes input strings with these whitespaces in the input boxes without caring. It does'nt look much difference in a glance. However, in the server side point of view, these start and trailing space does make a lot difference. For example, for a query request and database update request, these spaces can lead to failure of potential hits in the search and failure in finding the existing database entry. So, removing these starting and trailing space is a very common practice. It can be done on the client side when user submit the data.

Sounds good! Wait! Javascript object does'nt provide the trim function! So, how? Actually, it's not hard to make one trim function by yourself. The following is one of the examples using javascript regular expressions.

 

Open in new window

0
LVL 7

Expert Comment

by:Atique Ansari
function LTrim( value ) { var re = /\s*((\S+\s*)*)/;      return value.replace(re, "$1");      }
      function RTrim( value ) { var re = /((\s*\S+)*)\s*/;      return value.replace(re, "$1");      }
      function trim( value )
      {
            var value = value.replace(/\s\s+/g, ' ');
            return LTrim(RTrim(value));
      }
0
LVL 25

Expert Comment

by:James Rodgers
that is not a trim, that is a white-space replacement and can have unexpected results, for example some writing styles REQUIRE 2 spaces after a period, with your function that would remove, not trim the two spaces resulting in  "This is the end of the sentence.  Followed by another sentence." becoming "This is the end of the sentence.Followed by another sentence." - and actually breaks the writing style completely
0

JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.