Sunday, March 30, 2014

JavaScript Tips

Google Hosted JS libraries:

https://developers.google.com/speed/libraries/devguide
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

StartsWith
http://stackoverflow.com/questions/1767246/javascript-check-if-string-begins-with-something
You can use string.match() and a regular expression for this too:
if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes
string.match() will return the matching string if found, otherwise null.

if (pathname.substring(0, 6) == "/sub/1") {

http://stackoverflow.com/questions/957537/how-can-i-print-a-javascript-object

Use JSON.stringify(obj); Also this method works with nested objects.

How to get querystring value using jQuery
http://www.jquerybyexample.net/2012/05/how-to-get-querystring-value-using.html
function GetQueryStringParams(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
    }
}​

http://www.designchemical.com/blog/index.php/jquery/8-useful-jquery-snippets-for-urls-querystrings/
Get The Current Page URL
var url = document.URL;
Get The Current Root URL
var root = location.protocol + '//' + location.host;
var param = document.URL.split('#')[1];

Scroll Windows Screen
window.scrollBy(0,500);

Get Random Position In an Array
var randomIdx = Math.floor(Math.random()*iframeUrls.length);

Catch error if iframe src fails to load
http://stackoverflow.com/questions/15273042/catch-error-if-iframe-src-fails-to-load-error-refused-to-display-http-ww
var iframeError;
function change() {
    var url = $("#addr").val();
    $("#browse").attr("src", url);
    iframeError = setTimeout("error()", 5000);
}

function load(e) {
    alert(e);
}

function error() {
    alert('error');
}

$(document).ready(function () {
    $('#browse').on('load', (function () {
        load('ok');
        clearTimeout(iframeError);
    }));


});

No comments:

Post a Comment