Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Monday, 1 April 2013

Getting Started with SVG Animation

With HTML5, you can embed SVG images inline in your Web pages. Although the level of support for some of the SVG elements still has a long way to go, there are many advantages to using these graphics. Since you create the SVG code in XML in your pages, you can also implement animation and interaction on the contents of an SVG. SVGs are also scalable at any level, so are ideal for catering to different user environments.

In this tutorial we are going to look at basic animation within SVG elements in HTML5 pages. The results will not work in all modern browsers. Although inline SVG is in itself supported in all current versions of the major browsers, the animation elements are not. You will be able to see some of the effects in both Firefox and Chrome, but the effect in which we animate colour can only be reliably viewed in Chrome at the moment. As is always the case with HTML5 skills, this is more of a preview of what we will be able to do in the near future than a practical guide of techniques you can rely on already, so make sure you include alternatives in your live sites. You can see the demo now for an indicator of what we are working towards.

Create an HTML5 Page

Start by creating a new HTML5 page using the following outline:
<!DOCTYPE html>
<html>
<head>
</head>
<body>

</body>
</html>

We won't be using any scripts or CSS in the head section for this tutorial, however, you can use both to apply effects to the elements inside SVGs.

Create the SVG Element

In the body section of your page, add the SVG element as follows:




The remainder of our code will be placed between these opening and closing tags. The main attributes to pay attention to in the opening SVG tag are the dimensions. You can alternatively specify relative percentage values for the width and height if you have CSS dimensions set for the containing page element.

Add the Definitions

The SVG is going to contain shapes, definitions of gradients and animations. Let's start by defining a couple of gradients. The SVG is going to contain a simplistic representation of the sun rising against a blue sky background. In an SVG, you define re-usable items such as gradients in the dedicated defs section, so add it inside the SVG element first:




Inside this section, place a gradient to represent the sky background:

 
 


This is a linear gradient, with an ID so that we can apply it to our shapes when we create them. The x1, y1, x2, y2 attributes represent the start and end co-ordinates of the gradient. In this case we want the gradient to unfold vertically so the start point is the top left corner and the end point is the bottom left corner. The stop elements represent points in the gradient - in this case it is going to go from one shade of blue to another, will full opacity throughout.

Now add a radial gradient for the sun:

 
 


In this case we define the central points of the start and end circles of the gradient - it will spread from the center of the circle shape to its outer edges. The first colour stop starts 20% into the gradient, so there will be an area of solid colour at the centre.

Add the Shapes

The SVG is going to display a rectangle background and circular sun. First add the rectangle, after the closing defs tag but still inside the SVG element:




You can include a shape using a single self-closing tag, but we are going to include the animation properties inside the rectangle element, so we separate the opening and closing tags. The rectangle properties include the x and y co-ordinates for its top left corder and the width and height, which we set to cover the whole image. We set the gradient we defined in the defs section by referring to it in the fill attribute.

Now add the circle element for the sun:




The circle is defined using the co-ordinates for its central point and the length of the radius. Again, we specify one of the gradients already defined. The circle will be in the center of the image, occupying 80% of the total width (twice the radius).

Animate Movement

If you open your page now you will see a static image of the sun in front of the sky background. Now we can add some animation using the SVG animation elements, which come from SMIL animation. First, to animate the sun, making it move into the image as though rising from the horizon, add the following animate element inside the circle element:


This element specifies an animation that will move the circle element on the y axis, which we specify by referring to the cy attribute of the circle. The attribute type tells us what type of animation this is. The from and to attributes indicate the desired start and end positions for the circle. The begin attribute indicates that the animation should start immediately and the dur attribute that it should last 5 seconds. Setting the fill attribute to freeze stops the circle from going back to its original position when the animation has elapsed.

Animate Opacity

As well as moving the circle, let's fade it in at the same time. Add the following animation, also inside the circle element:


This time the animation is on a CSS property - the opacity. We want the circle to go from zero to full opacity, to last 5 seconds and to execute once.

Animate Colour

Let's also animate the sky to complement what is happening with the sun. This animation has less browser support at the time of writing, so you may need to view the page in Chrome to see it in action. Add it between the opening and closing rectangle tags:


This is an animateColor element, which animates a change in colour over 5 seconds. The animation uses the same colours we specified in the linear gradient for the sky - browsers without support for the colour animation will simply display the gradient instead.

Conclusion

That's our basic animation complete. Open your page in a supporting browser to see the result. You should see the sun shape rise up into the image while fading in, as the background changes colour from one shade of blue to a darker one. Check out the demo to see what it should look like. This is really just the beginning when it comes to SVG animation, as there are other elements for transformational animations such as rotations and translations. With any luck you'll be able to use them for more and more users as time passes, but for the moment these effects must necessarily be used with caution.

Thursday, 30 August 2012

How To Get Started With Web Development

Anyone can teach themselves the skills involved in Web development, but if you're a beginner it can be difficult to know where to begin. In this article we'll go over the basic areas to get yourself acquainted with. Ideally, if you can work through each area in turn, getting yourself to a reasonable level of competence in each before moving on to the next, you'll build a solid foundation in the discipline that you can continue to grow over time. If you do not have much technical experience, try not to be intimidated by the number of technologies involved, just focus on one at a time and within a short period you'll be well on your way to being a competent Web developer.

HTML

The first area to get to grips with is HTML. HTML is known as a markup language. The content of most Web pages is structured within HTML markup. This markup consists of elements and attributes, with each content item in a page listed within one or more element structures.

The first step in creating any Web page is working out what the content is going to be, which may include text, images, media such as videos and interactive items. Once you decide on these content items and have them ready, you will structure them within HTML markup.

