Archive for 03/07/14

Tutorial Check if Element is inside Another Specific Element

by in , 0

Replace the first selector with the child you are testing and the second selector with the parent you are testing for.

if ( $(".child-element").parents("#main-nav").length == 1 ) { 

   // YES, the child element is inside the parent

} else {
 
   // NO, it is not inside

}

Tutorial Check if Element Exists

by in , 0

if ($('#myElement').length > 0) { 
    // it exists 
}

Or to make it a fancy function with a callback:

// Tiny jQuery Plugin
// by Chris Goodchild
$.fn.exists = function(callback) {
  var args = [].slice.call(arguments, 1);

  if (this.length) {
    callback.call(this, args);
  }

  return this;
};

// Usage
$('div.test').exists(function() {
  this.append('<p>I exist!</p>');
});
​

Tutorial Check if Checkbox is Checked

by in , 0

Say that 10 times fast =).

Find out if a single checkbox is checked or not, returns true or false:

$('#checkBox').attr('checked');

Find all checked checkboxes:

$('input[type=checkbox]:checked');

Reference URL

Tutorial Check for Empty Elements

by in , 0

Do something for each empty element found:

$('*').each(function() {
         if ($(this).text() == "") {
                   //Do Something
         }
});

TRUE or FALSE if element is empty:

var emptyTest = $('#myDiv').is(':empty');

Tutorial Change WMode with jQuery

by in , 0

If you don't set the wmode on a flash embed it will float over the top of an overlay which can be a pretty big deal. This is ideal in environment with lots of legacy video code or where users will be posting new code and teaching them about wmode is a lost cause. This should work in all browsers.

$("embed").attr("wmode", "opaque");
var embedTag;
$("embed").each(function(i) {
       embedTag = $(this).attr("outerHTML");
       if ((embedTag != null) && (embedTag.length > 0)) {
               embedTag = embedTag.replace(/embed /gi, "embed wmode="opaque" ");
               $(this).attr("outerHTML", embedTag);
       } else {
               $(this).wrap("<div></div>");
       }
});

Reference URL

Tutorial Calculate Distance Between Mouse and Element

by in , 0

(function() {
    
    var mX, mY, distance,
        $distance = $('#distance span'),
        $element  = $('#element');

    function calculateDistance(elem, mouseX, mouseY) {
        return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.offset().left+(elem.width()/2)), 2) + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
    }

    $(document).mousemove(function(e) {  
        mX = e.pageX;
        mY = e.pageY;
        distance = calculateDistance($element, mX, mY);
        $distance.text(distance);         
    });

})();

This code will calculate the distance between the mouse cursor and the center of an element. This can be useful for triggering a function when the mouse is within a certain distance of an element. Or, you can base the value of a property, such as the width, height, or opacity of the element, on the proximity of the mouse cursor.

Reference URL

Tutorial Browser Detection + Apply Classes to HTML Element

by in , 0

