Showing posts with label javascript. Show all posts

Tutorial Empty an Array

by in , 0

This is one of the fastest and easiest ways of emptying an array. Of course there are may other ways, but those usually include creation of a new array. This way you reuse the same array.

var myArray = ["one", "two", "three"];

// console.log( myArray ) => ["one", "two", "three"]

myArray.length = 0;

// console.log( myArray ) => []

Tutorial Different Stylesheets for Different Days of the Week

by in , 0

<script type="text/javascript">
<!--
dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
dayNumber = new Date().getDay();
document.writeln('<link rel="stylesheet" type="text/css" href="' + dayNames[dayNumber] + '.css">');
//-->
</script>

<noscript>
<link rel="stylesheet" type="text/css" href="default.css">
</noscript>

Name your css files accordingly: Saturday.css, Friday.css, Sunday.css, etc...

If JavaScript is disabled in the browser, it will revert back to the default.css file.

Tutorial Different Stylesheet Pending the Time of Day

by in , 0

<script>
<!--
function getStylesheet() {
      var currentTime = new Date().getHours();
      if (0 <= currentTime&&currentTime < 5) {
       document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
      }
      if (5 <= currentTime&&currentTime < 11) {
       document.write("<link rel='stylesheet' href='morning.css' type='text/css'>");
      }
      if (11 <= currentTime&&currentTime < 16) {
       document.write("<link rel='stylesheet' href='day.css' type='text/css'>");
      }
      if (16 <= currentTime&&currentTime < 22) {
       document.write("<link rel='stylesheet' href='evening.css' type='text/css'>");
      }
      if (22 <= currentTime&&currentTime <= 24) {
       document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
      }
}

getStylesheet();
-->
</script>

<noscript><link href="main.css" rel="stylesheet"></noscript>

Name your css files accordingly: night.css, day.css, etc... One cool bonus is that since JavaScript gets the time from the local machine instead of from the server, users will be served the time-based stylesheet based on their time, not the server's, which may be in a completely different timezone.

If JavaScript is disabled in the browser, it will default to the main.css stylesheet.

Tutorial Detect Javascript On/Off, With Notification

by in , 0

<script type="text/javascript">
   document.write("Welcome, you have Javascript on.")
</script>

<noscript>JavaScript is off. Please enable to view full site.</noscript>

If JavaScript is on the user gets a welcome message. If off, the user is instructed to turn it on.

Tutorial Detect Internet Explorer

by in , 0

<script type="text/javascript">

if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
 if (ieversion>=8)
  document.write("You're using IE8 or above")
 else if (ieversion>=7)
  document.write("You're using IE7.x")
 else if (ieversion>=6)
  document.write("You're using IE6.x")
 else if (ieversion>=5)
  document.write("You're using IE5.x")
}
else
 document.write("n/a")

</script>

Reference

Tutorial Default Arguments for Functions

by in , 0

// Combiner of passed arguments and defaults (usable with any function)
Object.prototype.combine = function(_args){
  for(var i in this) {
    if(typeof _args[i] == "undefined") {
      _args[i] = this[i];
    }
  }
};

// Specific example function with defaults
function feedTheCat(args){
  var defaults = {
      'morning' : "nothing",
      'noon'    : "pork",
      'nite'    : "mouse"
  };
  defaults.combine(args);
}

// USAGE: only passing 2 of 3 arguments
feedTheCat({
  'morning': "milk", 
  'nite': "kitekat"
}); 

// Values would be: milk | pork | kitekat

Reference URL

Tutorial Current Page with JavaScript

by in , 0

This is like a replacement for PHP's SCRIPT_NAME with JavaScript.

location.href.split('/').pop();

For example with this URL:

http://css-tricks.com/examples/ScriptName/index.php

This code:

document.write( location.href.split('/').pop() );

Would write to the page: "index.php"

Reference URL

Tutorial CSS for when JavaScript is Enabled

by in , 0

document.documentElement.className = "js"

This adds a class to the root <html>, so you could (for example) do something like hide a <div> only when JavaScript is enabled.

.js div#id { display: none; }

Tutorial Cookie Getter/Setter

by in , 0

/**
 * Gets or sets cookies
 * @param name
 * @param value (null to delete or undefined to get)
 * @param options (domain, expire (in days))
 * @return value or true
 */
_.cookie = function(name, value, options)
{
    if (typeof value === "undefined") {
        var n, v,
            cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++) {
            n = $.trim(cookies[i].substr(0,cookies[i].indexOf("=")));
            v = cookies[i].substr(cookies[i].indexOf("=")+1);
            if (n === name){
                return unescape(v);
            }
        }
    } else {
        options = options || {};
        if (!value) {
            value = "";
            options.expires = -365;
        } else {
            value = escape(value);
        }
        if (options.expires) {
            var d = new Date();
            d.setDate(d.getDate() + options.expires);
            value += "; expires=" + d.toUTCString();
        }
        if (options.domain) {
            value += "; domain=" + options.domain;
        }
        if (options.path) {
            value += "; path=" + options.path;
        }
        document.cookie = name + "=" + value;
    }
};

Reference URL

Tutorial Comments in JavaScript

by in , 0

function doSomething() {

    /*
           This code by Chris Coyier
    */

    var i = 0;    // counter to be used later;

}

Comments in JavaScript can be between /* */ markings (useful for multiple line comments) or after // markings (for single lines only).

Tutorial Clear Field on Focus

by in , 0

<input type="text" onfocus="if(this.value == 'value') { this.value = ''; }" value="value" />

Replace "value" with the default value. If the field is selected, the default value will go away. If the user has previously changed the field value, it'll be left alone.