The HTML dictates the structure of a page, with each item listed within the body section, and information about the page listed in the head section. The head section gives the user's Web browser information it needs to display the page. To learn basic HTML, you should ideally cover: making a page, including text, links, images and HTML attributes. Once you have the basics of HTML mastered, you can look into other client side technologies.

CSS

Cascading Style Sheets determine the styling and appearance of Web pages, in conjunction with HTML code. CSS code for a page can appear along-side the HTML elements, in the page head section or in a separate file saved with ".css" as the extension.

CSS code can instruct the user's Web browser to display page items in particular ways. CSS dictates such display properties as text/ font style, colours, backgrounds, layouts, borders, margins and padding. The CSS declarations identify particular elements within a page by referring to the element type or using ID and class attributes included in the HTML markup.

The basic techniques involved in CSS are not complex, but the tricky part is testing your pages in different Web browsers, as your designs may appear with significant differences between them. Once you've learned basic HTML, learning the essentials of CSS is not difficult.

JavaScript

JavaScript is used to make Web pages dynamic and interactive. JavaScript code appears within the Web page HTML markup, either in the head or body section, or in a separate file saved with ".js" extension. Such scripts can respond to user interaction with a page, for example altering the appearance of a page element when the user hovers their mouse over it.

Writing JavaScript code is a fundamentally different activity to writing markup code. When you write JavaScript, you are effectively writing programs, with instructions for the Web browser to execute one after another. JavaScript areas to get yourself acquainted with for basic Web development include using logical structures such as loops and conditionals, variables, functions and event listeners. Try not to be too overwhelmed by learning JavaScript if you have no programming experience, as most websites only require small excerpts of code anyone can learn.

Server Side

So far we have focused on client side technologies, which are those technologies that operate in the user's Web browser (the client). Web development also involves technologies functioning on the Web server. These include database technologies and server side scripting.

Many websites store their data in databases in systems such as MySQL or XML data files, rather than coding the data directly into HTML files. In these sites, when the user's browser requests a Web page, a server side script runs on the server computer that is hosting the site. The script may carry out various processes, including querying a data source. The server side script takes the data it has retrieved and builds it into HTML structures, sending these to the user's browser to be rendered there are they would be with a standard HTML page.

If you want to continue learning Web development skills once you have a good grasp of client side development, you can try learning a server side scripting language such as PHP or ASP, as well as data technologies such as SQL and XML.

Conclusion

Web development involves many different skills, with new and emerging areas including HTML5, advanced JavaScript topics such as jQuery and mobile development. If you're new to the area this can all seem pretty intimidating, but in reality most of the technologies are accessible enough for you to teach yourself with the help of the many free Internet tutorials.

There are lots of websites for learning these skills, with W3Schools the main starting point for most people hoping to teach themselves. If you do want to get stuck into Web development, it's best to focus on one skill at a time and not worry too much about how fast your skills are progressing.

Links:

Wednesday, 29 August 2012

How To: AJAX PHP Functions

Using AJAX, you can combine HTML, JavaScript, PHP and XML to enhance websites. By adding AJAX PHP functions to your pages, you can create a more dynamic, interactive experience for your users. With AJAX, your pages can call a PHP script running on the Web server. This script can query a data source such as a relational database or XML store for new data. The script can then return this new data to the user's browser, where the client side script in JavaScript can write the new data into the page HTML. Essentially, this means that you can fetch and present new data to your users while they interact with your page, and without having to refresh the page as a whole.

Build the Page

Create an HTML page to implement your AJAX PHP processing. Use the following outline:

<html>
<head>

</head>
<body>

Here we will display new data from the server.
</body> </html>

We will place JavaScript functions in the page head area for fetching and receiving the new data from the server. Within the body, we have an element in which we will display the new data and a button to prompt the AJAX function execution.

Add JavaScript

In the script section in your page head, add the following code:

function getNewData() {
 
    //XML HTTP Request object
var xmlHTTPReq;
 
    //take care of different browsers
if (window.XMLHttpRequest) xmlHTTPReq = new XMLHttpRequest();
 
else xmlHTTPReq = new ActiveXObject("Microsoft.XMLHTTP");
 
}

Here we create an XML HTTP Request object. Next we provide the browser with instructions for when the new data is received, still inside the "getNewData" function:

xmlHTTPReq.onreadystatechange = function() {
 
//write the result to the page
if (xmlHTTPReq.readyState==4 && xmlHTTPReq.status==200)
document.getElementById("resultArea").innerHTML = xmlHTTPReq.responseText;
 
}

This code simply writes the new data to the section in the Web page with "resultArea" as its ID attribute. We have instructed the browser to handle the returned data, now we need to call the server side PHP script, at the end of the "getNewData" function:

//specify the script
xmlHTTPReq.open("GET", "get_data.php", true);
xmlHTTPReq.send();

Create a PHP Script

Next we need to create a PHP script to fetch the new data. Open a new file and save it "get_data.php" entering the following code:

<?php
$rand_num = rand(0, 100);
echo "Here is a random number between 0 and 100: ".$rand_num;
?>

The PHP script could do many different things here, such as fetching data from a database or from XML. In this case we simply return a random number for demonstration. Save your HTML and PHP files and upload them to your server. Visit the page in your browser and click the button to see the new data fetched from the server.

Options

You can also pass data to the PHP script if this suits your needs. For example, you can capture user data from an HTML form with input elements, passing the entered data for processing at the server side. A common use for this is committing the new user data to a database. To pass data to PHP, simply retrieve the user input data in the JavaScript function and append it to the PHP script URL as in this example:

//user entered data is stored in a var named "userData"
xmlHTTPReq.open("GET", "get_data.php?info=" + userData, true);

In the PHP script, you can retrieve the passed data as follows:

