Home > Monthly Archives: January 2012
Page 1

Using HTML5 to Determine User Location

Geolocation is one of the most exciting features offered by HTML5.

Using some relatively simple JavaScript code, you can create Web applications that determine various aspects of the user location, including longitude, latitude and altitude plus more. Some Web applications can even provide navigation functionality by monitoring the user position over time, integrating with map systems such as Google Maps API.

As with all HTML5 functions, you cannot yet rely on browser support. Where browser support exists, it varies in depth and consistency. Essentially, you need to provide alternative functionality for users whose browsers do not fully support HTML5.

In this tutorial we’ll run through the basics of establishing user location. In practice, the browser may be getting its data from more than one possible source. For example it could be GPS data on a mobile device or simply IP address based data on any device connected to the Internet. However, your code does not need to concern itself with these details, you can simply retrieve and use the location data for the purposes of your own projects.

HTML5 Web Page

Use the following code to create an outline for your HTML5 page:

<!DOCTYPE html> <html> <head> <script> /*Location functions here*/ </script> </head> <body> </body> </html>

We will place the JavaScript Geolocation functions in the page head script section and some basic HTML elements for testing and demonstrating the functionality in the body section.

HTML Demonstration Elements

Add the following markup to your HTML body section:

<input type="button" value="get location" onclick="getUserLocation()"/> <div id="locationData"> Location data here </div>

You can call your Geolocation functions at any time, such as when the page loads, or in conjunction with jQuery document ready functions. To demonstrate, we’ll use the button to call the function and will write the location data into the div element, which has some simple placeholder text in it initially.

Get Position Function

The main method we will be using to determine user location is the getPosition method. Add the following function in the script section in your page head:

function getUserLocation() { //check if the geolocation object is supported, if so get position if (navigator.geolocation) navigator.geolocation.getCurrentPosition(displayLocation, displayError); else document.getElementById("locationData").innerHTML = "Sorry - your browser doesn't support geolocation!"; }

This function is called when the user clicks the button. The code first checks that the navigator Geolocation object is present, which means the browser supports it. If the Geolocation object is supported, the code uses it to call the getCurrentPosition method.

The getCurrentPosition method takes two parameters indicating callback functions. The first is a function to call when the Geolocation data is received, while the second is a function to call if an error is returned instead.

If the Geolocation object is not supported, the function simply writes an error message to the page div element.

When a site attempts to retrieve the user location data for the first time, the user’s browser will prompt them to determine whether or not they consent to share their data. The function will only proceed if they do consent.

Display Location Function

Next we need to implement the function we included as first parameter to the getCurrentPosition method call. This function will be passed the user location data when the browser receives it. Add the following after your getUserLocation function:

function displayLocation(position) { //build text string including co-ordinate data passed in parameter var displayText = "User latitude is " + position.coords.latitude...
more →
Oguzhan Cansever says: Thanks for your explanation how to get a user position. I think longitude and latitude are coordinates to find out a...

Developing a Responsive Website: The Homepage Portfolio Slider

We are going to continue on with our designing a responsive website tutorial where we have already learned about the background images, the site’s navigation and the content.

This week we’re going to work on adding a little more content to our homepage.

At this point you should have a site that looks similar to this.

You should have a full-screen background image that changes in size to match the viewers screen resolution, a main navigation bar, and a little blurb that will grab the attention of the viewer and encourage them to keep exploring the site. One of the best ways to encourage a viewer to continue exploring is by putting some of your best work on the home page for them to see. Once you’ve captured their interest with those they’ll continue to click through to other pages.

We’re going to use a jQuery slider to display our mini-portfolio on our homepage, just below the main screen.  Because this is quite a big step, we’re going to break it down between two tutorials.  First we’ll set up the HTML, and structure the content for our main screen, then we’ll plug in the jQuery and make our slider responsive.  Go ahead and check out the image below to see what your finished product will look like.

Let’s begin in our index.php file. After we’ve closed off our “mainBG” div we are going to want to open up another div tag for our second screen that will contain our portfolio slider, I simply named my “mainBG2”. Next we’re going to want to put in another instance of our “container” id so that we can keep our content centered on the page. Then I included the “Articles” box section header that’s in the top left. Starting just under the closing tag for the “mainBG” div, my code looks as follows.

<div id="mainBG2" class="homeContent" data-type="background"> <div id="container"> <div class="articlesHeader">Articles</div> </div><!--end div "container"--> </div><!--end div "mainBG2"-->

Once the basic structure of our secondary portfolio screen is set up, we can add in the HTML structure we’ll need for our portfolio slider. You’re free to populate this with what ever content is relevant to you, I’m just going to use a couple previous articles I’ve written. As you can see we’re able to include images and text. You’ll want to place this after our “articlesHeader” class, but before the close of our “container” div.

<div class="slider-wrap"> <div id="slider1" class="csw"> <div class="panelContainer"> <div class="panel" title="Panel 1"> <div class="wrapper"> <h3>A Look At Responsive Web Design</h3> <img src="images/responsive.jpg" /> <div class="hideSmall"><img src="images/responsivesmall.jpg" /></div> <p>By Scott Stanton</p> <p>Responsive web design is widely thought of as a design trend, but it's much more than that.</p> <p>It is an approach...
more →
Howtomake says: began to alter the design of your blog under responsive and also ran into a problem that needed a slide, searched and found only...

PHP Arrays: Array Functions and Multidimensional Arrays

In Part I, we looked at simple arrays, as well as how to loop through and sort array elements.  In this article, we will look at other array functions as well as multidimensional arrays.

The difference between one-dimensional and multidimensional arrays is a simple one: a multidimensional array is a simple array that has simple arrays as elements, rather than strings or scalar variables.

Building a Multidimensional Array

Here is how our $arrBooks example from last week’s article can be expanded into a multidimensional array:

<?php $arrBooks = array( ‘Comic’ => array( ‘Title’=>‘Superman’, ‘Author’=>’Jerry Siegel and Joe Shuster’, ‘Publication Date’ => ‘1938’), ‘Science Fiction’ => array( ‘Title’=>‘Dune’, ‘Author’=>’Frank Herbert’, ‘Publication Date’=>’1965’), ‘Fantasy’ => array( ‘Title’=>‘The Hobbit’, ‘Author’=>’J.R.R. Tolkien’, ‘Publication Date’=>’1937’), ‘Horror’ => array( ‘Title’=>‘Carrie’, ‘Author’=>’Stephen King’, ‘Publication Date’=>’1974’) ); ?>

Extracting Elements from a Multidimensional Array

To extract a single element from the multidimensional array, you must refer to the keys in both the outer and inner arrays. For instance, the PHP code below:

<? echo $arrBooks[‘Science Fiction][‘Title’]; echo "<br>"; echo $arrBooks[‘Horror’][‘Author’]; ?>

would display:

Dune Stephen King

Looping Through a Multidimensional Array

The easiest way to loop through a multidimensional array is to nest two foreach loops; the outer loop goes through each outer array element, and the inner loop goes through each inner array element within the selected outer element.

<? foreach ($arrBooks...
more →
Ram says: ttttt yyyyyyy

Responsive Widgets

Responsive design is a hot topic of web development these days, and with a simple (and now well supported) way of handling the ‘one site for all clients’ model (and I mean clients as in browsers/platforms/devices, not the people that give you money in return for a web site) it should well be.

Redirecting mobile users to /m/ or some other cut-down area of your site is becoming a technique of the past.

Using collections of utilities, such as the excellent 320&up, makes building responsively much easier, and handles most of the gotchas for you automatically, so instead of fretting on the technical side of implementing a responsive build, the challenge now rests on the responsive design and User Experience of the site, I.E. how should these content regions stack up in a mobile view? What is the best way to show this sidebar in a single-column layout? Building it is easy; thinking about how the design should adapt itself is the tricky part.

Rich JavaScript Widgets

So when thinking about how a site should rearrange itself when viewed on a responsive site, part of that thought process should include thinking about what happens to rich JavaScript widgets when viewed on a mobile device. For example, your responsive site may have an attractive tabset that works well when viewed on a desktop or tablet computer, but what about when viewed on a smartphone? Tabbed content generally (although not always) sits with the tabs along the top of the group and while this may translate well for smaller tabsets with just a few tabs, it doesn’t work too well where there are a lot of tabs, they simply take up too much horizontal space, and two rows of tabs just doesn’t work that well visually.

One thing we can’t do is simply hide the content; we used to be able to reasonably decide what people wanted to do with their smartphones, a restaurant website owner for example, could decide that mobile users were likely to just want the street address and contact details, not view the entire set of menus while out and about and could therefore hide a lot of the content that simply wasn’t likely to be used. This is most definitely no longer the case; we simply cannot make assumptions about the intentions of mobile users.

Therefore we must make sure all content is available and presented to mobile users in an easy to use way. Coming back to the tabs example then, we may decide that the tabs widget is not going to work and so need another solution. Simply displaying all of the content may not be an option either – if the tabset contains too many tabs to show on a horizontally-restricted mobile device, it may contain too much content to just dump on the page. There may be an important area of the screen that is usually visible below the tabs, but which would be pushed too far down the page when all of the tab content is visible. One solution that meets both requirements of using an alternative widget to display tabbed content, while not making the page miles long is to implement something that works well in a page that is taller than it is wide, something like an accordion, where the content is still available on the page and can be viewed by users that wish to see it.

Implementation

Based on the 320&up model, we want to transform the underlying content differently based on the width of different devices. We would typically specify a set of different breakpoints in our CSS and each time a breakpoint is exceeded, we load a further style sheet, which builds on style sheets previously loaded. To keep this example simple we’ll work on just two breakpoints; at least 320 pixels wide gives us a breakpoint for smartphones, while 720 pixels and above gives us a breakpoint for tablets and desktop computers. We won’t be looking at the styling in this example; we’re only interested in the JavaScript required to make our widget responsive. We’ll use jQuery UI (version 1.8.16) to create the widgets.

We’ll assume that the content we wish to work with is in the following format:

<div id="content"> <h2>Content Heading 1</h2> <div> <p>...</p> <p>...</p> <p>...</p> </div> </div>

There will be a heading followed by a div containing one or more paragraphs of text. These elements will be repeated one or more times, with the whole lot wrapped in an outer container.

All we need to do to create the appropriate widget based on the width of the viewing device is check the width of the window when the page loads and then make any adjustments to underlying HTML that each widget requires:

(function ($) { var container = $("#content"), width = $(window).width(); if (width >= 320 && width ", { href: "#" }); container.accordion({ active: false, collapsible: true, autoHeight: false }); } else if (width >= 720) { var list = $("</>"); container.find("h2").each(function (i) { var header = $(this), item = $("<li/>"); $("<a/>", { text: header.text(), href: "#tab" + i }).appendTo(item); item.appendTo(list); header.next().attr("id", "tab" + i) header.remove(); }); container.prepend(list).tabs(); } } (jQuery));

The mark-up required for each widget differs slightly and because we don’t know beforehand which widget will be rendered, we don’t want to pollute the page with elements that aren’t going to be used, or duplicate structures that differ only slightly – instead we create the extra elements as required. The accordion requires links inside the headings, while the tabs require links within an unordered-list that point to different div elements. Once the required new elements have been created we then call the appropriate method to create and display the widget.

Summary

When planning a responsive build we need to think not just about how the layout of the page should change in order to provide the best experience to the visitor, we also need to think about how interactive elements, such as JavaScript widgets, should look and behave.

...
more →
Marcelo says: That's not "responsive web design", that's "adaptable web design"... Responsive web desgin is not limited by "if width: x", it...

Developing a Responsive Website Part 2: Navigation and Content

Now that we’ve got our background images squared away and set to break themselves down nicely across various devices and screen resolutions we can look in to populating our home page with some content.

Let’s begin with our header. I always like using a separate file for all the things that will stay uniform throughout my site, header, logo, navigation, etc. That way if I need to make a minor edit down the road I just have to edit the header file, which is then pulled in to every page with a simple PHP include script.

To start, let’s create a new php file, I named my “header.php” in order to keep things simple. In my header.php file I have placed my header, which simply contains the logo (I used the Developer Drive logo for this tutorial). After my logo is my navigation, a simple list will suffice for this tutorial. I chose a few basic links that someone may want to include in their site, but feel free to include what ever links are relative to you. My header.php code looks as follows.

<div id="logo"><img src="images/logo.png" alt="Developer Drive" /></div> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">Portfolio</a></li> <li><a href="#">Services</a></li> <li><a href="#">About</a></li> <li><a href="#">Blog</a></li> <li class="last"><a href="#">Contact</a></li> </ul> </nav>

Go ahead and save that file, and feel free to close it since we’re done working in there.

Open your index.php file and let’s begin adding the content. We’ll start by adding a container div after our background image, then place the php include for our header, and finish it off by putting in our little blurb bubble. When all is said and done you should have something similar to this.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=1"> <title>Responsive Web Design</title> <link href="main.css" rel="stylesheet"...
more →
Peter says: fyi, if you're working locally, you won't be able to run any php files unless you have Apache running locally (like WAMP of MAMP.)

SEO for Web Developers Part 2

Some experts say search only drives 30 percent of a website’s traffic.

While that may seem insignificant, that 30 percent often makes up visitors who are looking for the products, services or information specific to your company so losing them could have a significant impact on how well an organization performs.

In part one of this series we looked at some things that web developers need to consider when it comes to search engine optimization, but now it’s time to step up to the plate. Let’s roll up our sleeves and really see what it is we can do to help our site compete in the search engine results page.

While we know that our objective is to rank high, we need to understand what it is that prevents a site from achieving that goal, from a developer’s standpoint.

As a developer, the number one thing we need to consider is can a search engine spider crawl my web site? Because quite honestly, if the pages of the site can’t be crawled nothing else really matters.

So what prevents a spider program from finding the right information on our websites?

Frames

In the past spiders were not able to read frames, but now almost all the major spiders can read them. If you do need to solve a problem for a particular spider, the quick solution is to utilize your “No Frames” tag content to optimize your page. It is also advisable to make sure that you use a base href tag in your header to help search engines understand better.

Password Protected Pages

These are pages you probably don’t want indexed anyway. Just be aware that like a human, the spider cannot enter any area that is protected by a password.

If you have content behind these pages that you want people to find via the search engines, consider using a teaser with some of the content that can be indexed and protect the rest.

Flash Sites

Flash looks cool, it adds interactivity to your site but most of the time it give the search engine spiders some trouble. Recently, Google is reading, indexing and ranking Flash pages based on the text content used in the Flash code. However this is not optimal optimization.

One solution would be to use an entrance page that is keyword rich, create a two frame frameset where one frame is only one pixel in height and use the No Frames area, or to alternate the use of Flash and static HTML.

Image Maps

These are funny because they can be read by some spiders but not by others. If you plan to use an image map, make sure there are other links on the page (perhaps on the bottom) that link to your other pages or better still to a site map that links to all your pages with good anchor text.

PDF Files

These are a popular way to share content but they present a major stumbling block to most spiders. Some engines (specifically Google) are now, however, beginning to index this kind of pages.

Dynamic Pages

Some search engine spiders have problems with dynamic pages which contain variables in the URL. This is most often seen with dynamic pages that use CGI, ASP, or Cold Fusion. Google for instance will not index pages shower URL contains id= followed by more than ten characters or if there are too many variables in the URL. If you are having problems with dynamically generated pages you should consider using the rewrite module of the Apache server to rewrite those dynamic urls into static looking URL or using a similar add on if hosted on a Windows server. There are also PHP scripts which can be implemented which will change the address into a readable page.

...
more →
Ryan Keefer says: This is a pretty dated sounding article. Who uses frames and image maps in modern day sites. A lot of SEO is common sense, and...

XML Schema (XSD): Using Compositors

In XML, you can use XSDs to define markup structures in varying levels of detail. Compositors are among the many XSD structures you can choose from when specifying your XML content models.

The XML Schema standard supports three different compositor types, each of which indicates restrictions on the range and ordering of elements. In general terms, a compositor dictates (or describes) the composition of child elements within a parent element in an XML data source.

Compositors often appear within XSD entries for complex type elements, providing specifications for elements with multiple possible children. They work in conjunction with “minOccurs” and “maxOccurs” attributes to define whether or not an element must appear, how many times it may appear and how it should appear in conjunction with its fellow elements in the same content model.

Sequence

The sequence compositor enforces a specific order on the child elements that appear within a parent element. The following XSD sample includes a sequence compositor:

<xs:element name="account"> <xs:complexType> <xs:sequence> <xs:element name="client_id" type="xs:integer"/> <xs:element name="client_name" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element>

This XSD excerpt specifies a parent element named “account” with two child elements named “client_id” and “client_name” which must appear in the same order. The following XML satisfies this XSD code:

<account> <client_id>123</client_id> <client_name>Lovely Products</client_name> </account>

If the “account” element contained the two child elements, but not in this order, the XML would not satisfy the XSD, or, depending on your perspective, the XSD would not accurately describe the XML.

Choice

The choice compositor requires XML constructs to use only one from a possible set of child elements. The following XSD excerpt demonstrates:

<xs:element name="account"> <xs:complexType> <xs:choice> <xs:element name="corporate_id" type="xs:integer"/> <xs:element name="personal_id" type="xs:integer"/> </xs:choice> </xs:complexType> </xs:element>

This example could be for a service organisation with distinct corporate and personal accounts. Each account must be associated with either a corporate or personal ID number, but not both. The following XML satisfies the requirement:

<account> <corporate_id>456</corporate_id> </account>

Where the “minOccurs” and “maxOccurs” attributes allow XSDs to specify the number of times a single element can appear, the choice compositor defines which elements can appear with reference to other possible children within the same parent node.

All

The all compositor indicates that each member of a set of elements must appear, but only once, and in any order. The following XSD code includes an all compositor:

<xs:element name="account">...
more →
Guntas says: Very lucid explanation of the XSD Compositors!