Showing posts with label javascript. Show all posts

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;


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

// jQuery to dump out new values to element with ID of 'dump'
$(function() {
   for (var i=0;i<testArray.length;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 =,
      input = el.nodeName != 'INPUT' && el.nodeName != 'TEXTAREA',
      data = {};

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

      // we could send an ajax request to update the field
        url: window.location.toString(),
        data: data,
        type: 'post'

}, 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);
// '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 = [

  var attr_len = attr.length;

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

    j = attr_len;

    while (j--) {

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


Call the function like this:

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

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');

Code by Nathan Smith.

Tutorial Redirect to SSL

by in , 0

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

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 = ""

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);
		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">

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


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:


Pass variables when calling custom function:

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

Tutorial PageVisibility API

by in , 0

      <script type="text/javascript">  
           timer = 0;  
           function onLoad(){  
                document.addEventListener("webkitvisibilitychange", stateChanged);  
                document.addEventListener("msvisibilitychange", stateChanged);  
           function stateChanged(){  
                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.')  
 <body >  

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

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.

Sometimes this is desirable for readability.

Add backslashes to get it to work:

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

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") {
        var range = el.createTextRange();

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 */
   alert("The page was loaded");
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=""></script>