Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Saturday, 23 November 2013

How to secure jQuery AJAX calls in PHP from hackers?

How to secure jQuery AJAX calls in PHP from hackers?

If you are making jQuery AJAX calls in your PHP website, please ensure that those jQuery AJAX calls are secure from website hackers. Your code should not be vulnerable to hackers. Below are some methods and steps which need to be taken to secure your jQuery AJAX calls to PHP files. I am writing this post because I had written a simple post "How to call PHP function from JavaScript function? Always use AJAX." without mentioning any security code. I got following comment on that post:

"Your code is very vulnerable. You're not filtering the $_POST variable at all. This opens yourself to HTML injection. A hacker could pwn your web site very quickly if you used this code. Careless examples like yours is exactly why so many web sites are hacked."

That's why this is my small attempt to make your jQuery AJAX calls secure. 

1. Use $_SERVER['HTTP_X_REQUESTED_WITH']

This is a basic check to see if the request is an Ajax request or not?

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&       strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
{
    //Request identified as ajax request
}

However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

2. Use $_SERVER['HTTP_REFERER']

if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
{
 //Request identified as ajax request
}

But not all browsers set it. So don't properly rely on it but yes, to some extent it can secure your webpage.

Nobody can AJAX your site from other domain, but always can connect and drieclty send http request, for example by cURL.

JavaScript running on another domain cannot access any page on your domain because this is a violation of the Same-Origin Policy. The attacker would need to exploit an XSS vulnerability in order to pull this off. In short you don't need to worry about this specific attack, just the same old attacks that affect every web application.

3. Generate Access Tokens

$token = md5(rand(1000,9999)); //you can use any encryption
$_SESSION['token'] = $token; //store it as session variable

You can create some token in cookies, that will be also seen from jquery request, but that solution can also be hacked.

4. Always check $_POST variables in your PHP file whether those are set or not? Whether there is valid value in $_POST or not before executing the actual PHP code.

Basic code snippet for securing your jQuery AJAX calls in PHP

Step-1 : Generate Token System For All Web-Service:

Generating Token :

<?php
  session_start();
  $token = md5(rand(1000,9999)); //you can use any encryption
  $_SESSION['token'] = $token; //store it as session variable
?>

Step-2 : Use it while sending ajax call:

var form_data = 
{
  data: $("#data").val(), //your data being sent with ajax
  token:'<?php echo $token; ?>', //used token here.
  is_ajax: 1
};

$.ajax({
  type: "POST",
  url: 'yourajax_url_here',
  data: form_data,
  success: function(response)
  {
    //do further
  }
});

Step-3 : NOW, Let's secure ajax handler PHP file with,

