Read JSON data with AjaX request

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It’s text-based and simpler than other languages, this is the reason why it has become very popular in the last period. In this article, we’ll see how to get data from a JSON file (via AjaX requests) and dinamically fill sections of a HTML file with information read from it. Our focus will be on the technique used to retrieve and display data, so layout will be very simple (say, ugly!) but it can be easily improved with some additional CSS.

Define HTML structure

The first step is to define the HTML file. This file is basically composed of an empty section having a unique id. This id will be used to retrieve data from JSON file and poulate section with a title, an image gallery and a paragraph containing some information. Here you can find the described HTML code.

<section id="animals"></section>

Setup JSON files

The second step is to create a JSON file containing data. As stated into JSON official website, a JSON file can contain either a collection of name/value pairs or an ordered list of values (array). In our case, we will define both of them. The following snippet is composed of a “title” and a “description” as name/value element, and a “images” element as an array.

{
  "item": {
    "title": "ANIMALS",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing 
    elit. Suspendisse vitae turpis in turpis vehicula pharetra.
    Praesent euismod elit vel dui convallis fringilla. Cras volutpat,
    eros id pellentesque posuere, odio libero dapibus dolor, at
    interdum augue risus a mi. Curabitur ultricies cursus risus in
    tincidunt. Praesent fringilla interdum pellentesque. Maecenas nec
    vulputate arcu, at pharetra erat. Integer fringilla magna at
    ornare ornare. Aliquam quis tellus sed metus porttitor convallis
    et sit amet quam.",
    "images": [
      "images/animals/puppy.jpg",
      "images/animals/beagle.jpg",
      "images/animals/bernese.jpg",
      "images/animals/labrador.jpg"
    ]
  }
}

This file will be named “animals.json”, to allow jQuery code described in the next section to fill in HTML section with the proper data.

Add jQuery code

The final step is to create a jQuery script to read data from JSON file and populate HTML section. The script has a main cicle over all sections of HTML file (this means that if you want to add another section, you can simply add it to your HTML code, choose a unique id and create a new JSON file with the same name. That’s it!). For each section, script gets the id attribute to retrieve JSON filename. Then, it makes AjaX request to open JSON file and read data. Information are formatted as key/value pairs and can simply be accessed using the “title”, “description” and “images” identifiers. Images are used to build a Nivo Slider gallery, which is started at the end of the script.

$(document).ready(function()
{
	var dir = 'data/';
	var extension = '.json';

	$('section').each(function(index) 
	{
		var item = $(this);
		var id = $(this).attr('id');
		var filename = dir + id + extension;

		// create basic structure
		item.html('<h1></h1><div class="theme-default"><div class="nivoSlider"></div></div><p></p>');

		// read data from json file (function is invoked on file read completion)
		$.getJSON(filename, function(data) 
		{
			// retrieve values from file data
			$.each(data, function(key, val) 
			{
				// title
				var title = $('#' + id + ' h1');
				title.html(val.title);

				// images
				var slider = $('#' + id + ' .nivoSlider');
				$.each(val.images, function(imageID, image) 
				{
					slider.append('<img src="' + image +'"/>');
				});
				slider.nivoSlider();

				// description
				var description = $('#' + id + ' p');
				description.html(val.description);
			});
		});
	});
});

Conclusions and downloads

We are done! Here you can find the complete code of this example. Feel free to download and use it as you want. If you have any question or doubt, ask it into comments section. Thanks!

Download the full example code!

Responsive navigation menu

In the last year it has become very important to adapt our website layout to user screen size, in order to improve navigation experience and offer a usable way to present information. One of the first elements which are seen from users is the navigation menu: for this reason it’s important to design it to be intuitive and user-friendly. In this article we will introduce two techniques to create a responsive navigation menu: smart button and select menu.

Smart button menu

A first way to build a responsive navigation menu is to create a smart button. The first step is to create a complete navigation header, composed of a logo floated on the left, and a navigation bar and a smart button floated on the right (smart button is built via jQuery separately to keep HTML code clean). We can also add a little bit of CSS to improve presentation or influence link hover state (you can see it in the snippet below).

Now, thanks to CSS media queries, we can say that if user screen width is above 550px (you can change this breakpoint value depending on your needs), we show the navigation bar and hide smart button. When screen width decreases under 550px, navigation bar is displayed as a 100%-width block, placed under logo and hidden. The smart button is instead shown floated as a little block on the right.

A little jQuery script is then added to bind an event listener to button click: the action is obviously to toggle navigation bar visibility. Below you can find the link to the described code. To see it in action, simply resize result window until the CSS breakpoint triggers. You can customize all parameters you want, starting from media query parameters and logo url. If you want to create a new HTML document, please remember to include a call to jQuery library and include the script into a “document ready” callback.

Responsive navigation menu (smart button)