$passed_data = $_GET["info"];

Conclusion

You can incorporate AJAX PHP functions with various other technologies such as XML and jQuery. The emerging HTML5 features are also set to provide enhanced levels of communication between client and server using such utilities as Server Sent events, so the browsing experience is going to become more and more responsive.

See also:

How To: HTML5 Local Storage

The improved storage model in HTML5 is one of the most anticipated new features. Using Local Storage and Session Storage, your websites and Web applications can store much more data at the user's browser, the client. Storing data at client side is a common task with many Web projects, but until HTML5 there were serious restrictions on what you could do in this regard. In this tutorial we will outline the basics of using HTML5 Local Storage in a Web page, with JavaScript code to manage the data stored.

There are numerous advantages to the improved Local Storage utility in HTML5. As well as having the ability to store greater amounts of information at client side, your apps can utilise this data in a more efficient fashion. Storing data at the client inevitably reduces the need to continually fetch it over the network.

The Web Page

Your HTML5 Web pages should all have the same outline structure, with the HTML5 DOCTYPE. Use the following as a guide:

<!DOCTYPE html>







In the body we will place our page elements and in the head we will use a JavaScript section. Add these HTML elements in the body section of your page:

Here we will display the local data

Type some text in the box then click the button to store it locally.


This code creates a text area for the user to type some text into. Under the text field is some informative text telling the user to input text then click the button to store it locally.

JavaScript Function

Now create a script inside the head section of your HTML5 page. Add the following in the head:



Inside the script, add the following function:

function storeLocally() {
 
}

This is the function that will execute when the user clicks the button. Inside the function, first get a reference to the "div" element we want to write the result into:

var showDataElement =
    document.getElementById("local_data");

We are going to create a variable within the browser's Local Storage object. When the user returns to the page, the variable will be set from the last time, unless they have deleted the data. If the variable already exists, we are going to overwrite it with the new data. However, let's first check whether it has already been set and if so what was entered before:

var storedData = localStorage.typedData;
if(storedData==null) storedData = "";

Now let's get the newly entered data from the text field:

var newData = document.getElementById(inputData).value;

Update the Local Storage object with this new data:

localStorage.typedData = newData;

Finally, let's write the previous data and new data to the browser as a visible response to the user:

showDataElement.innerHTML = "

Last time you entered:

" + storedData + "

This time you entered:

" + newData;

When the script executes, the previously stored data will no longer be stored. If you wanted to keep a record of everything the user enters you could append the new data to the Local Storage variable rather than replacing it each time. This code is simply an example to illustrate the practice of using Local Storage in HTML5, but you will of course need to tailor it to the needs of your own projects.

Alternatives

The other main new storage option with HTML5 is the Session Storage. Unlike Local Storage, data stored in the Session Storage object only persists for a single user session. This is obviously more sensible if you don't need your stored data to stay around between user visits to the site. If you do need the data to remain accessible, use the HTML5 Local Storage option outlined above.

Related Links

Tuesday, 28 August 2012

Web Development Concepts: Client and Server

To put it simply, this is about the relationship between two computers: yours and the server. Client stuff happens on your computer and Server stuff happens on the server. However, although the Client stuff runs on your computer, it's still stored on the server. Make sense? Let's explore it in a bit more detail.

Who's Who

The terms Client and Server are used in Web development contexts. As with all tech terms, these are often used as a concise reference, but are unfortunately also often used when another term would actually be easier to understand. For whatever reason, a lot of geeks seem to love using mystifying language, perhaps to compensate for their crippling social inadequacies (and I include myself in that category) - who knows?

Anyway, Client and Server are fairly easy to get to grips with. They simply refer to where the different functions of a website are run. Server refers (as you might have guessed) to code etc that is executed on the Web server, and Client refers to things that happen within the browser (e.g. Firefox, Internet Explorer, Opera, Safari, Chrome) as it runs on your computer.

The Network

The terms Client and Server are used to reflect the relationship within the computer network (i.e. the Internet). However, you don't need to understand the ins and outs of networking to understand these terms.

The Process

When you browse to a website, a number of things happen. The data and programming code etc for the site are stored on the Web server. The website address identifies the location of the server, and the browser requests the relevant page from this location.

The Web browser receives the HTML content from the server, which it is able to interpret and display as a Web page, together with the text, images, data etc and style rules determining how it should be displayed.

A wide variety of technologies are used in Web development, some running on the server, and some on the client. Your Web browser is basically able to display HTML, but this HTML may be served to it in different ways.

Models

The traditional Web model meant storing HTML pages on the server which are simply sent to the browser and displayed. In this model, the content of a site was all directly written into the HTML files, and had to be manually changed if the information needed changed. However, as sites developed, there became more of a focus on data-driven sites that are said to be 'dynamic'. This simply means that the sites use data and other resources to build the Web pages at the time that they are requested by a browser.

Server side programming is one of the main tools involved in this. Server side languages such as ASP and PHP run on Web servers, creating HTML when they run and sending it to the requesting browser to be displayed. In a typical model, the Web server will have a database on it, plus the other content such as images etc. When someone requests a page, the Server side scripts execute, query the database for any relevant information and write this back to the browser in the form of the HTML page.

Client side programming refers to functionality that is carried out within the browser itself. Many sites try to be interactive in different ways, and one such way is using a Client side language such as JavaScript. This is typically used to achieve things like interactive menus and styles that make the elements in a site change their appearance as you interact with them using your mouse and keyboard - these are generally carried out using CSS (Cascading Style Sheets).

With the emerging techniques in HTML5 and CSS3, websites are becoming even more responsive, interactive and dynamic from both client and server side.

Client and Server Working Together