// jQBrowser v0.2: http://davecardwell.co.uk/javascript/jquery/plugins/jquery-browserdetect/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(c/a))+String.fromCharCode(c%a+161)};while(c--){if(k[c]){p=p.replace(new RegExp(e(c),'g'),k[c])}}return p}('Ö ¡(){® Ø={\'¥\':¡(){¢ £.¥},\'©\':{\'±\':¡(){¢ £.©.±},\'¯\':¡(){¢ £.©.¯}},\'¬\':¡(){¢ £.¬},\'¶\':¡(){¢ £.¶},\'º\':¡(){¢ £.º},\'Á\':¡(){¢ £.Á},\'À\':¡(){¢ £.À},\'½\':¡(){¢ £.½},\'¾\':¡(){¢ £.¾},\'¼\':¡(){¢ £.¼},\'·\':¡(){¢ £.·},\'Â\':¡(){¢ £.Â},\'³\':¡(){¢ £.³},\'Ä\':¡(){¢ £.Ä},\'Ã\':¡(){¢ £.Ã},\'Å\':¡(){¢ £.Å},\'¸\':¡(){¢ £.¸}};$.¥=Ø;® £={\'¥\':\'¿\',\'©\':{\'±\':²,\'¯\':\'¿\'},\'¬\':\'¿\',\'¶\':§,\'º\':§,\'Á\':§,\'À\':§,\'½\':§,\'¾\':§,\'¼\':§,\'·\':§,\'Â\':§,\'³\':§,\'Ä\':§,\'Ã\':§,\'Å\':§,\'¸\':§};Î(® i=0,«=».ì,°=».í,¦=[{\'¤\':\'Ý\',\'¥\':¡(){¢/Ù/.¨(°)}},{\'¤\':\'Ú\',\'¥\':¡(){¢ Û.³!=²}},{\'¤\':\'È\',\'¥\':¡(){¢/È/.¨(°)}},{\'¤\':\'Ü\',\'¥\':¡(){¢/Þ/.¨(°)}},{\'ª\':\'¶\',\'¤\':\'ß Ñ\',\'¥\':¡(){¢/à á â/.¨(«)},\'©\':¡(){¢ «.¹(/ã(\\d+(?:\\.\\d+)+)/)}},{\'¤\':\'Ì\',\'¥\':¡(){¢/Ì/.¨(«)}},{\'¤\':\'Í\',\'¥\':¡(){¢/Í/.¨(°)}},{\'¤\':\'Ï\',\'¥\':¡(){¢/Ï/.¨(«)}},{\'¤\':\'Ð\',\'¥\':¡(){¢/Ð/.¨(«)}},{\'ª\':\'·\',\'¤\':\'å Ñ\',\'¥\':¡(){¢/Ò/.¨(«)},\'©\':¡(){¢ «.¹(/Ò (\\d+(?:\\.\\d+)+(?:b\\d*)?)/)}},{\'¤\':\'Ó\',\'¥\':¡(){¢/æ|Ó/.¨(«)},\'©\':¡(){¢ «.¹(/è:(\\d+(?:\\.\\d+)+)/)}}];i<¦.Ë;i++){µ(¦[i].¥()){® ª=¦[i].ª?¦[i].ª:¦[i].¤.Õ();£[ª]=É;£.¥=¦[i].¤;® ­;µ(¦[i].©!=²&&(­=¦[i].©())){£.©.¯=­[1];£.©.±=Ê(­[1])}ê{® Ç=Ö ë(¦[i].¤+\'(?:\\\\s|\\\\/)(\\\\d+(?:\\\\.\\\\d+)+(?:(?:a|b)\\\\d*)?)\');­=«.¹(Ç);µ(­!=²){£.©.¯=­[1];£.©.±=Ê(­[1])}}×}};Î(® i=0,´=».ä,¦=[{\'ª\':\'¸\',\'¤\':\'ç\',\'¬\':¡(){¢/é/.¨(´)}},{\'¤\':\'Ô\',\'¬\':¡(){¢/Ô/.¨(´)}},{\'¤\':\'Æ\',\'¬\':¡(){¢/Æ/.¨(´)}}];i<¦.Ë;i++){µ(¦[i].¬()){® ª=¦[i].ª?¦[i].ª:¦[i].¤.Õ();£[ª]=É;£.¬=¦[i].¤;×}}}();',77,77,'function|return|Private|name|browser|data|false|test|version|identifier|ua|OS|result|var|string|ve|number|undefined|opera|pl|if|aol|msie|win|match|camino|navigator|mozilla|icab|konqueror|Unknown|flock|firefox|netscape|linux|safari|mac|Linux|re|iCab|true|parseFloat|length|Flock|Camino|for|Firefox|Netscape|Explorer|MSIE|Mozilla|Mac|toLowerCase|new|break|Public|Apple|Opera|window|Konqueror|Safari|KDE|AOL|America|Online|Browser|rev|platform|Internet|Gecko|Windows|rv|Win|else|RegExp|userAgent|vendor'.split('|')))

/* ----------------------------------------------------------------- */

var aol       = $.browser.aol();       // AOL Explorer
var camino    = $.browser.camino();    // Camino
var firefox   = $.browser.firefox();   // Firefox
var flock     = $.browser.flock();     // Flock
var icab      = $.browser.icab();      // iCab
var konqueror = $.browser.konqueror(); // Konqueror
var mozilla   = $.browser.mozilla();   // Mozilla
var msie      = $.browser.msie();      // Internet Explorer Win / Mac
var netscape  = $.browser.netscape();  // Netscape
var opera     = $.browser.opera();     // Opera
var safari    = $.browser.safari();    // Safari
			