session_start(); 
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') 
{
  //Request identified as ajax request

  if(@isset($_SERVER['HTTP_REFERER']) &&    $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
  {
   //HTTP_REFERER verification
    if($_POST['token'] == $_SESSION['token']) {
      //do your ajax task
      //don't forget to use sql injection prevention here.
    }
    else
   {
      header('Location: http://yourdomain.com');
    }
  }
  else 
  {
    header('Location: http://yourdomain.com');
  }
}
else 
{
  header('Location: http://yourdomain.com');
}

Wednesday, 20 November 2013

How to call PHP function from JavaScript function? Always use AJAX.

How to call PHP function from JavaScript function? Always use AJAX.

Recently, I was developing a web application in PHP. I get into the need of calling my PHP function from my Javascript function. This is the common thing when you are developing a web application in PHP and have to call a PHP code from Javascript to refresh only a certain portion of your web page with server results. Always use AJAX to achieve this functionality. Using AJAX you can call server side code / functions (your PHP code) from client side (Javascript). Below is the PHP and Javascript code snippet to illustrate this concept. 

This is very simple example on how to call server side functions of PHP from client browsers (Javascript)? In following example, I have a PHP file named myscript.php which has function named myfunction(). This function uses two $_POST variables and just echoes them. I have mydiv HTML div anywhere on my webpage which I want to refresh with the result which is returned from my PHP script. In my Javascript code, I am using AJAX to call my PHP script with parameters and POST method. The result which is getting returned, I am showing that in mydiv HTML div. 

Have a look at this very simple PHP AJAX example:

PHP code

<?php

myfunction();

function myfunction()
{
$myvar = $_POST['q']." how are you?";
$myvar2 = $_POST['z'];
echo $myvar."\n".$myvar2;
}
?>

HTML code

<div id="mydiv"></div>

Javascript code

var data =" hello world";
var data2=" hello all";
function run()
{
$.ajax(
{
                   url: 'myscript.php',
                data: {'q': data,'z':data2},
                   type: 'post',
                   success: function(output) 
                {
                          //alert(output);
                          document.getElementById("mydiv").innerHTML += output; //add output to div  
                }
}
          );
}

Monday, 21 October 2013

How to pause javascript setInterval method for sometime and restart again?

How to pause javascript setInterval method for sometime and restart again?

I was using javascript setInterval method to display different divs after a regular interval of time. In between, I fell into the requirement of pausing the javascript setInterval method for sometime, do some stuff and restart it again. So, I repeatedly used setInterval and clearInterval to acheive my functionality. 

I have 3 divs: div0 (green), div1 (yellow), div2 (red). All are overlapping each other. I am using setInterval to hide and show div1 and div2 after every second. if index = 4 or 6, I am showing red div else yellow div. 

My requirement is that, When index becomes 8, I want to pause the setInterval for 5 seconds and till then show div0 (green) and afterwards resume the loop of setInterval until clearInterval is called.

Below is the code snippet for pausing and restarting setInterval method which is self explanatory.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Sample Application</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
    var index=0;    
    var auto_refresh = 0;
    $(document).ready(function(){
    hideDiv();
    auto_refresh = setInterval(function(){myTimer()}, 1000);

    });

    function myTimer() 
    {
            index+=1;

            if(index == 4 || index==6)
            {
              showDiv2();
            }   

            else if (index == 8) 
            {
              clearInterval(auto_refresh);
              showDiv0();
              auto_refresh = setInterval(function(){myTimer()}, 5000);  //Now run after 5 seconds
            }

            else if (index > 12) 
            {
              clearInterval(auto_refresh);
            }       

            else
            {
              showDiv1();
            }

        }

    function hideDiv()
    {
      document.getElementById("div0").style.visibility="hidden";
      document.getElementById("div1").style.visibility="hidden";
      document.getElementById("div2").style.visibility="hidden";
    }

    function showDiv0()
    {
      document.getElementById("div0").style.visibility="visible";
      document.getElementById("div1").style.visibility="hidden";
      document.getElementById("div2").style.visibility="hidden";
    }

    function showDiv1()
    {
      document.getElementById("div1").style.visibility="visible";
      document.getElementById("div0").style.visibility="hidden";
      document.getElementById("div2").style.visibility="hidden";
      document.getElementById("div1").innerHTML=index;
    }

    function showDiv2()
    {
      document.getElementById("div2").style.visibility="visible";
      document.getElementById("div0").style.visibility="hidden";
      document.getElementById("div1").style.visibility="hidden";
      document.getElementById("div2").innerHTML=index;
    }

    </script>

  </head>
  <body>
    <div id="container" style="position:relative;">

<div id="div0"     style="background:green;height:200px;width:200px;margin:0;position:absolute">
Relaxing for 5 seconds
</div>
         
<div id="div1" style="background:yellow;height:200px;width:200px;margin:0;position:absolute">
This is div1
</div>

<div id="div2" 
style="background:red;height:200px;width:200px;margin:0;position:absolute">
This is div2</div>
</div>

</body>
</html>

Note: I had discussed this problem on stackoverflow and written the conclusion of the discussion here in this post.

Sunday, 20 October 2013

How to show / hide images randomly at regular intervals in javascript by shuffling the array?

How to show / hide images randomly at regular intervals in javascript by shuffling the array?

I had one requirement in one of my projects that I had an image which I had to show randomly in 4 places (div) in my webpage at regular intervals using javascript. I had asked this problem in stackoverflow. I got good help from a guy named "Hiral" there. With his/her help, I was able to implement this functionality. For implementing my functionality, I am shuffling an array and using javascript setInterval() and clearInterval() methods. Let me explain you my requirement and solution. Maybe you encounter similar requirement in future, then it might be helpful to you!

I have following 4 divs (bulb1, bulb2, bulb3, bulb4) and the image bulb.png in images folder of my project.

<div id="bulb1" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb2" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb3" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb4" class="lightbulb"><img src=".\images\bulb.png" /></div>

Initially, I will hide all these divs by calling my following function:

function hideBulbImages()
{
        document.getElementById('bulb1').style.visibility = "hidden";
        document.getElementById('bulb2').style.visibility = "hidden";
        document.getElementById('bulb3').style.visibility = "hidden";
        document.getElementById('bulb4').style.visibility = "hidden";
}

Now lets say I have an html button on the click of which I am calling below function showBulbImages. As I said I have 4 divs (places in html page) where I have to light the bulb randomly, so I am shuffling the array "myArray" in the below function so that array gets randomized by calling the function "shuffleArray". When array gets shuffled or randomized, I use javascript setInterval() method to turn on the visibility of bulbs randomly at regular intervals, 1 second in my case. When setInterval() method runs 4 times, I call clearInterval() to stop the show.

function showBulbImages()
    { 
        var blink_count = 0;
        var myArray = ['1', '2', '3', '4'];
        var randomArray = shuffleArray(myArray)
        var blink_the_bulbs = setInterval(function() {      
            var blinking_bulb = "bulb" + randomArray[blink_count];
            document.getElementById(blinking_bulb).style.visibility = "visible";
            blink_count+=1;
            if (blink_count > 3) 
            {
                 clearInterval(blink_the_bulbs);
            }
        }, 1000);
    }

    function shuffleArray(array) 
    {
        for (var i = array.length - 1; i > 0; i--) 
        {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    }

How to implement javascript count down timer using setInterval and clearInterval methods?

How to implement javascript count down timer using setInterval and clearInterval methods?

I had to implement  a count down timer in my project which runs for 40 seconds. I implemented count down timer in javascript using setInterval() and clearInterval() methods. I am sharing my javascript timer code in this post. It is very simple and can be understood in one go. Below is my javascript code snippet for count down timer.

        function playTimer()
        {
var count= 40;
document.getElementById("timer").innerHTML=count + " secs left";
var count_down=setInterval(timer, 1000); 
}

function timer()
{
count=count-1;
//if time is finished
if (count <= 0)
{
document.getElementById("timer").innerHTML="Time Over";
clearInterval(count_down);
                        //call you function which has to be called after timer
return;
}
//if 1 second is left, display "sec" instead of "secs"
if (count == 1)
{
document.getElementById("timer").innerHTML=count + " sec left";   
}
else
{
document.getElementById("timer").innerHTML=count + " secs left";
}
}

Friday, 1 March 2013

Basic Javascript Technical Interview Questions and Answers for Web Developers - Objective and Subjective

Basic Javascript Technical Interview Questions and Answers for Web Developers - Objective and Subjective

In this tutorial on "Basic Javascript Technical Interview Questions and Answers For Web Developers", we will discuss some questions which are frequenty and commonly asked when you sit in a  technical interview on Javascript. So, if you are going for job interview and have mentioned javascript in your CV, you must go through the following javascript interview questions and answers. We will cover very basic things about javascript here like basic introdurction to javascript, datatypes in javascript, syntax of javascript and basic DOM events associated with javascript. Here goes the list of javascript interview questions and answers:

1. What is JavaScript?

JavaScript is a platform-independent,event-driven, interpreted client-side scripting language developed by Netscape Communications Corp. and Sun Microsystems.

JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself.

But the language is used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat.

Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment.

When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser with the rest of the HTML tags and content.

2. How is JavaScript different from Java?

Don't be fooled by the term Java in both. Both are quite different technologies.

JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing; it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it's operating in for the user interface, such as a Web document's form elements.
JavaScript was initially called LiveScript at Netscape while it was under development. A licensing deal between Netscape and Sun at the last minute let Netscape plug the "Java" name into the name of its scripting language. Programmers use entirely different tools for Java and JavaScript. It is also not uncommon for a programmer of one language to be ignorant of the other. The two languages don't rely on each other and are intended for different purposes. In some ways, the "Java" name on JavaScript has confused the world's understanding of the differences between the two. On the other hand, JavaScript is much easier to learn than Java and can offer a gentle introduction for newcomers who want to graduate to Java and the kinds of applications you can develop with it.

3. What is the official JavaScript website?

This is a trick question used by interviewers to evaluate the candidate’s knowledge of JavaScript. Most people will simply say javascript.com is the official website.

The truth is- there is no official website for Javascript you can refer to. It was developed by Brendan Eich for Netscape. It was based on the ECMAScript language standard; ECMA-262 being the official JavaScript standard.

4. What’s relationship between JavaScript and ECMAScript?

ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.

5. What are the various datatypes in javascript?

Number
String
Boolean
Function
Object
Null
Undefined

6. What boolean operators does JavaScript support?

&&, || and !

7. What is negative infinity?

It’s a number in JavaScript, derived by dividing negative number by zero.

8. Is it possible to check if a variable is an object?

Yes, it is possible to do so. The following piece of code will help achieve the same.

if(abc && typeof abc === "object") {
console.log('abc is an object and does not return null value');
}

9. Can you explain what isNaN function does?

isNaN function will check an argument and return TRUE (1) if the argument does not seem to be a number.

10. How do you convert numbers between different bases in JavaScript?

Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);

11. What is the difference between undefined value and null value?

undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.

Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.


12. What is the difference between “==” and “===”?

While “==” checks only for equality, “===” checks for equality as well as the type.

13. Differentiate between “var a=2” and “a =2”

The major difference between the two is that one variable is local and the other is global. “var” basically defines the scope of the variable.

When we add var to a variable value assignment, javascript ensures that the variable is confined to whichever function it is assigned to and does not collide with the same name variable within another function.

When we don’t use var, then it is declared as a global function and chances of collision can happen. So it’s always advisable to use “var” before variable value assignment. If needed use an anonymous function for closure.

14.  What is Javascript namespacing? How and where is it used?

Using global variables in Javascript is evil and a bad practice. That being said, namespacing is used to bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that you’ve attached all further methods, properties and objects. It promotes modularity and code reuse in the application.

15. What does "1"+2+4 evaluate to?

Since 1 is a string, everything is a string, so the result is 124.

16. How about 2+5+"8"?

Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.

17. How to create arrays in JavaScript?

We can declare an array like this
var scripts = new Array();
We can add elements to this array like this
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0. To get the third element of the array we have to use the index number 2 . Here is the way to get the third element of an array.
document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);
 