Some uses of Web technology use the two approaches of client side and server side development in tandem, such as AJAX, as well as many jQuery and HTML5 functions. You'll see examples of these on lots of sites, where an element of the page is updated without the page as a whole being refreshed. In this case a Client side script in JavaScript often sends a request to a server side script (e.g. in PHP), with the returned data displayed in the browser without it having to request a new page. With HTML5, the client side code doesn't even have to request something from the server, the sever can simply push new data for the browser to display.

Usage

If you see someone referring to Client Server Applications or Client Server Development etc, this is really just a reference to the use of a variety of technologies deployed both on the Server and Client. These days, Web development pretty much always involves both so the terms are often redundant. Some developers do specialise and focus on one side or the other, particularly where large Web applications are involved.

Relevance

If you are planning to get involved in Web development yourself, it is vital to understand the process that executes when people view websites. However, if you are only planning on accessing the Web as an end-user, you really don't have to understand these concepts, although they are interesting if you're an utter geek like me.

See also:
What is Dynamic Content?
What is Web Content?
How to Get Started with Web Development

An Introduction to HTML5 Features

HTML5 promises to make a serious impact on the future of Web design and development. At the moment the level of browser support is still pretty low, but that doesn't mean you can't start using the new HTML5 features in your projects. For those users whose browsers do support the new features, you can create sites that are more engaging and accessible than before. As long as you ensure your sites are still accessible to the users with a lower level of browser support, providing alternative content items if necessary, you can get stuck into HTML5 now.

HTML5 DOCTYPE

The HTML5 DOCTYPE is incredibly simple, which is great news for developers. No more copying and pasting complex and unreadable DOCTYPE declarations, not to mention trying to decide which one to go for and then the inevitable hassle of getting your pages to validate. With HTML5 there is one very straightforward and memorable DOCTYPE declaration. Here it is:

<!DOCTYPE html>

Yes, it really is that easy! Just follow this with your HTML element plus head and body content and away you go. There is no other fundamental difference in terms of page structure with HTML5, so you can update existing markup without too much trouble.

New Elements


Among the most noteworthy HTML5 features are the new elements. With HTML5, the approach to page structure is fundamentally different. HTML5 includes a range of new structural elements: header, footer, nav, aside, section and article - we'll go through these next. HTML5 also includes new media elements such as video and audio, which we'll also briefly introduce. There are actually lots of new elements in HTML5, we're just going through some of the more notable and accessible ones.

Before we get onto actual markup examples, it's worth understanding that HTML5 is designed for more semantic Web design and development than previous versions. In an abstract sense, this means that the markup elements themselves indicate something about the meaning of the element content, rather than being purely structural. Don't worry if you're baffled about the semantic Web development concepts, as they will become clear as we work through the structural elements below.

Structural Elements

The new structural elements in HTML5 allow you to define the parts of your page as semantic items. The header element can be the header content for a page or a section of a page, while the footer element models content for the footer of a page or section. These are indicated by the HTML5 header and footer tags as follows:

page header

Here is some header text

Here is the main content area
Here is the footer info

Most pages contain at least on navigation section, which in HTML5 you can use the nav element for:



The section element defines any kind of section you choose to divide your page into, using section tags as follows:

Here is some info

picture

Grouped together within a section


The article element is designed to be used for a chunk of content that can stand in its own right, i.e. one or more content items that would make sense when presented on its/their own. Examples of article content would be forum and blog posts, news articles etc. The article tags appear as follows:

Here is some news

This is the content of the news

news picture

The aside element provides supplementary content for another content item. The aside tags should include information or other content that is relevant to the content within the element it is contained within, i.e. extra info about the parent element content:

Here is some info

As you can see, the structural HTML5 elements allow you to build a level of logic and meaning into your Web page markup.

Media Elements

HTML5 includes a range of media elements including those for presenting video, audio and the canvas element for JavaScript delivered graphics. The video tags can be included as follows:



The audio tags can be included as follows:



As you can see both the audio and video elements include source elements indicating the names, locations and types of the media files to play.

The canvas element is potentially one of the most exciting new HTML5 features, as it allows your pages to serve graphics through JavaScript directly to your users as they interact with the site. The following code demonstrates the canvas tags:




This draws a simple rectangle outline.

Input Elements

HTML5 offers new options for capturing user input within Web forms. The new elements include datalist, keygen and output. Since these are a little advanced for this introductory article, we won't go through them in detail. If you want to find out how to use the new HTML5 form elements, see the links at the bottom of the article.

Browser Support

At the moment, browser support is the number one issue to consider when building HTML5 websites. The support level is not great at present, but ultimately HTML5 will make it easier to provide support for users with legacy browsers. The browser software programs are of course always evolving, so your HTML5 markup will become more and more usable all the time. There are lots of good resources around the Web listing which HTML5 features are supported by which browsers, so these are well worth checking out on a fairly regular basis if you're planning on using HTML5 now. The HTML5 Please site is one of the most reliable sources.

Although resources like HMTL5 browser support sites are useful, they are not exhaustive and cannot be relied on for guarantees about browser support. As always, it's essential that you test your own sites on as many browsers, device types and operating systems as you can. This is a hazy area at the moment and is likely to be for some time. On the plus side, by getting stuck into HTML5 early on, your future development projects will benefit from the more semantic and user-friendly approach you will have already adopted.

See also:
How To: HTML5 Local Storage
Why Web Developers Are Excited About HTML5 and CSS3
How to Get Started with Web Development

Monday, 27 August 2012

Implementing Image Links With JavaScript

Most Web pages link to other pages, within the same site and on other sites. HTML anchor elements are the primary tool used to implement these links. However, JavaScript functions can also implement links between pages. These functions can execute on user interaction with the mouse, such as clicking an image element.