var userbrowser     = $.browser.browser(); //detected user browser

//operating systems

var linux = $.browser.linux(); // Linux
var mac   = $.browser.mac();   // Mac OS
var win   = $.browser.win();   // Microsoft Windows

//version

var userversion    = $.browser.version.number();

/* ----------------------------------------------------------------- */
			
if (mac == true) { 
	
	$("html").addClass("mac"); 
			
	
} else if (linux == true) {
	
	$("html").addClass("linux"); 
	
} else if (win == true) {
	
	$("html").addClass("windows");
	
}

/* ----------------------------------------------------------------- */			

if (userbrowser == "Safari") {
	
	$("html").addClass("safari"); 
	
} else if (userbrowser == "Firefox") {

	$("html").addClass("firefox"); 

} else if (userbrowser == "Camino") {

	$("html").addClass("camino"); 

} else if (userbrowser == "AOL Explorer") {

	$("html").addClass("aol"); 

} else if (userbrowser == "Flock") {

	$("html").addClass("flock"); 

} else if (userbrowser == "iCab") {

	$("html").addClass("icab"); 

} else if (userbrowser == "Konqueror") {

	$("html").addClass("konqueror"); 

} else if (userbrowser == "Mozilla") {

	$("html").addClass("mozilla"); 

} else if (userbrowser == "Netscape") {

	$("html").addClass("netscape"); 

} else if (userbrowser == "Opera") {

	$("html").addClass("opera"); 

} else if (userbrowser == "Internet Explorer") {
	
	$("html").addClass("ie");
	
} else {}

$("html").addClass("" + userversion + "");

Tutorial Better Broken Image Handling

by in , 0

Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead you may want to replace that with a "missing image" graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible, because images that a browser can't find fire off an "error" JavaScript event we can watch for.

// Replace source
$('img').error(function(){
        $(this).attr('src', 'missing.png');
});

// Or, hide them
$("img").error(function(){
        $(this).hide();
});

Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.

Tutorial Automatically Discover Document Links And Apply Class

by in , 0

$('a[href]').each(function() {
   if((C = $(this).attr('href').match(/[.](doc|xls|pdf)$/))) {
       $(this).addClass(C[1]);
   }
});

This will look through every a element on the page. If the href attribute of it has a .doc, .xls, or .pdf in it, it will apply the appropriate class name to it (e.g. class="doc")

Tutorial Append Site Overlay DIV

by in , 0

$(function() {

   var docHeight = $(document).height();

   $("body").append("<div id='overlay'></div>");

   $("#overlay")
      .height(docHeight)
      .css({
         'opacity' : 0.4,
         'position': 'absolute',
         'top': 0,
         'left': 0,
         'background-color': 'black',
         'width': '100%',
         'z-index': 5000
      });

});

Overlays entire site with a black tint, disabling all links and bringing into focus anything above it.

Tutorial Animate Height/Width to “Auto”

by in , 0

It's not possible to do thing.animate({ "height": "auto" });. So this is Darcy Clarke's method to allow that to work. You essentially clone the element, remove the fixed heights currently inflicting the element, and measure/save the value. Then you animate the real element to that value.

jQuery.fn.animateAuto = function(prop, speed, callback){
    var elem, height, width;
    return this.each(function(i, el){
        el = jQuery(el), elem = el.clone().css({"height":"auto","width":"auto"}).appendTo("body");
        height = elem.css("height"),
        width = elem.css("width"),
        elem.remove();
        
        if(prop === "height")
            el.animate({"height":height}, speed, callback);
        else if(prop === "width")
            el.animate({"width":width}, speed, callback);  
        else if(prop === "both")
            el.animate({"width":width,"height":height}, speed, callback);
    });  
}

Usage

$(".animateHeight").bind("click", function(e){
    $(".test").animateAuto("height", 1000); 
});

$(".animateWidth").bind("click", function(e){
    $(".test").animateAuto("width", 1000); 
});

$(".animateBoth").bind("click", function(e){
    $(".test").animateAuto("both", 1000); 
});