18. How do you create a new object in JavaScript?

var obj = new Object(); or var obj = {};

19. How do you assign object properties?

obj["age"] = 17 or obj.age = 17

20. What’s a way to append a value to an array?

arr[arr.length] = value;

21. What is this keyword?

It refers to the current object.
 

22. How many looping structures can you find in javascript?

If you are a programmer, you know the use of loops. It is used to run a piece of code multiple times according to some particular condition. Javascript being a popular scripting language supports the following loops

for
while
do-while loop

23. Are javascript and jQuery different?

jQuery is a quick as well as concise JavaScript Library that simplifies HTML document traversing, animating, event handling, & Ajax interactions for the purpose of quick web development needs. So although they are not entirely different, both are not the same either!

24. Explain the strict mode in Javascript.

The strict mode ensures that if functions are not properly thought it, those are disabled. It also kept a check on potentially unsafe actions and throw errors when it happens.

25. Is it possible for you to write a one line JavaScript code that concatenates all strings passed into a function?

The following function should help in producing the desired result

function concatenate()
{
  return String.prototype.concat.apply('', arguments);
}

26. Explain Javascript closures.

A basic overview of javascript closures is that it is a stack-frame which is not de-allocated when the function returns.

27. What is event bubbling?

Event bubbling describes the behavior of events in child and parent nodes in the Document Object Model (DOM); that is, all child node events are automatically passed to its parent nodes. The benefit of this method is speed, because the code only needs to traverse the DOM tree once. This is useful when you want to place more than one event listener on a DOM element since you can put just one listener on all of the elements, thus code simplicity and reduction. One application of this is the creation of one event listener on a page’s body element to respond to any click event that occurs within the page’s body.

28. Difference between window.onload and onDocumentReady?

The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed.

That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.
 

29. How do you change the style/class on any element?

document.getElementById(“myText”).style.fontSize = “20″;
-or-
document.getElementById(“myText”).className = “anyclass”;

30. How is form submission possible via javascript?

We can achieve the desired form submission by using the function document.forms[0].submit().

It must be noted that the 0 in the piece of code given above refers to the form index. Say we have multiple forms on a particular page. To make all the form procession unique, we give each form index numbers. The first form will have the index number as 0. The second form will have an incremented number, 1. The third will have 2 and so on.

31. How JavaScript timers work? What is a drawback of JavaScript timers?

Timers allow you to execute code at a set time or repeatedly using an interval. This is accomplished with the setTimeout, setInterval, and clearInterval functions. The setTimeout(function, delay) function initiates a timer that calls a specific function after the delay; it returns an id value that can be used to access it later. The setInterval(function, delay) function is similar to the setTimeout function except that it executes repeatedly on the delay and only stops when cancelled. The clearInterval(id) function is used to stop a timer. Timers can be tricky to use since they operate within a single thread, thus events queue up waiting to execute.

32. How to get CheckBox status whether it is checked or not?

alert(document.getElementById('checkbox1').checked);

if it will be checked you will get true else false.

