Friday, September 11, 2009

Javascript methods/functions

Javascript functions/methods

As a reminder methods are functions that belong to an object or class.

There are two types of object methods in javascript.



  • Static

  • Dynamic

Dynamic methods
The most common type of method is Dynamic. Dynamic methods are declared inside the object and are referenced from an instance of the object. For Example

function myobject(m){ //constructor for our object
this.message=m;
this.test=test; //assign test to this objects definition
}

function test(){ //global declaration of test function
alert(this.message);
}

// to use this function
o=new myobject('hello'); // creates a new myobject object.
o2=new object('goodbye'); //creates another object

//to reference this method
o.test(); //shows message 'hello'
o2.test(); //shows message 'goodbye'

There is another way of declaring the object without creating the function test using anonymous methods. ie

function myobject(m){ //constructor for our object this.message=m;
this.message=m;
this.test=function(){ //add parameters to function if required
alert(this.message);
}
}

Static or Class Methods
Most people find the difference between static and dynamic methods confusing. The main difference between the two is that a static method is referenced (or called) from the class and not an instance of the class.

function myobject(m){

}

function test(){
alert('class method');
}
//static methods are declared outside the class

//ie

myobject.test=test(); // here the method is assigned to the class itself

to call the method simply access classname.method ie
myobject.test();


Why use this when you can declare functions globally? ie
just
test();
rather than
myobject.test();

In some languages like c# all methods must be part of a class definition. This is of course not necessary in javascript. Here are a couple of reasons that you might think about

  • Helps create structured and readable code
  • For IDEs that have code completion methods can be exposed by typing the class name followed by period.












Monday, August 17, 2009

Having Problems with Apache when skype installed

Having Problems with Apache when skype installed/Apache not working

I was having a problem with my apache web server. The service was running fine and yet when I entered address http://localhost/ I was getting a page not found message. I checked the error log in c:\program files\apache group\apache\logs and could find no error. Stoping and starting the apache service would sometimes fix the problem. So what was causing the problem?

Every process (program and background service) that provides a network service has a port number associated with it. There are standard port numbers for different services. The standard port number for web servers is port 80.

To get a list of network programs that are running , start a command prompt by selecting run and choosing cmd. In the command prompt type

netstat -pa

This will list all the processes , their port number and PID (Process ID). The results were as following:



Top of this list is

Proto, Local Address, Foreign Address, State ,PID

TCP,main:http, main:0, Listening, 2012

TCP, main:http, main:0, Listening, 1596

Clearly there are two programs using port 80 (http). Only one program can use a port at the same time. Therefore there is a clash between these two programs which explains why the server is not working.

To find out which programs are trying to use port 80. Press Control, Alt and Delete you should get task manager. In task manager select view from the task menu and choose select columns. Tick the PID column and press OK. Select the processes tab and find the PIDs that match those given by netstat. In this case, 2012 and 1596. As it turns out

1596=Apache.exe

2012= Skype.exe

So both apache and Skpye are trying to use port 80/ Behave as webservers.

How to turn off the http port on skype

In skype choose options from the tools menu. Click on the advanced button and then the connection button. Untick port use port 80 and press the save button.

Stop and restart skype. run netstat -oa again . This time only one process should be listening on the http port. Restart the system to make sure it is now working.


Tuesday, August 11, 2009

Event Co-ordinates

Event Co-ordinates
When an event such as onClick is triggered the returned event object in javascript has details of the mouse position. Different types of co-ordinates are returned in event.screenX, event.clientX, event.offsetX (and corresponding Y values). Details below.

screenX,screenY
Give the screen coordinates when the event occured ie The cursor position on the screen and not on relative to the top left hand corner of the web page.


clientX,clientY

Events coordinates are relative to the browser window instead of the screen. Thus moving the browser around the screen does not affect client co-ordinates. Note that event co-ordinates are not relative to the bottom of the page (ie if the browser window is 800 pixels deep with a page is 2000 pixels long and you scroll to the bottom and click youll get 800 returned as the vertical position and not 2000).


offsetX,offsetY (layerx,layery in firefox)
Gives the co-ordinates within the element on which the event was triggered. If the element is bigger that the browser window - coordinates can exceed the height of the screen.

For more information see
http://www.javascriptkit.com/jsref/event.shtml