Reference URL

Tutorial Adding/Removing Class on Hover

by in , 0

$('#elm').hover(
       function(){ $(this).addClass('hover') },
       function(){ $(this).removeClass('hover') }
)

This will work in any browser on any element, to support styling changes on hover.

Tutorial Add Non-Breaking Space on Title to Prevent Widows

by in , 0

$("h2").each(function() {
         var wordArray = $(this).text().split(" ");
         var finalTitle = "";
         for (i=0;i<=wordArray.length-1;i++) {
            finalTitle += wordArray[i];
            if (i == (wordArray.length-2)) {
                finalTitle += "&nbsp;";
            } else { 
                finalTitle += " ";
            }
          }
          $(this).html(finalTitle);
});

Turns this:
New Screencast: First Ten Minutes with TypeKit

Into this:
New Screencast: First Ten Minutes with&nbsp;TypeKit

Tutorial Add Active Navigation Class Based on URL

by in , 0

Ideally you output this class from the server side, but if you can't...

Let's say you have navigation like this:

<nav>
	<ul>
		<li><a href="/">Home</a></li>
		<li><a href="/about/">About</a></li>
		<li><a href="/clients/">Clients</a></li>
		<li><a href="/contact/">Contact Us</a></li>
	</ul>
</nav>	

And you are at the URL:

http://yoursite.com/about/team/

And you want the About link to get a class of "active" so you can visually indicate it's the active navigation.