Web pages often include clickable images, particularly in the header area, for example with Web page banners. Using a combination of HTML and JavaScript code, developers can create Web page banner elements that link to other pages. Within the HTML markup for a banner image, the developer can include an event listener attribute to detect user clicks. When the user clicks an image, the JavaScript code can prompt the browser to open a new page. Web page banners can provide visually engaging, interactive elements within sites.

HTML Images

To include images within a Web page banner section, developers can use the HTML image element. The following code demonstrates:


This code includes an image in a dedicated page section. The image element uses a single self-closing tag, with the source attribute indicating the location and name of the image file for the browser to load and display. The "alt" attribute provides text to display if the image file cannot be loaded. The banner for a page may contain multiple different images, linking to different locations.

This markup code demonstrates a basic image element, which instructs the browser to display the image. However, clicking on the image will have no effect. To make the image clickable, the developer must add a click listener.

Click Listener

To implement a link through JavaScript, developers include event listener attributes within their HTML elements. The following extended code demonstrates:

banner picture

This code specifies a JavaScript function for the browser to execute when the user clicks the image element. The function call includes a text string parameter specifying the page to fetch. The address can be a relative or absolute URL (Uniform Resource Locator).

JavaScript Function

Web pages can include sections for JavaScript functions between the opening and closing head tags. The following code demonstrates a script section with a function outline inside it:



This function is called when the user clicks the image. The parameter passed represents the page to browse to. Inside the function, the developer can include code instructing the browser to load the new page.

Open Page


To instruct the user's Web browser to load a particular page, JavaScript code can use the Window object. The following code demonstrates:

window.open(linkPage);

The Window open method allows additional optional parameters. Using these, developers can specify where to open the new page, whether in a new window or in the current one. The "specs" parameter allows developers to indicate details of the browser window when opening the new page, including dimensions. The replace parameter indicates how the new page should be handled in the browser history. Once this code is included in the JavaScript function, users clicking the HTML image element will cause the linked page to load.

Alternatively, JavaScript code can use the Document and Location objects, as follows:

document.location.href = linkPage;

The page address is passed into the function as a parameter when the click event is triggered. The HTML markup for the image lists the actual address to fetch.

See also:
How To: AJAX PHP Functions
Displaying a Substring in JavaScript

Monday, 20 August 2012

How To: Javascript PHP Function Calls

Calling JavaScript functions from PHP is a common task in Web development.

When you build the HTML content of Web pages in PHP code, there are likely to be times when you need to call JavaScript functions. In dynamic websites, it is not unusual for pages and scripts to contain PHP, JavaScript, HTML and sometimes other types of code such as CSS, so the development process can become confusing. However, by building each of the elements in your website pages one at a time, then working out how to coordinate them, you can integrate the technologies with no trouble.

Before You Start

When creating a Web page containing JavaScript, PHP and optionally other languages, as well as implementing the interaction between them, it's good to first make sure you have a clear idea of the order in which the parts of your page are being constructed. If your PHP code is building HTML then writing this to the browser, your JavaScript function calls will need to be contained within these HTML structures.

JavaScript PHP function calls are dealt with at the same time when you write your scripts. However, when your pages are actually visited and interacted with by users, the two aspects of functionality are not executed at the same time. Don't worry if you still find these concepts confusing, as the best way to get to grips them is by putting them into practise. Learning to combine PHP with JavaScript is a good exercise to equip yourself with basic Web development skills.

Page and Script Outline

Within PHP files you can alternate between HTML and PHP code. Create your basic Web page outline as a PHP file containing HTML structures, as follows:

<html>
<head>
</head>
<body>
<?php
//PHP code goes here
?>
</body>
</html>

Copy the code into a new file in a text editor and save it with ".php" extension, for example "yourpage.php" - reflecting whatever the page content is.

Insert Your JavaScript Function

Add your JavaScript function. You can include JavaScript in a separate file called from the head of your page as follows (between the opening and closing head tags):



Alternatively you can include the JavaScript code directly within the page head section as follows:



This function is for demonstration, but you can include whatever function you intend to call from your PHP code.

Call JavaScript From PHP

Insert your PHP code within the PHP section of your page, as in this example where a series of buttons are created:

<?php
$count;
for($count=0; $count<10; $count++)
echo "<input type='button' value='button ".$count."'
onclick='yourFunction(".$count.")' />";
?>

Each button is given a number, so you will be able to see whether the script is working at a glance. Notice that in the section of code where PHP is writing out HTML, both single and double quotation marks (inverted commas) are being used. This is to distinguish between the PHP and HTML content. Double quotes are used within the PHP to delineate parts of the code to send to the user's browser, and single quotes are used within the HTML that is actually sent.

Upload and Test

Upload your page to your Web server. Browse to the Web page in your Web browser and test to see whether it works. Click on each button in turn - you should see an alert dialog box pop up, demonstrating that the JavaScript function is being called, and that the number is also being passed accurately to it.

If your page does not function correctly, check your code, ideally by reading it in a text editor with the ability to highlight PHP code. Try viewing the page source in your browser to see what HTML has actually been sent from the server side script.

Alter to Suit

This is the basic pattern for most PHP JavaScript function calls, but you will need to amend the script to suit the purpose of your own pages. As well as the HTML content, you will need to alter the PHP and JavaScript to address your own requirements, but the principle of calling a JavaScript function from PHP remains the same. Make sure you test your pages thoroughly before your website is exposed to users, as technologies such as JavaScript often behave differently across browsers.

Alternatives

As with most Web technologies, there are many different possible ways to combine JavaScript and PHP. The use of single and double quotation marks is just one option for handling JavaScript function calls from PHP. An alternative is to use escape characters, which indicate that a character is not being used in the normal way. For example, instead of the single inverted commas you can use all double and insert an escape character before those you want to appear in HTML:

