Following is the function to get the X-Y coordinates of mouse click relative to div which works across browsers:
function getPos(obj,e){
var evtobj=window.event? event : e;
if (Browser == 'Explorer' || Browser == 'Opera')
{
clickX = evtobj.offsetX;
clickY = evtobj.offsetY;
}
else
{
clickX = evtobj.layerX;
clickY = evtobj.layerY;
}
alert('clickX:'+clickX+', clickY'+clickY);
}
HTML will look like this:
<div style="width:400px;height:500px;border:1px solid red;position:relative;" onclick="getDetails(this,event)">
Only thing notable in the HTML is that we need to declare the 'position' explicitly.
Insight into Website Engineering
Monday, April 11, 2011
Friday, April 8, 2011
Aligning center image along with text of variable width with float
Div's have a default property of "display:block;", which gives them a width of 100% by default.
Sometime this can be a problem, consider a scenario where you want to show a image and message as 'Loading' as shown in the image below:
Or the message can be a bit long, say 'Failed to load, please try again later'. To reuse the CSS style for same purpose a better or handy solution here could be to use Tables.
Tables by default takes the width of the content inside it unless specified explicitly and it can be aligned center in all browsers.
So the code could look something like this:
<table border="0" cellpadding="0" cellspacing="0" align="center" style="margin:0 auto;">
<tr><td>
<div class="imgClass FloatLeft">
<div class="msgClass FloatLeft">
</td></tr>
</table>
One can apply required css to the table cell as per one's need.
Table will work as wrapper here. It will hold the content inside together and will align it to the center of the parent wrapper.
Sometime this can be a problem, consider a scenario where you want to show a image and message as 'Loading' as shown in the image below:
Or the message can be a bit long, say 'Failed to load, please try again later'. To reuse the CSS style for same purpose a better or handy solution here could be to use Tables.
Tables by default takes the width of the content inside it unless specified explicitly and it can be aligned center in all browsers.
So the code could look something like this:
<table border="0" cellpadding="0" cellspacing="0" align="center" style="margin:0 auto;">
<tr><td>
<div class="imgClass FloatLeft">
<div class="msgClass FloatLeft">
</td></tr>
</table>
One can apply required css to the table cell as per one's need.
Table will work as wrapper here. It will hold the content inside together and will align it to the center of the parent wrapper.
Thursday, April 8, 2010
Algorithm for unique array, optimized
I had come across a scenario where the need was to have an array with unique values.
Algorithm for small size array would not matter much in term of performance, but for large arrays the algorithm needs to be quick as it could become time consuming and can really affect browser performance.
Syntax:
Array.unique()
This function will return a new array with all values unique.
Example:
var arr = new Array(1,5,3,6,2,6,8,9,8,3);
arr.unique();
// Output will be (1,2,3,5,6,8,9)
Function:
Array.prototype.unique = function() {
this.sort();
var r = new Array();
o:for(var i=0,n=this.length;i<n;i++){
for(var x=r.length-1,y=x+1;x<y;x++){
if(r[x]==this[i]) continue o;
}
r[r.length]=this[i];
}
return r;
};
Algorithm for small size array would not matter much in term of performance, but for large arrays the algorithm needs to be quick as it could become time consuming and can really affect browser performance.
Syntax:
Array.unique()
This function will return a new array with all values unique.
Example:
var arr = new Array(1,5,3,6,2,6,8,9,8,3);
arr.unique();
// Output will be (1,2,3,5,6,8,9)
Function:
Array.prototype.unique = function() {
this.sort();
var r = new Array();
o:for(var i=0,n=this.length;i<n;i++){
for(var x=r.length-1,y=x+1;x<y;x++){
if(r[x]==this[i]) continue o;
}
r[r.length]=this[i];
}
return r;
};
Wednesday, October 28, 2009
JSON - JavaScript Object Notation
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.
JSON is built on two structures:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
JSON is not a document format. It is not a markup language. It is not even a general serialization format in that it does not have a direct representation for cyclical structures, although it can support a meta representation that does.
This is an example of a JSON object.
{
"name": "Jack (\"Bee\") Nimble",
"format": {
"type": "rect",
"width": 1920,
"height": 1080,
"interlace": false,
"frame rate": 24
}
}
JSON has become the X in Ajax. It is now the preferred data format for Ajax applications. There are a number of ways in which JSON can be used in Ajax applications.
The most common way to use JSON is with XMLHttpRequest. Once a response text obtained, it can quickly be converted into a JavaScript data structure and consumed by the program. There are two ways in which to do the conversion. The first is to use JavaScript's eval function, which will invoke the JavaScript compiler.
responseData = eval('(' + responseText + ')');
This works because JSON is a safe subset of JavaScript, but it is potentially dangerous because whatever the server sends will be executed. XMLHttpRequest is severely limited by the same origin policy, so the response text can only come from the origining server. If the server acts as a proxy and is incompetent in its filtering, then it could include dangerous scripts in the response text. If there is any risk of this, then the parseJSON method must be used instead.
responseData = responseText.parseJSON();
Back on the client, one need to write some code to handle the JSON response. One can use the json.js parser here from json.org, which adds a safe parseJSON() function to all JavaScript strings. All you have to do is grab the AJAX request's responseText property and call parseJSON() on it to turn it into a JavaScript object. Then it's just a case of updating the input element's status area according to the JSON data.
A popular alternative is use of the dynamic script tag hack. It completely circumvents the same origin policy so that data can be obtained from any server in the world. It is much easier to use than XMLHttpRequest. Just create a script node. The server sends the JSON text embedded in a script.
deliver(JSONtext);
The function deliver is passed the incoming data structure. There is no opportunity to inspect the response before it is evaluated, so there is no defense against a malevolent server sending a dangerous script instead of JSON text. The dynamic script tag hack is insecure. It should not be used unless the data is coming from a trusted source.
The characteristics of XML that make it suitable for data interchange are stronger in JSON.
Its simultaneously human- and machine-readable format;
This is true of both formats.
It has support for Unicode, allowing almost any information in any human language to be communicated;
JSON uses Unicode exclusively.
The self-documenting format that describes structure and field names as well as specific values;
This is also true of both formats, and it raises the question: If the format is self-describing, why is it necessary to have a schema?
The strict syntax and parsing requirements that allow the necessary parsing algorithms to remain simple, efficient, and consistent;
JSON's syntax is significantly simpler, so parsing is more efficient.
The ability to represent the most general computer science data structures: records, lists and trees.
SOURCE: http://www.json.org/ and others
JSON is built on two structures:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
JSON is not a document format. It is not a markup language. It is not even a general serialization format in that it does not have a direct representation for cyclical structures, although it can support a meta representation that does.
This is an example of a JSON object.
{
"name": "Jack (\"Bee\") Nimble",
"format": {
"type": "rect",
"width": 1920,
"height": 1080,
"interlace": false,
"frame rate": 24
}
}
JSON has become the X in Ajax. It is now the preferred data format for Ajax applications. There are a number of ways in which JSON can be used in Ajax applications.
The most common way to use JSON is with XMLHttpRequest. Once a response text obtained, it can quickly be converted into a JavaScript data structure and consumed by the program. There are two ways in which to do the conversion. The first is to use JavaScript's eval function, which will invoke the JavaScript compiler.
responseData = eval('(' + responseText + ')');
This works because JSON is a safe subset of JavaScript, but it is potentially dangerous because whatever the server sends will be executed. XMLHttpRequest is severely limited by the same origin policy, so the response text can only come from the origining server. If the server acts as a proxy and is incompetent in its filtering, then it could include dangerous scripts in the response text. If there is any risk of this, then the parseJSON method must be used instead.
responseData = responseText.parseJSON();
Back on the client, one need to write some code to handle the JSON response. One can use the json.js parser here from json.org, which adds a safe parseJSON() function to all JavaScript strings. All you have to do is grab the AJAX request's responseText property and call parseJSON() on it to turn it into a JavaScript object. Then it's just a case of updating the input element's status area according to the JSON data.
A popular alternative is use of the dynamic script tag hack. It completely circumvents the same origin policy so that data can be obtained from any server in the world. It is much easier to use than XMLHttpRequest. Just create a script node. The server sends the JSON text embedded in a script.
deliver(JSONtext);
The function deliver is passed the incoming data structure. There is no opportunity to inspect the response before it is evaluated, so there is no defense against a malevolent server sending a dangerous script instead of JSON text. The dynamic script tag hack is insecure. It should not be used unless the data is coming from a trusted source.
The characteristics of XML that make it suitable for data interchange are stronger in JSON.
Its simultaneously human- and machine-readable format;
This is true of both formats.
It has support for Unicode, allowing almost any information in any human language to be communicated;
JSON uses Unicode exclusively.
The self-documenting format that describes structure and field names as well as specific values;
This is also true of both formats, and it raises the question: If the format is self-describing, why is it necessary to have a schema?
The strict syntax and parsing requirements that allow the necessary parsing algorithms to remain simple, efficient, and consistent;
JSON's syntax is significantly simpler, so parsing is more efficient.
The ability to represent the most general computer science data structures: records, lists and trees.
SOURCE: http://www.json.org/ and others
Friday, August 21, 2009
Allow to enter only numbers in textbox
At times there is a need when we want to allow users to enter only number.
Say when its phone number, instead of validation after submit we can restrict users to enter non numeric characters using the following script:
Say when its phone number, instead of validation after submit we can restrict users to enter non numeric characters using the following script:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if(!((charCode>=48&&charCode<=57)|| (charCode==46) || (charCode==8))) return false; return true; } To use it in HTML: <input type="text" onkeypress="return isNumberKey(event);" />
Labels:
enter,
javascript,
number only,
only number,
textbox
Friday, August 14, 2009
Parse pop up blocker
All web browsers these days incorporate a popup blocker. These blockers are intended to stop popup windows from appearing except when they are requested by the person using the browser.
This means that a popup blocker is supposed to stop popup windows attached to such events as onload and onunload (and other events not directly associated with the person requesting a popup) from appearing but is not supposed to block those attached to an onclick event on a link (and other events that can be taken to mean that the person has requested it).
Unfortunately not all blockers handle this correctly. Sure they block any popups that are not requested but they also in many cases block requested popups. This is due to the way in which the browsers determine whether a popup was actually requested.
Not all browsers are smart enough to realize that if the onclick event on a link calls a function and the purpose of that function is to open a popup window that the popup has in fact been requested. They see the popup code in the function but are not clever enough to see that this code is called as a result of an action by the person using the browser. Coding our popup that way leads to the popup being blocked despite the fact that it was requested, a sure way to get someone annoyed that your site doesn't work properly despite the fact that the problem is actually their browser.
The way to fix this for many of these dumb browsers is to place the popup code into the onclick itself instead of calling a function. This can result in rather messy HTML but makes sure that the browser has the best possible chance to see that the popup is only created in response to a definite action and does not occur automatically.
For example, a Javascript generated popup could be coded like this:
The displayPopup function would create the content for the popup window like this:
I can't guarantee that your popup will appear if you code it this way. All I can guarantee is that your popup will have a better chance of making it past the blockers if coded like this as it makes it more obvious to the popup blockers that the popup window has actually been requested by the person viewing the page and is not being generated automatically.
Courtesy: Stephen Chapman
This means that a popup blocker is supposed to stop popup windows attached to such events as onload and onunload (and other events not directly associated with the person requesting a popup) from appearing but is not supposed to block those attached to an onclick event on a link (and other events that can be taken to mean that the person has requested it).
Unfortunately not all blockers handle this correctly. Sure they block any popups that are not requested but they also in many cases block requested popups. This is due to the way in which the browsers determine whether a popup was actually requested.
Not all browsers are smart enough to realize that if the onclick event on a link calls a function and the purpose of that function is to open a popup window that the popup has in fact been requested. They see the popup code in the function but are not clever enough to see that this code is called as a result of an action by the person using the browser. Coding our popup that way leads to the popup being blocked despite the fact that it was requested, a sure way to get someone annoyed that your site doesn't work properly despite the fact that the problem is actually their browser.
The way to fix this for many of these dumb browsers is to place the popup code into the onclick itself instead of calling a function. This can result in rather messy HTML but makes sure that the browser has the best possible chance to see that the popup is only created in response to a definite action and does not occur automatically.
For example, a Javascript generated popup could be coded like this:
<a href="#" onclick="popWin = window.open('','name','height=255,width=250, toolbar=no,directories=no,status=no,menubar=no, scrollbars=no,resizable=no'); openPopup(popWin);">popup</a>
The displayPopup function would create the content for the popup window like this:
function openPopup(TheNewWin) {
TheNewWin.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-transitional.dtd"><html xmlns="http:\/\/www.w3.org\/1999\/xhtml">');
TheNewWin.document.write('<head><title>Popup<\/title><\/head><body style="overflow:hidden" bgcolor="#ffffff"> <p>This is an example of a popup window.<\/p>');
TheNewWin.document.write('<p>Provided that your web browser supports Javascript then this window should be 250 pixels wide and 255 pixels high, there should not');
TheNewWin.document.write(' be any toolbars etc. and the window cannot be resized.<\/p><hr \/> <p align="right"><a href="#" onclick="self.close();return false;">Close');
TheNewWin.document.write(' Window<\/a><\/p> <\/body><\/html>');
}
I can't guarantee that your popup will appear if you code it this way. All I can guarantee is that your popup will have a better chance of making it past the blockers if coded like this as it makes it more obvious to the popup blockers that the popup window has actually been requested by the person viewing the page and is not being generated automatically.
Courtesy: Stephen Chapman
Wednesday, July 22, 2009
Stop adjusting the text size in iphone when you Rotate the Screen
There are many CSS3 properties available for you to use in Safari on the desktop and iPhone OS. CSS properties that begin with -webkit- are usually proposed CSS3 properties or Apple extensions to CSS.
Adjusting the text size is important so that the text is legible when the user double-taps. If the user double-taps an HTML block element—such as a <div> element—then Safari on iPhone OS scales the viewport to fit the block width in the visible area. The first time a webpage is rendered, Safari on iPhone OS gets the width of the block and determines an appropriate text scale so that the text is legible.
If the automatic text size-adjustment doesn’t work for your webpage, then you can either turn this feature off or specify your own scale as a percentage. For example, text in absolute-positioned elements might overflow the viewport after adjustment. Other pages might need a few minor adjustments to make them look better. In these cases, use the -webkit-text-size-adjust CSS property to change the default settings for any element that renders text.
In addition to controlling the viewport, you can control the text size that Safari on iPhone OS uses when rendering a block of text.
To turn automatic text adjustment off, set -webkit-text-size-adjust to none as follows:
html {-webkit-text-size-adjust:none}
To change the text adjustment, set -webkit-text-size-adjust to a percentage value as follows, replacing 200% with your percentage:
html {-webkit-text-size-adjust:200%}
Setting the text size adjustment property:
<body style="-webkit-text-size-adjust:none">
<table style="-webkit-text-size-adjust:auto">
<div style="-webkit-text-size-adjust:200%">
Adjusting the text size is important so that the text is legible when the user double-taps. If the user double-taps an HTML block element—such as a <div> element—then Safari on iPhone OS scales the viewport to fit the block width in the visible area. The first time a webpage is rendered, Safari on iPhone OS gets the width of the block and determines an appropriate text scale so that the text is legible.
If the automatic text size-adjustment doesn’t work for your webpage, then you can either turn this feature off or specify your own scale as a percentage. For example, text in absolute-positioned elements might overflow the viewport after adjustment. Other pages might need a few minor adjustments to make them look better. In these cases, use the -webkit-text-size-adjust CSS property to change the default settings for any element that renders text.
In addition to controlling the viewport, you can control the text size that Safari on iPhone OS uses when rendering a block of text.
To turn automatic text adjustment off, set -webkit-text-size-adjust to none as follows:
html {-webkit-text-size-adjust:none}
To change the text adjustment, set -webkit-text-size-adjust to a percentage value as follows, replacing 200% with your percentage:
html {-webkit-text-size-adjust:200%}
Setting the text size adjustment property:
<body style="-webkit-text-size-adjust:none">
<table style="-webkit-text-size-adjust:auto">
<div style="-webkit-text-size-adjust:200%">
Subscribe to:
Posts (Atom)