A lesson on Javascript event bubbling

Event Bubbles

When a user clicks or performs another event on an HTML element it propigates up the chain.
For example in the following code , when a user clicks on the blue box it triggers an event in both the blue and yellow boxes.

<div style="WIDTH: 200px; HEIGHT: 200px; BACKGROUND-COLOR: yellow" onclick="alert('2 clicked');">l 2 <div style="WIDTH: 100px; HEIGHT: 100px; BACKGROUND-COLOR: cyan" onclick="alert('1 clicked');">1</div</div>

Click on blue to see.
Clicking on yellow doesnt trigger a blue event because the events move up and not down the chain.






2
1






This behaviour can be useful because when the mouse is clicked in blue Yellow knows about it, so blue can ignore the event and let it be handled by yellow.

Sometimes you want to stop events being passed on to parent elements. The following code shows how to do this.

In the following code e represents the event object.

if (e.stopPropagation) e.stopPropagation(); //Code used for w3c compatible browsers (eg firefox)
else
e.cancelBubble = true; // code used for Internet Explorer


Incorporating this code into our example.

function test(e,message){
if(!e) e=window.event;
if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true;

alert(message);
}





<div style="WIDTH: 200px; HEIGHT: 200px; BACKGROUND-COLOR: yellow" onclick="test(event,'2 clicked');">l 2 <div style="WIDTH: 100px; HEIGHT: 100px; BACKGROUND-COLOR: cyan" onclick="test(event,'1 clicked');">1</div</div>

I cant demonstrate this script as blogspot isnt recognising my script tags.

Tuesday, August 4, 2009

New Project

Having created http://www.imagemapeditor.net/, which lets anyone upload images and create maps I'm embarking on a new project http://www.formeditor.net/.

The basic objective is to create a online form creator. There will be a toolbar for each different kind of form element ie.

Text Field
Hidden Field
Text Area
Check Boxes
Radio Buttons
List
Submit Button

Each type of form field will have a label. Form fields will be dragged from the left of the page to the form canvas where they can be configured (ie add radio buttons). Once added to the form these fields can be dragged up or down to change their order. They can also be deleted.

The output of the form editor will be an HTML form.

There will be instructions on how to use the form. The output from the form can be an email, or record stored in a database. It is envisaged that the latter will be used for marketing quesionaires and will come with a reporting tool that costs money (I have to make money somewhere!).

Ok thats my brief - we'll see how I get on!

Thursday, July 30, 2009

New Website for creating Image Maps

Hello,
Have just gone public with my new website www.imagemapeditor.net which lets anyone create an image map with an easy to use wysiwyg editor.

The service lets you work with an online image or upload one for development purposes. You just select the parts of the image you want to link and decide where to link to and then press the HTML button which creates the source HTML ready for pasting into a web page.

You can also save and load image maps making it easier to make changes.

Theres a free 10 minute video explaining how to use it.

The underlying software is available for purchase by other web design companies. See the site for details.

Happy editing

Tuesday, July 14, 2009

Writing valid HTML

If you want to check that your webpages are compliant with w3c standards visit
http://validator.w3.org/
I found quite a few errors on my new website http://www.imagemapeditor.net/

Ill list some of the things I learnt below.
  • Any link tags for external stylesheets must appear in the head section of the document
  • All your input tags must be ended with />
  • instead of using checked to check a radio button you must use checked="checked"
  • Use <br/> instead of <br>
  • use onsubmit instead of onSubmit in a form

Sunday, July 12, 2009

Creating table elements using span

Hello
This problem had me stumped for quite a while. Basically to create elements of a fixed width as you would my setting the size of a <td>

The solution to the problem lies in the css display property. Simply set the style property for your spans as display:inline-block;
ie

<span style="height:100px; width:100px; background-color:#FFCCFF; display: inline-block;" >test</span>

This will ceate an element that is 100px high and wide. Putting another span next to it will lay itself out like a table element.

Monday, June 29, 2009

Creating Transparency

To create a transparent region using css. Use the following
<style>
#image1 {opacity:0.4;filter:alpha(opacity=40);}
</style>


opacity is used by firefox and other modern browsers and has the value 0 - 1 (ie. 0.5 is a valid entry). 0 being the most transparent.

filter:alpha(opacity=40) is used by internet explorer and opacity can have value 0 - 100 (0 being the most transparent).