echo "<input type=\"button\" value=\"button ".$count."\"
onclick=\"yourFunction(".$count.")\" />";

This is the method preferred by many developers, but as you can see the code can quickly become difficult to read. Which option you go for is entirely up to you, but personally, when escape characters are used excessively I tend to lose track of where I am and be more inclined to make syntax errors. As with everything in programming, it's best to stick with whatever approach makes the most sense to you.

Being able to read your code is always important, particularly where different languages are being used, as in this case, where it's vital to be able to see JavaScript in PHP code at a glance.

Notes
  • Create your Web pages incrementally, adding one element at a time and testing regularly. This makes mistakes easier to find and fix.
  • When you develop Web pages with both server side and client side languages, it's essential that you understand what happens on the server and what happens in the browser. If you're unsure about these things, it's well worth taking the time to familiarise yourself with the basics of the technologies involved.

See also:
How To: AJAX PHP Functions
How To Send Mail in PHP

Expand and Collapse HTML Text

Many websites display text that users can expand and collapse while interacting with a page. This allows you to give users control over what they can see when viewing your pages and can result in sites that are more usable. By using a small amount of JavaScript code in conjunction with HTML, you can expand and collapse Web page text elements when the user presses a button or other visible element. Giving users control over your pages in this way can help them to process essential information about your business and services.

Text Element

To expand and collapse a text element in an HTML page, you first have to include the text content. The following sample code demonstrates including a paragraph element with some demonstration text in it:

Here is some text


The opening paragraph tag includes an ID attribute so that the JavaScript code for the page can identify the element, altering its appearance. The paragraph could optionally contain a much longer section of text. The element does not need to be a paragraph, with many other options including <div> elements.

Interaction

To give the user control over whether the text is expanded or collapsed, you need to include an interactive element. This can be an HTML input element or any element the user can click, such as an image. The following code demonstrates a button input element, which can be included before or after the text element:



The button appears with "show/hide" displayed on it so that users understand its purpose. When the user clicks the button, the browser will execute a JavaScript function named "toggleText" which will also be included within the page code.

JavaScript Function

The page head section can include a JavaScript function to execute on user interaction with the button element. The following JavaScript section can appear between the opening and closing <head> tags in the page:



This code includes the function indicated within the "onclick" attribute for the button element. The script section first creates a variable storing the current state of the text, which is expanded when the page initially loads. Within the function, the code first gets a reference to the text element within the page, using its ID attribute. The remainder of the function must handle expanding and collapsing the element.

Collapse

To collapse the element, JavaScript code can set the display style property. The following code demonstrates, added inside the function, after the line in which a reference to the element is stored in a variable:

if(isShown) {
textElement.style.display="none";
isShown = false;
}

This conditional statement checks the variable to establish whether the text is currently shown or not. If it is, the code sets the element display property to "none" which both hides and collapses the element within the page. Finally, the code toggles the boolean "isShown" variable to false, indicating that the element is now hidden.

Expand

To expand the text, the function can alter the style property of the text element again. The following code demonstrates, added after the "if" statement but still inside the function:

else {
textElement.style.display="block";
isShown = true;
}

The "else" statement only executes when the "if" statement returns a false value, which occurs when the element is currently collapsed. The code first alters the display property to "block" which both shows the text content and expands the element it is contained in. Finally the code resets the boolean variable to true, indicating that the element is currently shown. Each time the user clicks the button the element will toggle between expanded and collapsed.

See also:
Implementing Image Links with JavaScript
Displaying a Substring in JavaScript
Using Scripts in HTML Pages

Monday, 6 August 2012

Special Characters In Programming

Computer programming and markup code is naturally written with alphanumeric and other characters. However, within each language or technology, there are normally a set of characters that have a specific meaning or usage. This means that special consideration has to be given when those characters are used, for example when text strings are output for reading by users. The special characters for particular languages vary, as do techniques for handling them.

Coding

Whether a language is for programming or markup, there are typically always characters that cannot be used in the normal way. Those characters that have a specific meaning separate to their mainstream typographic use are generally considered special characters.

For example, within HTML, the tags surrounding Web page content use the "less than" and "greater than" characters:

<p>

This means that if those characters are to be used within an HTML page, they need to be included using their ASCII or ISO codes. For "less than" there are two options:

&#60; &lt;

Problems

When coding is carried out without sufficient handling of special characters, a number of problems may arise. For programming languages, code may not compile, and if it does there may be runtime errors.

For Web coding such as HTML markup, pages may not be rendered correctly, and their appearance may differ across Web browsers. Tools used to validate HTML and other Web markup to check whether it is well-formed will also show errors if special characters are not included properly.

Types

The types of special character depend on the language being used. In general, punctuation and non-alphanumeric characters may need special handling. There may also be characters that have a specified meaning within a particular language. For example, in many languages it is common to include text strings within quotation marks, for example in PHP:

$text="Here is some text";

If the text string also contains a quotation mark, this may cause a problem, as the compiling program will interpret the second quotation character it encounters as the end of the text string, preventing it from being able to process the code that follows.

Coping

The main technique for coping with special characters is to use an "escape" function. This is a shorthand syntax method letting the compiler know that a character is not being treated as it would be normally. For example, to include quotation marks in the PHP string:

$text="Here is \"some\" text";

The backslash is a common escape character used in many languages. The escape character is typically included immediately prior to the special character, preventing the compilation process from going wrong when it encounters the character in question.

Links

Special Characters | Webmonkey
Common HTML Validation Problems
Characters (The Java Tutorials > Learning the Java Language > Numbers and Strings)
PHP: htmlspecialchars - Manual
Special Characters - Microsoft