Drop-down menu

The second way to build a responsive navigation menu is to create a select element. This solution is very similar to the smart button code: the behaviour above 550px breakpoint is exactly the same. The difference comes when we are below 550px, where navigation bar is replaced with a drop-down select element containing navigation items.

As in the smart button solution, the drop-down menu is built separately via jQuery script, to keep HTML code clean. Current page url (where the script is invoked from) is retrieved inside the script and the corresponding element is selected into drop-down list. A change event lister is bound to select item: when an element is selected, the browser is redirected to relative url. Clearly, this is a base example and you can add some CSS to improve its presentation if you want. The described code is linked below.

Responsive navigation menu (drop-down menu)

Conclusions

In this article we presented 2 techniques to build a responsive navigation menu. Thanks to CSS media queries we can retrieve user screen resolution and adapt menu appearance to offer the best experience. Of course, there are a lot of other variations and many improvements you may perform (i.e. manage a second-level menu), but if you need a simple navigation menu these solutions may be a start point.

CSS arrows and triangles

Triangles and arrows are one of the most used glyphs in modern web designs. In this article we are going to discuss 3 techniques to draw both of them, defining some customizable properties like thickness, orientation and color.

CSS Triangles

The most common technique for drawing triangles is to create an empty div (with both width and height equal to zero) and use its borders to create the arrow tip. The solution is based on the fact that borders in HTML elements join with 45° junctions. If we draw one of the borders and set its adjacent borders to be transparent, we can easily obtain the desired triangle. To create right-triangles, for example, it’s sufficient to draw the left border and set both top and bottom borders to be transparent, as shown in the following snippet.

CSS triangles (borders)

This solution is compatible with all modern browsers (including ie8) and is very flexible, since colors and thickness can be easily changed by modifying CSS entries.

CSS arrows (rotation)

Drawing arrows may be a little more tricky, but we can still use div borders for our goal. If we draw two adjacent borders choosing the same colour and rotate the figure properly, we can obtain an arrow pointing everywhere we want. The complexity in this case is to create a cross-browser solution, since ie8 needs an image transform matrix to perform the rotation.

CSS arrows (rotation)

This solution offers the advantage to be compatible in all browsers and the ability to customize arrow direction (for further information see Matrix Filter documentation, rotation example section with customizable costheta and sintheta values). Unfortunately, since the arrow tip is obtained with a div angle, it is limited to be a 90° angle.

Canvas arrows

An interesting technique to draw arrows is to use HTML canvas. Thanks to canvas, we can draw lines of with arbitrary thickness, colors and angles. This solution is very flexible since we can draw any kind of shape. Unfortunately, canvas are not supported from ie8 and we need to add an excanvas library call to our code, which slows down page load. Secondly, canvas don’t naturally fit to their content, so we must manually set up their dimensions. The following example shows how to use canvas to draw arrows.

Canvas arrows

Conclusions

In this post we have seen 3 techniques to draw triangles and arrows in HTML documents. Each of them has strenghts and drawbacks, so it’s up to you to choose what is the best for your needs. As always, if you know better solutions for this argument we can freely discuss about them in comments. Thanks for your attention and see you soon!

Center div horizontally and vertically

Sometimes we have the necessity to center a content inside a container. It may be a text on a background picture or an image inside a box. This can be easily done via CSS if we know the height of the content, but if these value are unknown it may be a little harder.

Centering image: absolute positioning

The simplest solution is to impose the width and the height of the content, and display it with an absolute positioning at 50% into container. In this case we must define a negative margin equal to half of the content dimensions to achieve perfect centering. This solution is very effective, but it forces us to display images with a fixed size (which is not suitable in responsive web designs).

Center div horizontally and vertically (absolute)

Centering image and text: jQuery script

If we would like to create “responsive” images (say, pictures which dimensions adjust to visitor screen size) and center them into the container, absolute positioning is not suitable. In this case, we may use a jQuery script to retrieve the size of both content and container and compute the proper margin to obtain centering. This technique has the advantage to be compatible with all major browsers, works with both images and text content, but it requires an extra-call to server (at least for jQuery library) which slows down page loading.

Center div horizontally and vertically (jquery)

Centering text: table display

Handling with text is more difficult: if we resize the container, text scrolls down and increases the height of the content, making it impossible to center with a simple positioning. If we don’t want to use jQuery, a solution may be display container as a table and content as a table cell. The solution has the advantage to increase container height as the content scrolls down, but has some important drawbacks. First, the content extends to 100% width and 100% height of the container. Second, it’s impossible to define a width for content (width property in content style results ineffective): this can be fixed by defining some padding, but it sounds like a trick and not a solution.

Center div horizontally and vertically (table)

Centering text: ghost element