$(function() {
  $('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});

Essentially that will match links in the nav who's href attribute begins with "/about" (or whatever the secondary directory happens to be).

Tutorial Add :nth-of-type to jQuery

by in , 0

$.expr[':']['nth-of-type'] = function(elem, i, match) {
    var parts = match[3].split("+");
    return (i + 1 - (parts[1] || 0)) % parseInt(parts[0], 10) === 0;
};

See the original article for more info on adding the other "of type" selectors.

Tutorial Word Count Bookmarklet

by in , 0

Add to bookmarks bar, select text, click it to get the word count.

<a href="javascript:(function(){var%20t;if%20(window.getSelection)%20t%20=%20window.getSelection();else%20if%20(document.selection)%20t%20=%20document.selection.createRange();if%20(t.text%20!=%20undefined)%20t%20=%20t.text;if(!t%20||%20t%20==%20""){%20a%20=%20document.getElementsByTagName("textarea");%20for(i=0;%20i<a.length;%20i++)%20{%20%20if(a[i].selectionStart%20!=%20undefined%20&&%20a[i].selectionStart%20!=%20a[i].selectionEnd)%20%20{%20%20%20%20t%20=%20a[i].value.substring(a[i].selectionStart,%20a[i].selectionEnd);%20%20%20%20break;%20%20}%20}}if(!t%20||%20t%20==%20"")alert("please%20select%20some%20text");else%20alert("word%20count:%20"%20+%20t.toString().match(/(\S+)/g).length);})()" class="button">Count Words</a>

Bookmarklet

Count Words < Drag to Bookmarks Bar

Reference URL

Tutorial Viewport Size, Screen Resolution, Mouse Postition

by in , 0

This code is cross-browser compatible and checks the dimensions of the viewport, the screen resolution and the mouseposition which can be quite helpful to perform some checks with JavaScript.

<script type="text/javascript">
function getViewportWidth()
{
       if (window.innerWidth)
       {
               return window.innerWidth;
       }
       else if (document.body && document.body.offsetWidth)
       {
               return document.body.offsetWidth;
       }
       else
       {
               return 0;
       }
}

function getViewportHeight()
{
       if (window.innerHeight)
       {
               return window.innerHeight;
       }
       else if (document.body && document.body.offsetHeight)
       {
               return document.body.offsetHeight;
       }
       else
       {
               return 0;
       }
}

var tellMeTheSizes=function()
{
       document.getElementById("viewportwidth").innerHTML = getViewportWidth() + "px";
       document.getElementById("viewportheight").innerHTML = getViewportHeight() + "px";
       document.getElementById("resolutionheight").innerHTML = screen.height + "px";
       document.getElementById("resolutionwidth").innerHTML = screen.width + "px";
}

window.onload=function()
{
       tellMeTheSizes();
}

window.onresize=function()
{
       tellMeTheSizes();
}

window.onmousemove=function(event)
{
       ev = event || window.event;
       document.getElementById("mousetop").innerHTML = ev.pageY + "px";
       document.getElementById("mouseleft").innerHTML = ev.pageX + "px";
}
</script>

Tutorial Validate HTML Bookmarklet

by in , 0

javascript:(function(){%20function%20fixFileUrl(u)%20{%20var%20windows,u;%20windows%20=%20(navigator.platform.indexOf("Win")%20!=%20-1);%20%20/*%20chop%20off%20file:///,%20unescape%20each%20%hh,%20convert%20/%20to%20\%20and%20|%20to%20:%20*/%20%20u%20=%20u.substr(windows%20?%208%20:%207);%20u%20=%20unescape(u);%20if(windows)%20{%20u%20=%20u.replace(/\//g,"\");%20u%20=%20u.replace(/\|/g,":");%20}%20return%20u;%20}%20/*%20bookmarklet%20body%20*/%20var%20loc,fileloc;%20loc%20=%20document.location.href;%20if%20(loc.length%20>%209%20&&%20loc.substr(0,8)=="file:///")%20{%20fileloc%20=%20fixFileUrl(loc);%20if%20(prompt("Copy%20filename%20to%20clipboard,%20press%20enter,%20paste%20into%20validator%20form",%20fileloc)%20!=%20null)%20{%20document.location.href%20=%20"http://validator.w3.org/file-upload.html"%20}%20}%20else%20document.location.href%20=%20"http://validator.w3.org/check?uri="%20+%20escape(document.location.href);%20void(0);%20})();

Make a bookmark with the above code, or just drag the following button link to your bookmarklets bar.

validate html

Tutorial Unescape HTML in JS

by in , 0

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

Usage

htmlDecode("&lt;img src='myimage.jpg'&gt;"); 
// returns "<img src='myimage.jpg'>"

Tutorial Trim First/Last Characters in String

by in , 0

Remove last four characters

var myString = "abcdefg";
var newString = myString.substr(0, myString.length-4); 
// newString is now "abc"

Remove first two characters

var myString = "abcdefg";
var newString = myString.substr(2);
// newString is now "cdefg"

Notes

The substr function can be called on any string with two integer parameters, the second optional. If only one provided, it starts at that integer and moves to the end of the string, chopping off the start. If two parameters provided, it starts at the first number and ends at the second, chopping off the start and end as it is able.

Example

abcdefghijklmnopqrstuvwxyz

Press to Chop

Tutorial Toggle (Show/Hide) Element

by in , 0

<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>

Inline usage:

<a href="#" >Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>

Reference URL

Tutorial Test if Mac or PC with JavaScript

by in , 0

User Agent testing sucks, but sometimes you need it for subtle things. In my case I was using it to adjust what I was showing for keyboard shortcut keys (Command or Control). Nothing super major.

if (navigator.userAgent.indexOf('Mac OS X') != -1) {
  $("body").addClass("mac");
} else {
  $("body").addClass("pc");
}

The statements in there use jQuery to add a body class, but that's not required, you could do whatever.

Tutorial Test if Element Supports Attribute

by in , 0

Not all browsers support all attributes on all elements. There are a number of new attributes in HTML5, so the idea of testing to see what kind of browser environment you are in becomes every increasingly important.

function elementSupportsAttribute(element, attribute) {
  var test = document.createElement(element);
  if (attribute in test) {
    return true;
  } else {
    return false;
  }
};

Usage

if (elementSupportsAttribute("textarea", "placeholder") {

} else {
   // fallback
}

Tutorial Test if dragenter/dragover Event Contains Files

by in , 0

HTML5 drag and drop is great for handling file uploads. But if that's the only thing you are using it for, it's nice to know if any particular dragenter or dragover event actually has files. Unlike, for example, just the dragging of some selected text.

Send the event object to this function and it will return the truth (assuming you are in a browser that supports all this):

function containsFiles(event) {

    if (event.dataTransfer.types) {
        for (var i = 0; i < event.dataTransfer.types.length; i++) {
            if (event.dataTransfer.types[i] == "Files") {
                return true;
            }
        }
    }
    
    return false;

}

Reference URL

Tutorial Test for Internet Explorer in JavaScript

by in , 0

var isMSIE = /*@cc_on!@*/0;

if (isMSIE) {
  // do IE-specific things
} else {
  // do non IE-specific things
}

Reference URL

Tutorial Support Tabs in Textareas

by in , 0

Normally the tab key moves to the next focusable thing. This inserts a tab character in instead.

HTMLTextAreaElement.prototype.getCaretPosition = function () { //return the caret position of the textarea
    return this.selectionStart;
};
HTMLTextAreaElement.prototype.setCaretPosition = function (position) { //change the caret position of the textarea
    this.selectionStart = position;
    this.selectionEnd = position;
    this.focus();
};
HTMLTextAreaElement.prototype.hasSelection = function () { //if the textarea has selection then return true
    if (this.selectionStart == this.selectionEnd) {
        return false;
    } else {
        return true;
    }
};
HTMLTextAreaElement.prototype.getSelectedText = function () { //return the selection text
    return this.value.substring(this.selectionStart, this.selectionEnd);
};
HTMLTextAreaElement.prototype.setSelection = function (start, end) { //change the selection area of the textarea
    this.selectionStart = start;
    this.selectionEnd = end;
    this.focus();
};

var textarea = document.getElementsByTagName('textarea')[0]; 

textarea.onkeydown = function(event) {
    
    //support tab on textarea
    if (event.keyCode == 9) { //tab was pressed
        var newCaretPosition;
        newCaretPosition = textarea.getCaretPosition() + "    ".length;
        textarea.value = textarea.value.substring(0, textarea.getCaretPosition()) + "    " + textarea.value.substring(textarea.getCaretPosition(), textarea.value.length);
        textarea.setCaretPosition(newCaretPosition);
        return false;
    }
    if(event.keyCode == 8){ //backspace
        if (textarea.value.substring(textarea.getCaretPosition() - 4, textarea.getCaretPosition()) == "    ") { //it's a tab space
            var newCaretPosition;
            newCaretPosition = textarea.getCaretPosition() - 3;
            textarea.value = textarea.value.substring(0, textarea.getCaretPosition() - 3) + textarea.value.substring(textarea.getCaretPosition(), textarea.value.length);
            textarea.setCaretPosition(newCaretPosition);
        }
    }
    if(event.keyCode == 37){ //left arrow
        var newCaretPosition;
        if (textarea.value.substring(textarea.getCaretPosition() - 4, textarea.getCaretPosition()) == "    ") { //it's a tab space
            newCaretPosition = textarea.getCaretPosition() - 3;
            textarea.setCaretPosition(newCaretPosition);
        }    
    }
    if(event.keyCode == 39){ //right arrow
        var newCaretPosition;
        if (textarea.value.substring(textarea.getCaretPosition() + 4, textarea.getCaretPosition()) == "    ") { //it's a tab space
            newCaretPosition = textarea.getCaretPosition() + 3;
            textarea.setCaretPosition(newCaretPosition);
        }
    } 
}

Reference URL

Tutorial Strip Whitespace From String

by in , 0

Whitespace, meaning tabs and spaces.

// Remove leading and trailing whitespace
// Requires jQuery
var str = " a b    c d e f g ";
var newStr = $.trim(str);
// "a b c d e f g"

// Remove leading and trailing whitespace
// JavaScript RegEx
var str = "   a b    c d e f g ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
// "a b c d e f g"

// Remove all whitespace
// JavaScript RegEx
var str = " a b    c d e   f g   ";
var newStr = str.replace(/\s+/g, '');
// "abcdefg"

Doesn't work with other types of whitespace though, for instance &#8239; (thin space) or &nbsp; (non-breaking space)

Tutorial Strip Numbers from a String

by in , 0

var someString = "Hello 123 World!";

newString = someString.replace(/[0-9]/g, '');

// console.log(newString);
// "Hello  World!";

Tutorial Strip HTML Tags in JavaScript

by in , 0

var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");

Tutorial Shuffle Array

by in , 0

Technique #1

function Shuffle(o) {
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

Usage

var testArray = [1,2,3,4,5];
Shuffle(testArray);

// jQuery to dump out new values to element with ID of 'dump'
$(function() {
   for (var i=0;i<testArray.length;i++) {
      $("#dump").append(testArray[i]);
   }
});

Technique #2

yourArray.sort(function() { return 0.5 - Math.random() });

Tutorial Saving contenteditable Content Changes as JSON with Ajax

by in , 0

Elements with the contenteditable attribute can be live-edited right in the browser window. But of course those changes don't affect the actual document on your server, so those changes don't persist with a page refresh.

One way to save the data would be to wait for the return key to be pressed, which triggers then sends the new innerHTML of the element as an Ajax call and blurs the element. Pressing escape returns the element to it's pre-edited state.

document.addEventListener('keydown', function (event) {
  var esc = event.which == 27,
      nl = event.which == 13,
      el = event.target,
      input = el.nodeName != 'INPUT' && el.nodeName != 'TEXTAREA',
      data = {};

  if (input) {
    if (esc) {
      // restore state
      document.execCommand('undo');
      el.blur();
    } else if (nl) {
      // save
      data[el.getAttribute('data-name')] = el.innerHTML;

      // we could send an ajax request to update the field
      /*
      $.ajax({
        url: window.location.toString(),
        data: data,
        type: 'post'
      });
      */
      log(JSON.stringify(data));

      el.blur();
      event.preventDefault();
    }
  }
}, true);

function log(s) {
  document.getElementById('debug').innerHTML = 'value changed to: ' + s;
}

Live demo on JS Bin by Remy Sharp.

Tutorial Remove the Last Character from a String

by in , 0

var origString = 'Happy Dance7';
var trimmedString = origString.substring(0, origString.length-1);
console.log(trimmedString);
// 'Happy Dance'

Tutorial Remove Inline Styles

by in , 0

This function also preserves hidden content.

function remove_style(all) {
  var i = all.length;
  var j, is_hidden;

  // Presentational attributes.
  var attr = [
    'align',
    'background',
    'bgcolor',
    'border',
    'cellpadding',
    'cellspacing',
    'color',
    'face',
    'height',
    'hspace',
    'marginheight',
    'marginwidth',
    'noshade',
    'nowrap',
    'valign',
    'vspace',
    'width',
    'vlink',
    'alink',
    'text',
    'link',
    'frame',
    'frameborder',
    'clear',
    'scrolling',
    'style'
  ];

  var attr_len = attr.length;

  while (i--) {
    is_hidden = (all[i].style.display === 'none');

    j = attr_len;

    while (j--) {
      all[i].removeAttribute(attr[j]);
    }

    // Re-hide display:none elements,
    // so they can be toggled via JS.
    if (is_hidden) {
      all[i].style.display = 'none';
      is_hidden = false;
    }
  }
}

Usage

Call the function like this:

var all = document.getElementsByTagName('*');
remove_style(all);

Note: Selecting all elements in the page via a wildcard query could be slow, depending on how many elements are in the page. You could use a smaller set of elements to be more performant:

var set = document.getElementById('foo').getElementsByTagName('bar');
remove_style(set);

Code by Nathan Smith.

Tutorial Redirect to SSL

by in , 0

window.location = "https://" + window.location.hostname + window.location.pathname + window.location.search;

You might wanna test if window.location.href doesn't start with "https" before doing that, so you don't redirect unless you have to.

Tutorial Redirect

by in , 0

<script type="text/javascript">
<!--
  window.location = "http://www.google.com/"
//-->
</script>

Tutorial Random Hex Color

by in , 0

var randomColor = Math.floor(Math.random()*16777215).toString(16);

View Demo

There is also a PHP version.

Reference URL

Tutorial Put Comma Values in Numbers

by in , 0

This function assumes what is being submitted to it is a string, with a decimal point and two places after the decimal. To get your number into that format first, use this.

Then this function will properly comma separate the number. For example, 2345643.00 will return 2,345,643.00

function CommaFormatted(amount) {
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3) {
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}

Tutorial Print Object To Screen

by in , 0

PHP has a nice print_r function for printing out information about a variable to the screen. console.log() is great for that in JavaScript also, but sometimes you just need/want to look at it on the screen.

function print_r(o) {
  return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;'); 
}

So if you have an object like:

var myObject = {
   "lunch": "sandwich",
   "dinner": "stirfry"
};

You could do:

var putHere = document.getElementById("#put-here");

putHere.innerHTML = print_r(myObject);

to see the result on screen.

Also, console.table() is sometimes much better than console.log() for this kind of thing.

Tutorial Prevent Embedded JavaScript from Failing Validation

by in , 0

Ever see that CDATA stuff in JavaScript and wonder what it was for? It is to prevent the validator from reading that code as markup and failing validation. For example, ampersands (&) and greater-than / less-than signs (< >)are often culprits for failing validation when it's actually perfectly OK to use them in JavaScript.

<script type="text/javascript">
  //<![CDATA[

    alert("<This is compatible with XHTML>");

  //]]>
</script> 

Tutorial Prevent Background Image Flickering in IE

by in , 0

try {
 document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}

Tutorial Perform Function At Timed Intervals

by in , 0

Perform a function every one second:

function myFunction() {
   // do something
}

var int = setInterval(myFunction, 1000);

Cancel it:

clearInterval(int);

Pass variables when calling custom function:

setInterval(function(){ doMove(panelWidth, tooFar); }, delayLength);

Tutorial PageVisibility API

by in , 0

<!DOCTYPE HTML>  
 <html>  
 <head>  
      <script type="text/javascript">  
           timer = 0;  
           function onLoad(){  
                document.addEventListener("visibilitychange",stateChanged);  
                document.addEventListener("webkitvisibilitychange", stateChanged);  
                document.addEventListener("msvisibilitychange", stateChanged);  
           }  
           function stateChanged(){  
                console.log(document.webkitVisibilityState);  
                if(document.hidden || document.webkitHidden || document.msHidden){  
                     //new tab or window minimized
                     timer = new Date().getTime();  
                }  
                else {  
                     alert('You were away for ' + (new Date().getTime()-timer)/1000+ ' seconds.')  
                }  
           }  
      </script>  
 </head>  
 <body >  
 </body>  
 </html>

Demo by Sagar Ganatra

Tutorial Namespaced Javascript Template

by in , 0

Self invoking anonymous function assigned to the yournamespacechoice global variable. Serves the effect of keeping all functions and variables private to this function. To expose a function or variable we must explictly return it at the bottom of the function. Remaps jQuery to $.

var yournamespacechoice = (function ($) {
   var publicfunction;

   function privatefunction() {
       // function only available within parent function
   }

   publicfunction = function publicfunction() {
       // public function available outside of this funtion
   };

   // Expose any functions that we need to access outside of this scope. Use yournamespacechoice.functionName() to call them.
   return {
       publicfunction: publicfunction
   };
}(window.$));

Tutorial Multiline String Variables in JavaScript

by in , 0

This works:

var htmlString = "<div>This is a string.</div>";

This fails:

var htmlSTring = "<div>
  This is a string.
</div>";

Sometimes this is desirable for readability.

Add backslashes to get it to work:

var htmlSTring = "<div>\
  This is a string.\
</div>";

Tutorial Move Cursor to End of Input

by in , 0

Where el is a reference to an input or textarea.

function moveCursorToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

Reference URL

Javascript Modern Event Handling

by in , 0

<script type="text/javascript">
/**
 * Attach an event handler on a given Node taking care of Browsers Differences
 * @param {Object} node
 * @param {String} type
 * @param {Function} fn
 * @param {Boolean} capture
 */
function addEventHandler(node,type,fn , capture){
       if(typeof window.event !== "undefined"){
                /* Internet Explorer way */
               node.attachEvent( "on" + type, fn );
       } else {
               /* FF & Other Browsers */
               node.addEventListener( type, fn , capture );
       }
}


/* Example */
addEventHandler(window,"load",function(){
   alert("The page was loaded");
},true)
</script>
This is better than doing the traditional "window.onload" event, as it can attach multiple event handlers to a single event and they all get called.

How to Make HTML5 Elements Work in Old IE

by in , 0

(function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while(i--){document.createElement(e[i])}})()
Hotlink Script:
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->