Thursday, 26 July 2012

Using Scripts in HTML Web Pages

Web pages use a variety of technologies to present interactive content to users. If you are responsible for a website for your business, you can enhance its interactivity using scripting. The content and structure of a site generally involves HTML markup, which you can manipulate using scripting in JavaScript code. With website scripts, you can respond to user interaction with your page elements, for example detecting users moving the mouse over a particular part of the page and altering its appearance in response.

1.

Create a script area within your page. Open your HTML page in a text editor. Enter a script section within the head area as in the following outline:

<!DOCTYPE html>
<html>
<head>

</head>
<body>

</body>
</html>

The script content will appear between the opening and closing script tags in the page head, with the page content inside the body section.

2.

Detect user interaction. JavaScript functions typically execute when events occur, such as user interaction. Within your HTML page elements, you can detect particular types of interaction. The following HTML markup instructs the browser to execute a particular JavaScript function when the user clicks the element:

a picture

The "onclick" code indicates a click listener. When the user clicks the image, the browser will call the function named "changeElement" which you will create next. By including "this" within the function brackets, you pass a reference to the image element as a parameter to the function. Alter the image "src" attribute to indicate the name and location of your own image.

3.

Create a JavaScript function. In the head section, between the opening and closing script tags, enter your function outline as follows:

function changeElement(elem) {
//function content

}

This is the function outline. The function name is followed by a parameter in the brackets, matching the syntax you included in your image element click listener. Within the function, your code has access to the element reference passed to it, so it can manipulate the image element within the page.

4.

Respond to user interaction. Inside your script function, between the opening and closing curled brackets, enter the following code for demonstration:

elem.style.marginLeft="50px";

This code uses the element reference parameter to alter its appearance in the page. To demonstrate the principle, the function alters the element style properties, in this case applying a margin to the left of it. You can carry out many different types of element manipulation within your script function.

5.

Test your page. Save your HTML file and open it in a browser to test it. Click the image to prompt the script function. You should see the element move instantly to the right, when the margin is applied to the left. To see the effect more than once, refresh the page and click the image again.

Notes
  • Web page scripts can detect multiple different events, including the user moving their mouse on and off elements.
  • If your scripts become complex, they may have unpredictable results, so testing is essential.

See also:
How To: JavaScript PHP Function Calls
Programming: Handling Code Errors
Web Development Concepts: Client and Server
Web Development Concepts: Static Vs Dynamic

Monday, 23 July 2012

Why Web Developers are Excited About HTML5 and CSS3

If you are involved in Web design, development or just the Web itself in any way, you will almost certainly have become aware of the excitement about the emerging developments in HTML5 and CSS3. This article will attempt to explain some of the reasons for this excitement. HTML5 and CSS3 represent more than a normal update of the languages in question, as they include a number of substantial changes that promise to fundamentally alter the way developers create pages and sites.

OK, so what are HTML5 and CSS3 anyway?

HTML is the main markup language (Hypertext Markup Language) used in Web pages. When you visit a website, the content items you see (text, images, media etc) are included in HTML markup code. HTML uses tagged code to define the overall structure of a page, with elements enclosing the content items. When your browser receives the HTML markup code for a page, it interprets it and presents it to you accordingly.

While HTML defines page structure, CSS (Cascading Style Sheet) code determines the styling of a page, including layout and various other visual aspects of what you see. The way the content of a page is displayed is therefore determined by both HTML and CSS code. HTML5 and CSS3 are the most recent versions of these two specifications. Essentially, with HTML5 and CSS3, developers have new techniques to choose from when building pages.

Most websites use client side scripting in JavaScript in conjunction with HTML and CSS. This allows developers to deliver interactive components. HTML5 and CSS3 include new options for such interactive sites, including the ability to build advanced media items such as animation and drawing functions.

Fine, what does HTML5 offer over previous versions then?

HTML5 introduces a range of new elements that developers can utilise. The most notable new elements are the structural elements, media elements including canvas, and new input elements for capturing user information through website forms. The structural tags include "header", "footer", "article", "section", "nav" and "aside". These allow developers to define sections of a page in a more logical, meaningful way than before. HTML5 also includes new tags for embedding media items such as audio and video in a much more straightforward way. The canvas element is one of the most interesting additions, as Web pages can create graphics using JavaScript drawing functions, building these graphic items while the user is viewing the page.

And CSS3, what does it bring to the table?

CSS3 includes a variety of new properties and functions, allowing developers to create a greater level of interaction than before. The transform and transition functions create interactive animations in both 2D and 3D, while the "keyframes" rule defines animated sequences that elapse over time. CSS3 also introduces advanced user interface styling and the ability to use fonts without the user having them installed on their own computer.

What does semantics have to do with this?

You will see people referring to emerging techniques in Web design as being semantic. This basically means that the actual markup for a page will include an indication of semantics, or meaning, by letting the browser know something about the content of an element. For example, in the past many HTML elements simply grouped a chunk of Web page content in a meaningless way. The HTML defined the content and the CSS styled it, with only the developer and user interpreting the meaning of the content in any way. With the new structural elements in particular, HTML5 markup indicates a level of meaning that the browser can interpret and use to make the page more accessible to the user, whatever their environment happens to be.

How do HTML5 and CSS3 relate to Flash?

Many people are also making claims about the impact that HTML5 and CSS3 will have on other technologies such as Flash. It's certainly still a bit early to make huge claims about how much longer Flash will last. However, with HTML5 and CSS3, developers can achieve the kinds of interactive multimedia component that was previously mainly done in Flash. By using these new specifications instead, developers can create the same results in a way that is more accessible to different users.