Alternatively, use onfocus="this.value='';" to always clear the field.

Tutorial Check if Number is Even/Odd

by in , 0

function isEven(value) {
	if (value%2 == 0)
		return true;
	else
		return false;
}

Tutorial Check if Function Exists Before Calling

by in , 0

When using scripts that are shared between different areas of a site, there may be cases where a function is called that doesn't exist. It makes sense on one page (the dependency is there) but not another. The difference is too slight to warrant forking the file into different versions. Instead, you can just check if the function exists before calling it to avoid the error:

if (typeof yourFunctionName == 'function') { 
  yourFunctionName(); 
}

Tutorial Check if font-family is Honored

by in , 0

function checkFont(strFamily) {
  var objDiv = document.createElement('div');

  objDiv.style.fontFamily = strFamily;
  objDiv.appendChild(document.createTextNode('FONT TEST'));

  if (window.getComputedStyle) {
      return window.getComputedStyle(objDiv, null).getPropertyValue('font-family') === strFamily;
  }

  return objDiv.currentStyle.fontFamily === strFamily;
}

Usage

var iconFontHonored = checkFont('icomoon');

Reference URL

Tutorial Call Function with Random Timer

by in , 0

function randRange(data) {
       var newTime = data[Math.floor(data.length * Math.random())];
       return newTime;
}

function toggleSomething() {
       var timeArray = new Array(200, 300, 150, 250, 2000, 3000, 1000, 1500);

       // do stuff, happens to use jQuery here (nothing else does)
       $("#box").toggleClass("visible");

       clearInterval(timer);
       timer = setInterval(toggleSomething, randRange(timeArray));
}

var timer = setInterval(toggleSomething, 1000);
// 1000 = Initial timer when the page is first loaded

View Demo

Tutorial Break Out of iframe

by in , 0

if (top.location!= self.location) {
   top.location = self.location.href;
}

That will generally work, but there is a small chance of failure in the case that window is overridden. Here's a couple of clever alternatives from Nathan Smith:

<script>

// Break out of an iframe, if someone shoves your site
// into one of those silly top-bar URL shortener things.
//
// Passing `this` and re-aliasing as `window` ensures
// that the window object hasn't been overwritten.
//
// Example:
//   var window = 'haha, punked!';
//
// Note: Probably unnecessary, but just for kicks.

(function(window) {
  if (window.location !== window.top.location) {
    window.top.location = window.location;
  }
})(this);

</script>
<script>

// A more cryptic one-liner, to awe & impress.
//
// No need to protect `window` since `this` is
// immutable, and at the topmost level means
// `window` anyways. Here, we compare locations
// on the left side of the "&&" and execute the
// code in parenthesis if that condition is
// true (top location isn't iframe location).
//
// Otherwise, nothing happens. It's basically an
// if statement without wrapping curly brackets.
//
// Weird, I know. But pretty cool, right? :)

this.top.location !== this.location && (this.top.location = this.location);

</script>

Reference URL

Tutorial Basic Alert

by in , 0

<script type="text/javascript">
       alert('ALERT!')
</script>

Tutorial Auto Select Textarea Text

by in , 0

<textarea rows="10" cols="50"  readonly="readonly">
   example text
</textarea>

Tutorial Async Sharing Buttons (G+, Facebook, Twitter)

by in , 0

Some of these services already (smartly) provide their scripts in an async fashion, this just combines them into more efficient, organized, and understandable code.

(function(doc, script) {
  var js, 
      fjs = doc.getElementsByTagName(script)[0],
      frag = doc.createDocumentFragment(),
      add = function(url, id) {
          if (doc.getElementById(id)) {return;}
          js = doc.createElement(script);
          js.src = url;
          id && (js.id = id);
          frag.appendChild( js );
      };
      
    // Google+ button
    add('http://apis.google.com/js/plusone.js');
    // Facebook SDK
    add('//connect.facebook.net/en_US/all.js#xfbml=1&appId=200103733347528', 'facebook-jssdk');
    // Twitter SDK
    add('//platform.twitter.com/widgets.js');

    fjs.parentNode.insertBefore(frag, fjs);
}(document, 'script'));

I found it going through some site code and I forget exactly who originally did it but it seems like a Nicolas Gallagher or Mathias Bynes kind of thing. Correct me if I'm wrong.

You'll need the HTML in place for the scripts to put their stuff:

<a href="https://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a>

<div class="g-plusone" data-size="medium" data-count="true"></div>

<div id="fb-root"></div>
<div class="fb-like" data-send="false" data-layout="button_count" data-width="1" data-show-faces="false" data-action="recommend"></div>

Tutorial Async Script Loader with Callback

by in , 0

var Loader = function () { }
Loader.prototype = {
    require: function (scripts, callback) {
        this.loadCount      = 0;
        this.totalRequired  = scripts.length;
        this.callback       = callback;

        for (var i = 0; i < scripts.length; i++) {
            this.writeScript(scripts[i]);
        }
    },
    loaded: function (evt) {
        this.loadCount++;

        if (this.loadCount == this.totalRequired && typeof this.callback == 'function') this.callback.call();
    },
    writeScript: function (src) {
        var self = this;
        var s = document.createElement('script');
        s.type = "text/javascript";
        s.async = true;
        s.src = src;
        s.addEventListener('load', function (e) { self.loaded(e); }, false);
        var head = document.getElementsByTagName('head')[0];
        head.appendChild(s);
    }
}

Usage

var l = new Loader();
l.require([
    "example-script-1.js",
    "example-script-2.js"], 
    function() {
        // Callback
        console.log('All Scripts Loaded');
    });

Reference URL