A nice solution for text centering without using jQuery scripts comes from an interersting post of Chris Coyer. The trick is to create a ghost element before the content with 100% height. Text is displayed as an inline-block element, and this allows us to give it desired size (also percentage values). As said, jQuery is not used and this reduces page loading time, but if user screen is too narrow, text scrolls down and exceeds container height.

Center div horizontally and vertically (ghost)

Conclusions

In this post, we have compared 4 techniques to center text and images inside divs both horizontally and vertically. We have first analyzed a case of fixed-size content and then considered the case of unknown content dimensions. An important section has been dedicated to text contents, which may have unpredictable height depending on visitor screen size. If you would like to ask something or propose other solutions, please let me know in comments. Thanks for your attention, see you soon!

Equal height columns

A common web design situation is the necessity to create columns with equal height, regardless of their content. A classic example is newspaper layout, where we have flanked columns containing articles of different lenght: we may have the necessity to color columns with a background tint, and keep them to the same height for a better-looking layout.

Table display

The first trick to solve this issue is to display columns as table cells. This technique works fine in all major browsers (including ie8) and offers the advantage to define a clear CSS with a simple class for all columns. There’s no need to specify the position of a single column or the value of its margin, we must only define the width. The disadvantage is that this solution is not very semantic: we are going back to 2000, when layouts were made with tables.

Equal height columns (table display)

Absolute positioning

Another solution is to display columns with an absolute positioning. In this case, we must wrap them with a relative-position container and define a proper left margin for each column. The trick here is to wrap all columns but the last into a class, and write the last column content directly inside the container. To display the last column properly, we must define a padding-left property into container style: this leaves free space for other columns. This solution is quite flexible, since we can swap columns order simply changing margin property, but it requires extra javascript (i.e. selectivizr) to work in older browsers (ie8).

Equal height columns (absolute positioning)

Flexible boxes

The third trick makes use of the flexbox technique. In this case, we display columns as flexible boxes. This solution has the advantage to be clear and easily customizable. For example, columns width is determined by “flex” property: 1 means that all columns are equally spread, 2 in a column style means that this column has double width of other columns. Furthermore, column ordering can be achieved in a very straight way simply setting “order” property. Unfortunately, this solution has the disadvantage to be  incompatible with ie<10, but it surely will represent a cornerstone in layout design for the next years.

Equal height columns (flexbox)

Conclusions

In this post, I’ve compared 3 solutions to create equal heights columns. Some of them are extremely flexible and clear but have compatibility problems, expecially with older internet explorer versions. Have you found better solutions or do you use different techniques? Let me know in comments.

2-columns layout: Fixed and Fluid

A problem I’ve often faced with during my projects is the creation of a 2-columns fixed-fluid layout. The first column has a fixed width, while the second column covers the remaining space into actual window size. This may be an issue when, for example, you are building website headers with the fixed-width logo and the navigation menu filling the remaining space.

Table display

A first solution is to create a container for the 2 columns displayed as a table, and display the 2 columns as table cells. This solution offers a good flexibility, because if we want to display the fixed column on the right, we can simply swap the columns in html. It also has the advantage to keep both columns to the same height regardless the width of the container. Unfortunately, it forces us to specify the width of the fixed column (otherwise columns have both 50% width and spread equally into container) and it’s not very semantic.

2-columns layout (table left)
2-columns layout (table right)

Position absolute

Another solution may be the use of absolute positioning. We create a container with relative positioning and display columns with absolute positioning.  We must define the width of the fixed column and a margin for fluid column. This solution offers the ability to swap columns via CSS without affecting HTML (see both solutions below, which share the same HTML code and differ only by css). Unfortunately, the trick does not keep both columns to the same height.

2-columns layout (position absolute left)
2-columns layout (position absolute right)

CSS calc function

A further solution is the use of CSS calc function. Thanks to this feature, available in all modern browsers, we can calculate the fluid width as the difference between container and fixed width. This trick allows to swap columns simply exchanging their CSS width properties or HTML id properties. Unfortunately, there are no IE8 fallbacks and column heights are different. Please also note that in this snippets we must avoid white spaces between HTML column elements, otherwise a 4px margin is displayed and we must keep it in count in calc values.

2-columns layout (CSS calc left)
2-columns layout (CSS calc right)

Floating div

The last solution is to specify the floating property for the fixed column and a margin for the fluid column. As for the absolute positioning, it is possible to swap columns via CSS without affecting HTML (see solutions below, with fixed column positioned on the left and on the right of container, respectively). Unfortunately, it’s not possible to keep columns to the same height and it’s necessary to specify the overflow property for container in css.

2-columns layout (float left)
2-columns layout (float right)

Conclusions

In this article, four possible solutions were presented to create a fixed-fluid column layout. For each solution, pros and cons were considered and analyzed. I hope this tricks may help you. If you have any doubt or if you like to propose better solutions, feel free to do it: comments are here for you!