Image at 40% transparency

To make an object in javascript transparent use the following code (where 0.8 and 80 represent 80% transparency)

style.opacity=0.8;

style.filter="alpha(opacity=80)";

Forcing an image to refresh

When you refresh a web page the images on it are normally cached. This means if you make a change to an image and refresh the page that it is on, the image will appear unchanged because the browser is using the cached version.

To get round this you can force the image to be reloaded by adding parameters to the image url.

ie for image

<img src="/images/image1.jpg" >

To force refresh change to
<img src="/images/image1.jpg?id=11" >

incrementing the value of the id variable in the url will force the image to be reloaded. Therefore a counter is required . The easiest way to set the counter in php is to set the id to the time function which is a number that increments with the time.

<img src="/images/image1.jpg?id=<?=time()?>" >

Sunday, June 28, 2009

Adding scroll bars to an image

If you have a large picture or text box and you want it to fit on to the page without widening the page in the past you would have used frames both ordinary and inline frames (can hang anywhere). However there is an easy way to do this with css (cascading style sheets).

Heres some sample code
<style>
#scrollbox {width:400px; height:200px; overflow:auto;}
</style>

<div id='scrollbox' >
<img src="http://www.ianskipworth.com/suig/images/wallpaper/005xga.jpg">
</div>

This will show a box 400px by 200px with scroll bars which let you scroll to see the rest of the image. Its the overflow attribute defined in #scrollbox which makes this happen. There are two settings that are useful : auto which shows scroll bars if the image is bigger than the box but none if its smaller or you can force scroll bars with the overflow value of "scroll".

Below is the example working.



Friday, June 26, 2009

What browsers should I support

It is my belief that your site should support the following browsers

Internet Explore 6
Google Chrome
Opera
firefox 2
Safari

If you support IE 6 and firefox 2 your website should work with most modern browsers

Thursday, June 25, 2009

Installing MYSQL

Download and Extract mysql-1.1.22-win32 and run setup
Choose typical install

Choose to skip registration

Choose to configure mysql

Choose standard config

Accept the defaults

Set a password for the root

Finish the install

For php5 copy
C:/php5/libmysql.dll to c:/windows/system32

Configuring the MYSQL
One of the best tools for database manipulation and modification is phpmyadmin.

First configure virtual host database as you configured your site1 etc use directory for both apache configurations ie

C:\program files\apache\apache\database

Download and extract

Phpmyadmin-2.9.1.1-english
to
C:\program files\apache\apache\database

under
C:\Program Files\Apache Group\Apache\database

Copy
config.sample.inc.php
to
config.inc.php

edit config.inc.php in both apache and apachephp5 directories

change youpasssting and yourrootpass to the passwords you set in following
$cfg['blowfish_secret'] = 'youpassstring’

$cfg['Servers'][$i]['controluser'] = 'root';
$cfg['Servers'][$i]['controlpass'] = 'yourrootpass';

now

Run a cmd prompt and
Cd c:\program files\mysql\mysql server 4.1\bin

Now to configure the connection from phpmyadmin

Mysql –u root –p
Enter your root password then at mysql prompt

Set password for root@localhost = old_password('yourrootpass');

Where yourrootpass is your root password for mysql
Quit your command prompt By typing
quit
In your browser access http://database/index.php

and login as root with your password also try

http://database:8080/index.php for php5


In phpMyAdmin find one of the two files in the scripts folder:
If you are using a mySQL version lower than MySQL 4.1.2, then find and run create_tables.sql

If you are using a mySQL version higher than MySQL 4.1.2, then find and runcreate_tables_mysql_4-1-2+.sql

Scripts are in myphpadmin directory under scripts

Wednesday, June 24, 2009

Setting Up PHP

Download php-4.4.4-win32 and php-5.2.6-win32.zip to a folder on your hard disk. Different releases of php can be obtained from

http://www.php.net/releases/

Next extract to the following by right clicking on the zip file and choosing extract

php-4.4.4-win32 to C:\php4
and
Php-5.2.6-win32.zip to C:\php5

Under c:\php4 copy php.ini.recommended to php.ini
copy php.ini to the Apache directory
copy php4ts.dll to c:\windows