33. How to get value from a textbox?

alert(document.getElementById('txtbox1').value);

34. How to get value from dropdown (select) control?

alert(document.getElementById('dropdown1').value);

35. How to get value from RadioButtonList control?

Here id is the name property of the RadioButtonList
function GetRadioButtonValue(id)
        {
            var radio = document.getElementsByName(id);
            for (var ii = 0; ii < radio.length; ii++)
            {
                if (radio[ii].checked)
                    alert(radio[ii].value);
            }
        }

36. How to detect the operating system on the client machine?

In order to detect the operating system on the client machine, the navigator.appVersion
string (property) should be used.

Sunday, 17 February 2013

How to format and update datetime in Javascript?

How to format and update datetime in Javascript?

There are a lot of datetime formats in which you can display the date and time on your webpage using javascript. There are a lot of javascript datetime functions available. In this javascript datetime tutorial, I will show you how to display the date on your webpage and keep on updating datetime every minute.

I have to show the javascript datetime in following format:

Monday, February 18, 2013 12:18

I will keep this time updating every minute without refreshing my webpage.

For this, I will make two arrays. One array will contain the names of the months and other array will contain the names of the days. I will use setInterval function which will keep on calling myDateTimer function after every minute.

Lets look at this javascript datetime code:
 
var myVar=setInterval(function(){myDateTimer()},1000);
  
function makeArray()
{
 for (i = 0; i<makeArray.arguments.length; i++)
 this[i + 1] = makeArray.arguments[i];
}
  
function myDateTimer()
{
 var months = new makeArray('January','February','March','April','May',
 'June','July','August','September','October','November','December');
 var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
 var date = new Date();
 var day = date.getDate();
 var month = date.getMonth() + 1;
 var yy = date.getYear();
 var year = (yy < 1000) ? yy + 1900 : yy;
 var hours = date.getHours();
 var minutes = date.getMinutes();
 var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
 document.getElementById("showDateTime").innerHTML=finaldate;
}

Thursday, 17 January 2013

Basic Tips for Professional Webpage Designers

Basic Tips for Professional Webpage Designers

Are you a professional webpage designer? or
Are you new to webpage design and going to learn it?

Does not matter!!

Following are some basic tips which each webpage designer must follow. Webpage designing is very easy and interesting. You can learn webpage designing in no time if you take interest in it. You don't have to learn any complex algorithm or diagrams for this. Learning web design online is very easy. There are a lot of websites which will teach you web design from the scratch.

You will have to learn HTML, CSS and Javascript for web design. Flash, Photoshop will be a plus. Today, HTML5 has eliminated the need of Flash. CSS3 has now lot of advanced features which are provided by Photoshop like gradient effects, animations, rounding the corners of images etc.

You can get a lot of web design templates online. There are a lot of free editors available for HTML, CSS and Javascript which will help you in learning web designing.

For now, I have listed some basic points which each web designer must have in mind before designing any webpage.

1. Include Doctype in your webpages

The DOCTYPE defines which version of HTML you are using, and gives important information to your browser so it can render your page faster and more consistently.

