JSFiddle - React, Tailwind, and code Playground
by Paul Lan
HTML
<button title="click me to change url" id="selector_based">Selector based</button>
<button title="click me to change url" id="func_based">Function based</button>
<div id="main" title="if be_click button is clicked, this div will be changed">
</div>
<button id="be_click" class="ui-helper-hidden" ></button>
CSS
#main {
border: 1px solid #ff00ff; height: 200px; width:300px; padding:10px; margin:20px; overflow:auto;
}
JavaScript
// utilitites
// implement hashChange event to all browser
(function(window) {
// exit if the browser implements that event
if ( "onhashchange" in window.document.body ) { return; }
var location = window.location,
oldURL = location.href,
oldHash = location.hash;
// check the location hash on a 100ms interval
setInterval(function() {
var newURL = location.href,
newHash = location.hash;
// if the hash has changed and a handler has been bound...
if ( newHash != oldHash && typeof window.onhashchange === "function" ) {
// execute the handler
window.onhashchange({
type: "hashchange",
oldURL: oldURL,
newURL: newURL
});
oldURL = newURL;
oldHash = newHash;
}
}, 100);
})(window);
var Hash = function() {
var self = this;
// pattern definition to match url hash
var getRegType = function() {
var i, matched, toReturn = {},
def = {
selector: function() {
return RegExp('#hashEvent\\/selector\\/(.+?)\\/event\\/(.+?)$');
},
func: function() {
return RegExp('#hashEvent\\/func\\/(.+?)$');
}
};
for (i in def) {
matched = def[i]().exec(location.hash);
if (matched != null) {
toReturn = {
type: i,
hashPart: matched
};
return toReturn;
}
}
return false;
}
// function to execute if matched pattern found
var Trigger = function() {
this.selector = function(hashPart) {
var selector = decodeURIComponent(hashPart[1]),
myEvent = decodeURIComponent(hashPart[2]).toLowerCase();
$(selector).trigger(myEvent)
}
this.func = function(hashPart) {
$.globalEval('(' + decodeURIComponent(hashPart[1]) + ')()');
}
}
var trigger = new Trigger();
var Process = function() {
// match demo:
this.selector = function(hashPart) {
if ( hashPart != null) {
trigger.selector(hashPart);
...