One HTML page can have so many elements, If you want to have dedicated link for elements in the page then you better to go for Hash Change.

Hash Change with ID values 

The basic way to give dedicated links is "Using IDs".    
  1. dedicated.html#post1  shows Post1 div 
  2. dedicated.html#post2  shows Post2 div
  3. dedicated.html#post3  shows Post3 div
  4. dedicated.html#navigation  shows Navigation div

Loading Ajax JSON Data  with Hash Change Event

This is advanced concept in dedicated links. Logic of the concept is in below steps
  1. Detect Hash Change using javascript 
  2. Load JSON data based on the Hash value in the URL

Detect Hash Change using javascript 

window.onhashchange triggers the function on hash change in URL 
function locationHashChanged() {
    var hash = location.hash;
    var id = hash.replace(/^#/, '');
    // write your logic here
}
window.onhashchange = locationHashChanged;

Markup 

The below markup is for displaying student information
Name : <span id="name"></span> <br/>
Subject : <span id="subject"></span> <br/>
School : <span id="school"></span> <br/>

jQuery code to load JSON data in Ajax based on Hash Change 

$(function() {

    // This function will be triggered by hash change event
    function locationHashChanged() {
        var hash = location.hash;
                // remove # and get id
        var id = hash.replace(/^#/, '');
                // load student data based on ID
        if (id == 'srinivas') {
            loadStudentData("/json/student1.json");
        } else if (id == 'mark') {
            loadStudentData("/json/student2.json");
        } else if (id == 'gates') {
            loadStudentData("/json/student3.json");
        } else if (id == 'satya') {
            loadStudentData("/json/student4.json");
        }
    }

    // hash change event
    window.onhashchange = locationHashChanged;

    // function to load student data
    function loadStudentData(jsonurl) {
        $.ajax({
            url : jsonurl
        }).done(function(data) {
            data = jQuery.parseJSON(data);
            $("#name").text(data.name);
            $("#subject").text(data.subject);
            $("#school").text(data.school);
        });
    }

    // To check hash value on page loading
    locationHashChanged();

});

0 comments:

Blogroll

Follow this blog by Email

Popular Posts