Sounds good, why isn't this stuff all over the Web already?


The main factor delaying the adoption of HTML5 and CSS3 is browser support. The main browsers are all working on increasing support of these new standards, some faster than others, but full support is still a long way off. For this reason developers cannot assume that users will be able to engage with new effects created using the most recent specifications, and must provide alternatives for users with older browsers.

See also:
An Introduction to HTML5 Features
How To: HTML5 Local Storage
Using CSS3 Fonts
How to Get Started with Web Development

Web Development Concepts: Static Versus Dynamic

What is the difference between a static and dynamic Web page?

Essentially, whether a Web page is static or dynamic depends on what happens between the user making a request to see it, and the server sending the requested content to their browser. It makes no difference to users whether a page is static or dynamic, but is relevant to developers, as each model uses different techniques and technologies.

Essentially a static page is one whose content is stored in static, unchanging form in a document on the Web server, while the content of a dynamic page is only created when it is requested for viewing.

What happens when someone browses to a page?

When you browse to a Web page, for example by clicking a link or typing its URL into your browser address bar, your computer sends a request message to the Web server on which the requested page is hosted.

With a static page, the content is simply sitting in a file, typically in HTML, and the content of this file is returned by the server to your computer, where it is displayed in your browser window. For example, if you had a file saved as "page.html" on your server in the root directory, and browsed to it as follows:

http://exampledomain.com/page.html

The server would respond by sending the content of the file.

For dynamic pages, the process is different. Dynamic pages use programming languages such as PHP. In this case you would save your script on the server, for example using the name "page.php", and it would contain programming code as well as HTML code.

When the page is browsed to this time:

http://exampledomain.com/page.php

The code within the script file is executed (run) on the server. The server side program may do many different things, but typically one of them will be to build a Web page with HTML content and send this to the user's browser. The browser displays this HTML the same way it would have if the page had been static - the difference lies in what happens on the server, and makes no difference at the user (or "client") end.

How exactly is this different?

Static and dynamic pages don't just use different file formats, they use a fundamentally different technique. Static pages typically contain only markup code, whereas dynamic pages also contain programming code.

The content of an HTML file is basically text, images etc contained within a tree structure, with each element delineated by tags, each pair of opening and closing tags comprising an element as in the following example paragraph:

Some text...


This is HTML markup, and its structure, together with formatting such as CSS, tells the browser how the content of each element should be laid out and displayed.

With a dynamic page containing server side code, a different process takes place. The page script is executed according to its own logical structure, and as it goes it builds HTML structures and writes them out. This example PHP performs a simple calculation and writes the result out in HTML:

<?php
$answer=3*2;
echo "<p>".$answer."<p>";
?>

A typical PHP script will also do other things such as connecting to a database and querying it for data to write out as part of the HTML.

What are the advantages to using dynamic pages?

There are many advantages to using dynamic pages, the main one being the fact that they contain dynamic data. By connecting to a database, a dynamic page can potentially offer different content each time it is viewed. Static page content remains the same unless the page files themselves are manually changed, whereas dynamic pages populate their content at the time of viewing, according to what happens to be in the data store at that particular time.

It is often the case that many pages within a site will contain the same, or similar content. If this content needs to be changed, in a static site each page on which it occurs will need to be changed in turn. However, using dynamic scripting, the piece of content can be contained in a single, dedicated script, and this script can then be called from each page on which the content item appears. If the content needs to be changed, it only has to be changed in one place, i.e. the dedicated script, or the database if this is where it comes from.

Dynamic sites are therefore easier to maintain and to make changes to, while still keeping a consistent appearance and behaviour. If a site is being built for commercial purposes, being able to store the data in a database is also an advantage in itself.

Are there disadvantages to using dynamic pages?

The only potential disadvantage to using dynamic pages is the fact that a greater range of technologies, and therefore skills, are involved. A certain amount of programming expertise is necessary, and in most cases database development as well. However, if you're thinking about trying dynamic Web page development, don't be put off even if you have no programming experience, as these skills are actually relatively easy to pick up. There are lots of online tutorials and guides, so you really can teach yourself.

Do I need to use dynamic pages?


No! Using dynamic pages is not obligatory. However, depending on the purpose and nature of your site, it may be a real advantage. Setting your dynamic site up may seem an intimidating prospect, but once this is done the site will become much easier to amend and maintain. If your site only contains a small amount of simple information that does not need to be updated very often, there's probably no need to learn Web programming if it isn't something you're interested in.

How do I get started creating dynamic pages?

The first thing is to make sure you have a sound enough grasp of the basic Web technologies that are used in both static and dynamic pages, including the initial skills for making a Web page using HTML, CSS and JavaScript. You don't need to be at an advanced level, just make sure you understand the basic principles and practices.

Next is learning a server side language. I would recommend PHP, which is available on most Web hosting platforms. Start with the basics and build your knowledge incrementally, this is the only way to do it, and don't worry if you feel you're making slow progress, it will all fall into place eventually!

If you're building a dynamic site, you'll probably want to use a database. MySQL is available for free on many Web hosting packages and is a good system to start with. You can learn SQL if you like, but if your host provides phpMyAdmin, you can carry out most common tasks using the browser interface. If you're unsure about how to structure your database, it may be worth finding out a bit about relational database modelling.

Related Links
MySQL :: Developer Zone
MySQL Tutorial - Introduction
phpMyAdmin
PhpMyAdmin Tutorial
PHP: PHP Manual - Manual
PHP Tutorial
SQL Tutorial

Tech Interpreter Links:
Why Web Developers are Excited About HTML5 and CSS3
Using Scripts in HTML Pages
What is Web Content?
What is Dynamic Content?
Web Development Concepts: Client and Server
How to Get Started with Web Development