Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

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

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

Sunday, 26 August 2012

Displaying a Substring in JavaScript

The JavaScript language provides a diverse range of functions for string handling within websites. This allows developers to process user input and other strings in various ways. Substrings are among the most useful of these functions, as they allow you to access and process smaller sections of a larger strings where necessary. Using substrings in JavaScript is a straightforward task, worth learning at an early stage in JavaScript programming as it often proves useful.

Preparation

Prepare the string you plan on processing within your script. The following example code creates a string variable with some arbitrary text in it:

var wholeString = "ABCDEFG";

You can use any text string you like, including any you already have stored within your script, so this step is purely for demonstration. If you do already have a string, make sure you are storing it in a variable as in the example, as this will facilitate the substring processing.

Processing

Process the substring function on your string. Using the following code syntax, carry out the substring operation on your text variable:

wholeString.substring(1, 5);

This method takes the start and end string positions as parameters. The first index indicates the substring start position, while the second index is one after the final character to be included in the substring. Using the example text string, this operation would result in the text "BCDE".

Alternative

Process the "substr" function on your text string. The "subtr" is an alternative option for processing substrings in JavaScript, working in a slightly different way to the main substring method. To achieve the same result as the substring example, you can use the following syntax:

wholeString.substr(1, 4);

The second parameter in this case indicates the total length of the resulting substring. The first parameter is simply the starting character as in the first example. You can optionally carry out both functions using only a single parameter indicating the start position, and the substring will contain the remaining characters in the original string, for example:

wholeString.substring(1);
wholeString.substr(1);

Both of these will result in "BCDEFG".

Store

Store the result of your substring operation in a variable. Whichever method you choose, you can store the result in a variable for further use as follows:

var subSection = wholeString.substring(1, 4);

Using the alternative "substr" function:

var subSection = wholeString.substr(1, 4);

This allows you to access the substring at any point in your script after the operation has been carried out.

Display

Display your substring. There are different options for displaying strings and sections of strings within the Web browser, so which method you adopt will depend on your own project. The following code included within the body section of your HTML inside a "script" area will simply output the substring as text:

document.write(subSection);

If your JavaScript function is in the page head or another script and you want it to write into the page body, you can use the following to include it within an HTML element with a specific ID:

document.getElementById("anelement").innerHTML = subSection;

Notes

  • The string class in JavaScript provides lots of other functions you may find useful.
  • Make sure you test your string processing using realistic examples of text, particularly if user input is being used, as unexpected text may prevent your code from functioning correctly.

See also:
How To: AJAX PHP Functions
Implementing Image Links with JavaScript
How To: JavaScript PHP Function Calls

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

Programming: Handling Code Errors

Encountering code errors is essentially a part of the daily reality of programming. The more programming you do, the more you begin to realise that the activity of coding is in large part about finding and fixing the mistakes you've made. You can forget about not making mistakes, unless you're a robot. Accepting the fact of code errors is actually a positive step in your development as a coder, as programming is primarily a problem solving task, which is ultimately why it's a rewarding one - honest!

Even if you could write an entire application without a single syntax error, you're always going to come up against errors or unforeseen problems with your code logic and implementation so it's vital to be able to handle them.

Approaches

Whether you're struggling with syntax errors (referred to as compile time errors if they prevent program compilation from occurring successfully), runtime errors, or logic errors preventing your programs doing what you need them to, there are a number of key helpful techniques.

These methods can help resolve code errors more quickly, and in some cases prevent them from arising in the first place. Effective error handling involves getting into good habits with your routine coding practises, as well as what you do when problems crop up, i.e. your debugging skills.

Planning

It may not be the sexiest part of programming, but taking the time to plan your development activities properly will inevitably reduce the amount of debugging you end up having to do. It's always tempting when you've just started working on an application or project to get stuck in start coding straight away, but it is genuinely the case that spending even a small amount of preparation time makes the development process less error prone and stressful.

Use a Code Highlighting Editor

For many developers this one goes without saying, but if you're perhaps just getting started as a coder, you might be amazed by how much easier it is to work with code that is highlighted. Depending on the language or technology you're working with, you may want to simply opt for a decent text editor that can highlight source code, such as Notepad++ on Windows or Gedit on Linux.

Use an IDE (Integrated Development Environment)

Depending on which language or platform you're working in, there may be one or more IDEs you can use for it. Integrated Development Environments come with a number of different tools, for example to help with debugging, visualising your applications and with the development process generally. At the very least, an IDE will highlight your code reliably, and in most cases will flag up any syntax errors so that you will typically catch them before you even attempt to compile and run your program.

Most IDEs also have some sort of error or output console which will indicate information about any runtime errors that occur. You can also use these output consoles for trace statements, as explained in the below section.

Use Comments and Documentation

It's something many programmers don't have the best habits for, but effective use of comments is one of the key defences against errors. Ideally, if you outline what the different elements in a program are going to do with comments before you even start writing code, as well as continuing as you write the code, this will provide a clear picture of what's going on throughout the development cycle.

Comments aren't just to help other people read and understand your code, as the more code you write the more you'll understand the regular nightmare of looking back at your own code and being totally baffled by it, sometimes only a short time after writing it in the first place.

Depending on the platform you're working in, and the size of application you're developing, you may want to consider documentation as part of your daily coding routine as well. For a language such as Java, the process of generating documentation is easily automated using tools such Javadoc, which again make the development process less frustrating.

Use Indentation and Whitespace

Effective use of indentation and whitespace in your source code files is another simple but often neglected practise that makes development much easier. Indenting your code makes the overall structures within it visible at a glance, particularly where structures such as conditionals, loops and class declarations are being used. If you're using an IDE, it may automate the process of correcting your indentation, particularly useful if it's in a bit of a mess.

Develop Incrementally

Sometimes you have to go against your instincts with programming to spare yourself some headaches down the line. If you've just started on a project or have just worked out how you want to approach part of it, it's tempting to get a load of code down quickly and without stopping. However, the more code you write in between testing, the more difficulty you'll have finding the syntax and logical errors within it.

Writing small amounts of code one at a time and testing regularly makes for programs that have fewer bugs, and in which the bugs are easier to locate and fix. If you're worried about remembering the details of an algorithm or solution to some problem you've been having, i.e. if you've just had a brainwave and want to get the code down before you forget the details, you can insert an overview as a note in a comment first, then set about implementing it in code.

Use Development Tools

Whether or not you're using an IDE, there will likely be development tools available for the language you're working with. If you're developing for the Web, there are a lot of browser tools that can help to find and fix errors. Tools such as Firebug can prove indispensable, particularly if you're working on large or complex applications.

If you're developing in an IDE, check out whatever debugging tools it has installed, or indeed whether there are any you can install as plugins. IDEs like Eclipse typically have a lot of optional extras you can install as well as the already extensive set of tools provided as standard.

Use Trace Statements

To fix code errors, you first have to locate them, and this can be the hardest part of the process. As well as developing in short bursts, testing each time you add some new aspect of functionality, you can give yourself some helpful clues as to what's going wrong using trace statements. A trace statement is generally something that you output to indicate what is happening at a specific point in your program.

Where your trace statements are output depends on the platform and IDE you're using, if appropriate. For IDEs there will typically be an output console, which you can write to directly, for example in this Java statement outputting the value of some variable at a particular point:

System.out.println("Data value: "+someVariable);

For Web development, you can output similar information from server side scripts to the browser, as in this PHP example:

echo "Data value: ".$someVariable."
";

In this case the value will simply appear within the webpage HTML, although this may not be ideal if you're working on a site that is already live - in these cases you can opt for something that will not be seen by site users, for example using server side tools such as writing to the PHP error log.

For client side scripting such as JavaScript, you can output information either to an alert dialog in the crudest example, which is again only suitable if you are working on a site that is not live:

alert("Data value: "+someVariable);

Alternatively, you can write your information to the log, which is also accessible using tools such as Firebug:

console.log("Data value: "+someVariable);

As well as using trace statements to check variable values as your code executes, you can use them to simply check whether the code is reaching a particular stage, for example to see if a function is definitely being called.

Isolate Error Prone Code Excerpts

If you're working on a large or complex project, it may help if you can separate any sections of code that are causing particular difficulties. This can help to locate the problem areas and can also make the testing process a little less cumbersome.

An alternative to copying chunks of source code into separate scripts, to be run independently, is to temporarily comment out those parts of code you do not need running to complete your debugging, letting you focus on the parts you're trying to troubleshoot.

Take Regular Breaks

It's yet another thing most of us know we should do but regularly fail to, but taking regular breaks can make the difference between success and failure when it comes to fixing code errors, as well as potentially stopping you going totally off your head! Sometimes I feel I've hit a complete dead end with a code problem, but after a short break I manage to find it relatively quickly and easily.

Links

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

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