Category Archives: javascript

javascript

How to get url hash state safely

Normally, we can get the hash string by location.hash. But currently i fond the value is not actually correct in FF. FF automatically decoding encoded hash string in the URL.

So safely method is avoid use location.hash, and it is better to use location.href.split('#')[1] instead of location.hash.

Indeed location.href.split('#!')[1] does not get decoded by FF automatically (at least today).

var currentUrl = '';
var getHashPath = function() { 
    return location.href.split('#!')[1];
};
$(window).on('hashchange', function(e) {
    var url = getHashPath();
    if (url !== currentUrl) {
        currentUrl = url;
        // do some business logic...
    }
});

Make websafe colors

For Web colors plugins.

Convert a normal hex color to a websafe color.

var round = Math.round;
var floor = Math.floor;

function get_hex(dec) { return dec.toString(16); }
function get_dec(hex) { return parseInt('0x' + hex, 16); }

function rgb_to_hex(r, g, b) {
    var c1 = get_hex(floor(r / 16));
    var c2 = get_hex(floor(r % 16));
    var c3 = get_hex(floor(g / 16));
    var c4 = get_hex(floor(g % 16));
    var c5 = get_hex(floor(b / 16));
    var c6 = get_hex(floor(b % 16));
    return c1 + c2 + c3 + c4 + c5 + c6;
}
function hex_to_rgb(hex) {
    var i = 0, arr = [], c1, c2;
    while (i < 6) {
        c1 = get_dec(hex.substring(i, ++i));
        c2 = get_dec(hex.substring(i, ++i));
        arr.push((c1 * 16) + c2 * 1);
    }
    return arr;
}

function web_safe(r, g, b) {
    var t;
    t = r % 51; if (t > 25) { t = r + 51 - t; } else { t = r - t; }
    var c1 = get_hex(round(t / 17));
    t = g % 51; if (t > 25) { t = g + 51 - t; } else { t = g - t; }
    var c2 = get_hex(round(t / 17));
    t = b % 51; if (t > 25) { t = b + 51 - t; } else { t = b - t; }
    var c3 = get_hex(round(t / 17));
    return c1 + c1 + c2 + c2 + c3 + c3;
}

function get_safe_color(c) {
    if (c.charAt(0) === '#') c = c.substring(1);
    var rgb = hex_to_rgb(c), r = rgb[0], g = rgb[1], b = rgb[2];
    return '#' + web_safe(r, g, b);
}

console.log(get_safe_color('#1255FF')); // #0066FF

216 Web Safe Colors table see also http://websafecolors.info/

Update offline application cache

You can automate this. To update users to the newest version of your site, set a listener to monitor the updateready event on page load:

// storage interface, for more details storage implemments see https://gist.github.com/allex/a9b431ebcc921f2b309d
var storage = {
  get: function(k) {},
  set: function(k, v) {},
  remove: function(k) {}
};

window.onload = function(e) {
  var appCache = window.applicationCache;
  if (!appCache) { return; }

  // update offline.manifest caches if possible.
  appCache.addEventListener('updateready', function(e) {
    if (appCache.status === appCache.UPDATEREADY) {
      // Browser downloaded a new app cache.
      // Swap it in and reload the page to get the new hotness.
      try { appCache.swapCache(); } catch (e) {}
      if ( confirm('A new version of this site is available. Load it?') ) {
        storage.set('reload_flag', 1);
        reload();
      }
    }
    else {
      // Manifest didn't changed. Nothing new to server.
    }
  }, false);

  // The manifest returns 404 or 410, the download failed,
  // or the manifest changed while the download was in progress.
  appCache.addEventListener('error', function(e) {
    var reload_flag = parseInt(storage.get('reload_flag'), 10) || 0;
    if (navigator.onLine && reload_flag > 0) {
      storage.set('reload_flag', 0);
      reload();
    }
  }, false);

  function reload() {
    window.location.reload();
  }
};

Reference Links:

Get the cursor position in input or textarea

How to get cursor position in input/textarea?

// get current cursor position
function getCursorPos(el) {
    var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange;

    start = el.selectionStart;
    if (typeof start === 'number') {
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() === el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, '\n');

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints('StartToEnd', endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart('character', - len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints('EndToEnd', endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd('character', - len);
                    end += normalizedValue.slice(0, end).split('\n').length - 1;
                }
            }
        }
    }

    return {start: start, end: end};
}

for more complex example, please see code in: http://rangy.googlecode.com/svn/trunk/demos/position.html

Javascript RegExp – lastIndex Property

lastIndex is a read/write property of RegExp objects. For regular expressions with the g attribute set, it contains an integer that specifies the character position immediately following the last match found by the RegExp.exec() and RegExp.test() methods. These methods use this property as the starting point for the next search they conduct.

This property allows you to call those methods repeatedly, to loop through all matches in a string and works only if the g modifier is set.

This property is read/write, so you can set it at any time to specify where in the target string the next search should begin. exec() and test() automatically reset lastIndex to 0 when they fail to find a match (or another match).

Buuuuut, str.replace(), str.match() NO NEED to reset the lastIndex

Simple example:

var str = 'Javascript is an interesting scripting language'
var re = /script/g
var pos = 0, match
while (match = re.exec(str)) {
  console.log('"' + str.substring(pos, pos = re.lastIndex) + '" <<== ', [match.index, pos])
}

// output:
// "Javascript" <<==  [ 4, 10 ]
// " is an interesting script" <<==  [ 29, 35 ]

Mobile safari manually focus text field failed using a delay.

button.addEventListener('click', function() {
    // *** If triggered immediately - functionality occurs as expected
    // input.focus();
    // *** If called by callback - triggers the focusin event, but does not bring up keyboard or cursor
    setTimeout(function() {
        input.focus();
    }, 10);
});

Remember that on iOS setting focus on an input element brings up the keyboard – so all those web pages out there that set focus on an input element on page load, like Google does, would be extremely annoying to use on iOS. I guess Apple decided they had to do something to prevent this. this is a feature not a bug.

There’s no known workaround for this, so you’ll have to ditch the idea of using a delay.