Under c:\php5
copy php.ini.recommended to php.ini
copy php.ini to the Apachephp5 directory
copy php5ts.dll to c:\windows

Under Apache directory edit httpd.conf add

# Add to the end of the LoadModule section
LoadModule php4_module "c:/php4/sapi/php4apache.dll"

# Add to the end of the AddModule section
AddModule mod_php4.c

AddType application/x-httpd-php .php

Restart the server from a cmd prompt
Net stop apache
Net start apache


Under Apachephp5 directory edit httpd.conf add


# Add to the end of the LoadModule section
LoadModule php5_module "c:/php5/php5apache.dll"

# Add to the end of the AddModule section
AddModule mod_php5.c

# Add this line inside the <IfModule mod_mime.c> conditional brace
AddType application/x-httpd-php .php

Configuring php

In each php.ini file uncomment

;extension=php_gd2.dll

;extension=php_myql.dll

By removing the ;

make sure the extensions path is set correctly in the file ie

extension_dir = "c:/php4/extensions";

Configuring Email Server

In each php.ini file set SMTP to the address of your mail server and sendmail_from to your email address

[mail function]

;For Win32 only

SMTP = localhost

smtp_port = 25

; For Win32 only.;

sendmail_from = me@example.com

Restart the server from a cmd prompt

Net stop apache8080

Net start apache8080

Tuesday, June 23, 2009

Configuring Multiple Projects in Apache

You can set up different websites on the same server. They are refered to by changing the server name ie Instead of referring to the website on the local machine as localhost you can refer to them as Instead of

http://localhost/

it would be

http://site1/
http://site2/

You must first add your host names to the hosts file in windowsTo do this edit C:\windows\system32\drivers\etc\hosts

Add an entry for each virtual server ie - The tcpip address for your local machine is

127.0.0.1 site1
127.0.0.1 site2
127.0.0.1 database


You will need to make these entrys in each computer you use to access your test server. If you need to access the server on a LAN I recommend setting up and using a domain name server.

Next Edit the httpd config file and at the bottom add

# Use name-based virtual hosting.
NameVirtualHost *

And for each site add


<virtualhost *>

ServerAdmin admin@site1
DocumentRoot “c:/program files/apache group/apache/site1”
ServerName site1
ErrorLog logs/site1.log
</virtualhost>

Where site1 is the name of the virtual server

DocumentRoot should point to a separate directory for each site it should be contained in quotes

If you have more than one server on your machine you should make these modifications to each httpd.conf configuration file.

After making the modifications restart the servers. Do start run and type cmd.

From the cmd prompt

net stop apache
net start apache

and if second server installed

net stop apache8080
net start apache8080

If a server fails to start then check the error log in the apache log directory ie

c:\program files\apache group\apache\logs

Setting up the Apache server

Part 1 Installing Apache multiple times
The following procedure allows you to install 2 copies of the apache server one accessed at localhost and the other at localhost:8080. Installing multiple copies of the server allows for testing of php with both version 4 and 5.

This configuration is for development purposes only and should not be used for a live server.

Install Apache 1.3.22-win32-x86.exe or above to c:\program files\apache group

Install as a service by default the service name will be apache

Test by visiting
http://localhost/

in your browser

To install a second server copy the apache directory to

Apachephp5

Your Configuration file will be c:\program files\apache group\apachephp5\conf\http.conf

In the apachephp5/conf directory


In the file httpd.conf

#
# Port: The port to which the standalone server listens. Certain firewall
# products must be configured before Apache can listen to a specific port.
# Other running httpd servers will also interfere with this port. Disable
# all firewall, security, and other services if you encounter problems.
# To help diagnose problems use the Windows NT command NETSTAT -a
#
Port 80

Change port to 8080
Run a command prompt using start run and entering
Cmd
Cd c:\program files\apache group\apachephp5
run apache -i -n "Apache8080" -f "c:\program files\apache group\apachephp5\conf\httpd.conf" Start the service with Net start apache8080 In your browser visithttp://localhost:8080/ to check the service is working You now have two webservers running on the same machine.

Tuesday, June 9, 2009

Hello

Hello and weclome to my blog. In this blog I'll be sharing those nuggets of information that are hard to find but can make all the difference to both inexperienced and hardened software developers.
Ill be sharing this information as and when i come across it.

Happy blogging
Richard Pearson