Javascript

Created Thursday 28 November 2013

  1. Mozilla JS docs:
    1. https://developer.mozilla.org/en-US/docs/Web/JavaScript

  1. Checking if var is undefined:
    1. if (typeof variable === 'undefined') {...}
      1. http://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null
    2. Var exists, check if there is any value in it:
      1. if (undefined != yourvar) {...}
      2. http://stackoverflow.com/questions/858181/how-to-check-a-not-defined-variable-in-javascript
    3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
  2. Check if variable is array:
    1. variable instanceof Array
    2. Object.prototype.toString.call(variable) === '[object Array]'
    3. http://stackoverflow.com/questions/1058427/how-to-detect-if-a-variable-is-an-array
  3. Prevent refresh:
    1. http://codingresource.blogspot.co.il/2010/04/disable-refresh-in-webpage-using.html
    2. http://forums.asp.net/t/1278949.aspx
  4. Removing URL from history to avoid loosing iframe contents on back + show iframe only when loaded:
    1. Based on some research...:
      1. http://forums.devshed.com/javascript-development-115/location-replace-firefox-and-iframe-257460.html
      2. http://www.w3schools.com/jsref/met_loc_replace.asp
    2. Example:
var init = false;
if ($('#yourSbtButton').length) {
    $('#yourSbtButton').click(function () {
     if ($('#myIframe').length) {
        $('#myIframe').load(function () {
// Setting URL in cookie for the latter use
         if ($.cookie('someCk') && parseFloat(someCk.getValue('counter')) == 0 && !someCk.getValue('url')) {
            var counter = parseFloat(someCk.getValue('counter'));
            counter++;
            someCk.updateCookie('counter', counter);
            someCk.updateCookie('url', encodeURIComponent($(this).contents().get(0).location.href));
         }
// Check if iframe's contents are loaded
         if ($('#myIframe').contents().find('#someForm').length) {
            $('#myIframeWrap').show()
            $('.toHideOnIframeReady').hide();
            if (init) {
             var curHeight = parseFloat($('#someDiv').height());
             curHeight += 250;
             $('#someDiv').height(curHeight + 'px');
             init = false;
             var marginTop = parseFloat($('#someOtherDiv').css('margin-top'));
             marginTop += 30;
             $('#someOtherDiv').css('margin-top', marginTop + 'px');
            }
         } else { // Get the iframe contents on back button with the previously set URL
            if ($.cookie('someCk') && parseFloat(someCk.getValue('counter')) > 0 && someCk.getValue('url')) {
             $(this).contents().get(0).location.replace(decodeURIComponent(someCk.getValue('url')));
            }
         }
        });
     }
    });
}

  1. Password generator:
    1. http://stackoverflow.com/questions/1497481/javascript-password-generator
function generatePassword(length) {
var charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
  1. Cross domain iframe focus
<!DOCTYPE html>
<html>
<head>
<title>Check cross domain iframe focusing</title>
<script type="text/javascript">
window.addEventListener("load", function(e) {
     var iframe = document.getElementById("iframe");
     iframe.focus();
});
</script>
</head>
<body>
<iframe id="iframe"
     style="width:500px;height:500px;"
** src="https://other.domain.com/someuser/service.php?param1=25&param2=1&param3=1">**
</iframe>
</body>
</html>
  1. Get ouf of iframe
<!DOCTYPE html>
<html>
<head>
<title>Get out of iframe</title>
<script type="text/javascript">
window.addEventListener("load", function(e) {
     var iframe = document.getElementById("iframe");
     var toIframe = document.getElementById("toIframe");
     var srcToIframe = function(e) {
     if (window.top.location !== window.location) {
         toIframe.setAttribute("disabled", "disabled");
         alert("Hey, I'm in iFrame!");
     } else {
         // Enter the iFrame
     }
     }
     toIframe.addEventListener("click", srcToIframe);
     var getMeOut = document.getElementById("getMeOut");
     var goingOut = function(e) {
     if (window.top.location !== window.location) {
         window.top.location = window.location;
     } else {
         alert("Hey, I'm not in iFrame!");
     }
     }
     getMeOut.addEventListener("click", goingOut);
});
</script>
</head>
<body>
<form id="form"
** action="http://yourdomain.com/iframeout.html?iframe=1"**
     target="iframe">
<button id="getMeOut" type="button">Get me out of iFrame!</button>
<input id="toIframe" type="submit" value="To iFrame" />
</form>
<iframe id="iframe"
     name="iframe"
     src=""
     style="width:500px;height:500px;">
</iframe>
</body>
</html>
  1. Cookies
http://www.w3schools.com/js/js_cookies.asp
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT";
var x = document.cookie;
document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie()
{
var username=getCookie("username");
if (username!="")
{
alert("Welcome again " + username);
}
else
{
username = prompt("Please enter your name:","");
if (username!="" && username!=null)
{
setCookie("username",username,365);
}
}
}

function removeEventHandler(elem,eventType,handler) {
if (elem.removeEventListener)
elem.removeEventListener (eventType,handler,false);
if (elem.detachEvent)
elem.detachEvent ('on'+eventType,handler);
}
// Here is an example of calling removeEventHandler()
// to unregister event handlers for 'button1' and 'button2':
var b1 = document.getElementById('button1');
var b2 = document.getElementById('button2');

removeEventHandler(b1,'click',handlerFunction1);
removeEventHandler(b2,'click',handlerFunction2);

function doSomething(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
}

function doSomething(e, param1, param2) {
if (!e) var e = window.event; // for IE
var unlockMeImg = e.target ? e.target : e.srcElement; // for IE
if (unlockMeImg.nodeType == 3) unlockMeImg = unlockMeImg.parentNode; // for Safari
var unlockMeA = unlockMeImg.parentNode;

if (confirm('Super test?')) {
var aParent = unlockMeA.parentNode;
unlockMeA.parentNode.removeChild(unlockMeA);
aParent.innerHTML = '<center>' +
.........................
</center>';
surpriseFunc(param1, param2);
} else {
// nothing to do...
}
}
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();

var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();

return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
function getSelectedOptions(el) {
var rv = [];
for (var i = 0; i < el.options.length; i++) {
if (el.options[i].selected) {
rv.push(el.options[i]);
}
}
return rv;
};

function serializeToQueryString(form) {
var results = {};
var rv = '';
var inputs = form.elements;

for (var k = 0; k < inputs.length; k++) {
var el = inputs[k];

if (el == null || el.nodeName == undefined) continue;

var tagName = el.nodeName.toLowerCase();
if (!(tagName == "input" || tagName == "select" || tagName == "textarea")) continue;

var type = el.type, names =[], name = el.name, current;
if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') continue;

var value = (tagName == 'select') ? getSelectedOptions(el).map(function(opt){
return opt.value;
}) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.value;

if (value != null) rv = rv + "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(value);
}

return (rv.length > 0) ? rv.substring(1) : rv;
};



Backlinks: