Archivi categoria: JQuery

Read JSON data with AjaX request

Giorgio Bongiorni

Telecommunication Engineer with more than 5 years experience in web development and SEO campaigns. Favourite languages are HTML5, PHP5, MySql, CSS3 and jQuery.

Latest posts by Giorgio Bongiorni (see all)

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": [

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.

	var dir = 'data/';
	var extension = '.json';

		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');

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

				// description
				var description = $('#' + id + ' p');

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

Giorgio Bongiorni

Telecommunication Engineer with more than 5 years experience in web development and SEO campaigns. Favourite languages are HTML5, PHP5, MySql, CSS3 and jQuery.

Latest posts by Giorgio Bongiorni (see all)

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)


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

Giorgio Bongiorni

Telecommunication Engineer with more than 5 years experience in web development and SEO campaigns. Favourite languages are HTML5, PHP5, MySql, CSS3 and jQuery.

Latest posts by Giorgio Bongiorni (see all)

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


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

Giorgio Bongiorni

Telecommunication Engineer with more than 5 years experience in web development and SEO campaigns. Favourite languages are HTML5, PHP5, MySql, CSS3 and jQuery.

Latest posts by Giorgio Bongiorni (see all)

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)


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!