Tutorial JavaScript Array Contains

by in , 0

Javascript objects are really nice, but sometimes they are missing some useful little functions/methods. The example above is with Arrays. It's really nice to know whether or not an item is contained within your array. Well you can write a function that takes the array and the item you're checking for, but it's much cleaner to add the contains( item ) method to the Array object.

Extending JavaScript Arrays

/**
 * Array.prototype.[method name] allows you to define/overwrite an objects method
 * needle is the item you are searching for
 * this is a special variable that refers to "this" instance of an Array.
 * returns true if needle is in the array, and false otherwise
 */
Array.prototype.contains = function ( needle ) {
   for (i in this) {
       if (this[i] == needle) return true;
   }
   return false;
}

Usage

// Now you can do things like:
var x = Array();
if (x.contains('foo')) {
   // do something special
}

Tutorial Intervals

by in , 0

Standard

You don't need to create the variable, but it's a good practice as you can use that variable with clearInterval to stop the currently running interval.

var int = setInterval("doSomething()", 5000 ); /* 5 seconds */
var int = setInterval(doSomething, 5000 ); /* same thing, no quotes, no parens */

If you need to pass parameters to the doSomething function, you can pass them as additional parameters beyond the first two to setInterval.

Without overlapping

setInterval, as above, will run every 5 seconds (or whatever you set it to) no matter what. Even if the function doSomething takes long than 5 seconds to run. That can create issues. If you just want to make sure there is that pause in between runnings of doSomething, you can do this:

(function(){

   doSomething();

   setTimeout(arguments.callee, 5000);

})()

Reference URL

Tutorial Input with Disappearing Background Image

by in , 0

This replicates the functionality of the standard embeddable Google Search fields. They have an image in the background and when the input is clicked into, the image disappears.

<form name="searchform" id="search-form">
   <div>
       <b>Search</b>
       <input type="text" name="txtInput" title="Enter the terms you wish to search for." />
       <input type="submit" value="GO!" class="submit" style="cursor: pointer;" />
   </div>
</form>

JavaScript underneath form markup:

<script type="text/javascript" language="javascript">
 (function() {
    var id = document.getElementById('search-form');
    if (id && id.txtInput) {
      var name = id.txtInput;
      var unclicked = function() {
          if (name.value == '') {
              name.style.background = '#FFFFFF url(images/googbg.png) left no-repeat';
          }
       };
       var clicked = function() {
          name.style.background = '#ffffff';
       };
    name.onfocus = clicked;
    name.onblur = unclicked;
    unclicked();
    }
  })();
</script>

View Demo

Tutorial Inject New CSS Rules

by in , 0

If you need to change the style of an element with JavaScript, it's typically better to change a class name and have the CSS already on the page take effect and change the style. However, there are exceptions to every rule. For instance, you might want to programmatically change the a pseudo class (e.g. :hover). You can't do that through JavaScript for the same reason inline style="" attributes can't change pseudo classes.

You'll need to inject a new <style> element onto the page with the correct styles in it. Best to inject it at the bottom of the page so it overrides your CSS above it. Easy with jQuery:

function injectStyles(rule) {
  var div = $("<div />", {
    html: '&shy;<style>' + rule + '</style>'
  }).appendTo("body");    
}

Usage

injectStyles('a:hover { color: red; }');

Demo

More Information

Style injection quirks in IE (Ryan Seddon). Stack Overflow thread.

Tutorial htmlEntities for JavaScript

by in , 0

htmlentities() is a PHP function which converts special characters (like <) into their escaped/encoded values (like &lt;). This allows you to show to display the string without the browser reading it as HTML.

JavaScript doesn't have a native version of it. If you just need the very basics to so that the browser won't interpret as HTML, this should work fine (via James Padolsey and I got a a similar idea from David Walsh).

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

The PHP.js project, which is a project to port over all of PHP's native functions to JavaScript, contains an example as well. I tried it and it works, but I've been warned much of the code from that project is poorly written, so I've kept it simple and used the above.

Tutorial Global Variables

by in , 0

Declare variable outside of the function...

var oneVariable;

function setVariable(){
    oneVariable = "Variable set from within a function!";
}

function getVariable(){
    alert(oneVariable); // Outputs "Variable set from within a function!"
}

Or... attach it to the window object

function setValue() {
    window.myValue = "test";
}

function getValue() {
    alert(window.myValue); // "test" (assuming setValue has run)
}

Tutorial Get YouTube Key from a Link

by in , 0

// Example link:
// <a id="myLink" href="http://www.youtube.com/watch?v=cyRqR56aCKc&feature=PlayList&p=00000000000&index=0&playnext=1">Youtube link</a>

var youtubeLink = document.getElementById('myLink').href;
var youtubeVideoKey = youtubeLink.substr(youtubeLink.lastIndexOf("v=") + 2, 11);

// youtubeVideoKey will return "cyRqR56aCKc"