Saturday, May 25, 2013

Cross Browser Hash Change Event

hashchange adalah event JavaScript yang akan memicu suatu fungsi untuk bekerja setiap kali hash pada address bar berubah. Umumnya terjadi ketika pengguna menekan tombol Back dan/atau Forward pada peramban. Bermanfaat untuk memastikan agar AJAX bisa tetap bekerja ketika pemicu fungsi yang digunakan adalah berupa penekanan tombol Back dan Forward:

// http://stackoverflow.com/questions/9339865/get-the-hashchange-event-to-work-in-all-browsers-including-ie7
(function(w) {
    if ('onhashchange' in w) {
        if (w.addEventListener) {
            w.addHashChange = function(func, before) {
                w.addEventListener('hashchange', func, before);
            };
            w.removeHashChange = function(func) {
                w.removeEventListener('hashchange', func);
            };
            return;
        } else if (w.attachEvent) {
            w.addHashChange = function(func) {
                w.attachEvent('onhashchange', func);
            };
            w.removeHashChange = function(func) {
                w.detachEvent('onhashchange', func);
            };
            return;
        }
    }
    var hashChangeFuncs = [], oldHref = location.href;
    w.addHashChange = function(func, before) {
        if (typeof func === 'function') hashChangeFuncs[before ? 'unshift' : 'push'](func);
    };
    w.removeHashChange = function(func) {
        for (var i = hashChangeFuncs.length-1; i >= 0; i--) {
            if (hashChangeFuncs[i] === func) hashChangeFuncs.splice(i, 1);
        }
    };
    setInterval(function() {
        var newHref = location.href;
        if (oldHref !== newHref) {
            oldHref = newHref;
            for (var i = 0; i < hashChangeFuncs.length; i++) {
                hashChangeFuncs[i].call(w, {
                    'type': 'hashchange',
                    'newURL': newHref,
                    'oldURL': oldHref
                });
            }
        }
    }, 100);
})(window);

Dasar Penggunaan

Fungsi ini akan menampilkan kotak peringatan setiap kali hash berubah. Fungsi ini tidak memerlukan pemicu seperti window.onload, elem.onclick, atau event apapun! Karena pemicu kemunculan kotak pesan berasal dari perubahan hash pada peramban. Untuk mengubah hash pada peramban bisa dilakukan dengan cara mengeklik tautan lokal yang mengandung hash atau menekan tombol Back dan/atau Forward:

addHashChange(function() {
    alert('OK!');
});

Lihat Demo

Sampel Penerapan AJAX

$('.ajax-link').on("click", function() {
    window.location.hash = this.hash;
    return false;
});

// If user opens a URL that already contains a hash...
if (window.location.hash) {
    var theHash = window.location.hash; // Save the hash
    window.location.hash = ''; // Remove the hash, so if the AJAX link is clicked, the `hashchange` event will be triggered.
    $('.ajax-link').filter(function() {
        return this.hash == theHash;
    }).trigger("click"); // Trigger a click event to the AJAX link if it `hash` match with `window.location.hash`
}

// From hash change or history (Back/Forward button)
// Does not require any event. Just place the function like this...
// Because the trigger came from the hash changes in the address bar.
addHashChange(function(e) {
    var url = (e.newURL||location.href).split('#');
    $('#container').load(url[0] + ' #' + url[1]);
});

Labels: ,

7 Comments:

At Saturday, May 25, 2013 at 8:43:00 PM GMT+7, Blogger Unknown said...

gak mudang mas taufik,,ni postingan buat yg senior hahahay

 
At Sunday, May 26, 2013 at 7:17:00 AM GMT+7, Blogger Unknown said...

saya ga paham ni.. :p
untuk penerapan di blog apa yang harus diganti,? .ajax-link dan #container itu mengarah kemana mas???

 
At Sunday, May 26, 2013 at 7:17:00 PM GMT+7, Blogger Unknown said...

Penempatan scriptnya di mana mas

 
At Sunday, May 26, 2013 at 8:59:00 PM GMT+7, Blogger Taufik Nurrohman said...

Ini cuma contoh. Untuk penerapan fungsi yang sesungguhnya bisa kamu lihat pada widget Galleria yang baru-baru ini Saya perbaharui ⇒ DEMO

 
At Tuesday, May 28, 2013 at 3:38:00 PM GMT+7, Blogger Unknown said...

bener" ga paham saya,, belum nyampe ilmu saya.. :p
kalau hash yang seperti ini ya contoh #.UaRsr6xv_xU

 
At Wednesday, May 29, 2013 at 4:07:00 PM GMT+7, Blogger budkalon said...

sebenarnya fungsi dari script ini untuk apa? dan kelebihannya? :p

 
At Saturday, December 7, 2013 at 9:04:00 PM GMT+7, Anonymous Anonymous said...

sama ini juga blum kesampaian sama otak saya

 

Post a Comment

<< Home