The DOCTYPE declaration also allows validating software to check the syntax of your page.
<!DOCTYPE html>

2. Include Title in your webpages

The <title> element is one of the most important HTML elements. Its main function is to describe the content of a web page. It is important to the quality of your web site because it will be visible in search engine lists, the browser's title bar and user's bookmark.

The title should be as short and descriptive as possible.
 
When a user searches for a web site, most search engines will display the title of your web site in the search result. Make sure the title matches the content the user is looking for. Then it is more likely the user will click on the link to visit your web site.

3. Use Headers in your webpages

The <h1> element is used to describe the main heading of a web page. You can use <h2>, <h3>, <h4> etc to arrange your content in your webpage. This will be great approach for search engine optimization.

4. Follow CSS standards

With CSS, you can store all style information for your web site in one single document. Using Cascading Style Sheets (CSS) is the preferred way of separating content from style in quality web pages.

Using CSS will improve the quality of your web site and increases the readability for many different browsers. It will also greatly reduce your web site development costs.

5. Use Web Validators

A validator is a software program that can check your web pages against the web standards.
When using a validator to check HTML, XHTML or CSS documents, the validator returns a list of errors found, according to your chosen standard.

6. Do not use fixed sizes

Never use fixed size values. Always use relative size values.

The most important reason for this advice is that fixed sizes can not be resized by the browser.
Your visitors will have different monitors, different viewing conditions (light), and possible disabilities (poor eyesight).

Setting your default text size to 100% (or medium), your main headers to 140% (or x-large), your sub headers to 120% (or large), as an example, will make it possible for your reader to resize your pages to their best fit.

7. Take care of different date formats

Don't use dates like "04-03-02". This is confusing.

The date above could mean the 2nd of March, 2004. It could also mean the 4th of March, 2002. Or even the 3rd of April, 2002.

The International Standard Organization (ISO) has defined an international format for dates as "yyyy-mm-dd", where yyyy is the year, mm is the month, and dd is the day.

When you use this ISO format, you can expect most visitors to understand your dates.

8. Always take care of font-family, line spacing, letter spacing, color contrasts, foreground and background colors.

Monday, 24 December 2012

Javascript Window Object: How to open and close a new browser window using javascript?

Javascript Window Object: How to open and close a new browser window using javascript?

Every web browser window and every frame within every window is represented by a Window object in Javascript.

Why to use Javascript Window Object?

Sometimes you need to open a new window in your application for some purpose. Here Javascript Window Object comes into play. Using Javascript window object you can open a new window in your HTML page.

Syntax and Explanation of Javascript Window Object

window.open('url', 'name of window', 'attribute1, attribute2')

1. url: This is the web address of the page you wish to appear in the new window.

2. name of window: You can name your new javascript window whatever you like.

3. 'attribute1, attribute2': You can set attributes or properties of the new window like below:

Javascript Window Object Attributes and Properties

Below is a list of the attributes you can use:

1. width=300: Use this to define the width of the new window.

2. height=200: Use this to define the height of the new window.

3. resizable=yes or no: Use this to control whether or not you want the user to be able to resize the window.

4. scrollbars=yes or no: This lets you decide whether or not to have scrollbars on the window.

5. toolbar=yes or no: Whether or not the new window should have the browser navigation bar at the top (The back, foward, stop buttons..etc.).

6. location=yes or no: Whether or not you wish to show the location box with the current url.

7. directories=yes or no: Whether or not the window should show the extra buttons. (what's cool, personal buttons, etc...).

8. status=yes or no: Whether or not to show the window status bar at the bottom of the window.

9. menubar=yes or no: Whether or not to show the menus at the top of the window (File, Edit, etc...).

10. copyhistory=yes or no: Whether or not to copy the old browser window's history list to the new window.

Example: How to open a new browser window using javascript window object?

<form>
<input type="button"
value="Open a new window"
onClick="window.open('http://theprofessionalspoint.blogspot.com/','TheProfessionalsPoint','width=400,height=200,toolbar=yes,
location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,
resizable=yes')">
</form>

Example: How to close a new browser window using javascript window object?

<form>
<input type="button" value="Close Window" onClick="window.close()">
</form>