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"

Tutorial Get URL Variables

by in , 0

function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

Usage

Example URL:

http://www.example.com/index.php?id=1&image=awesome.jpg

Calling getQueryVariable("id") - would return "1".
Calling getQueryVariable("image") - would return "awesome.jpg".

Tutorial Get URL and URL Parts in JavaScript

by in , 0

JavaScript can access the current URL in parts. For this URL:

http://css-tricks.com/example/index.html

window.location.protocol = "http" window.location.host = "css-tricks.com" window.location.pathname = "example/index.html"

So to get the full URL path in JavaScript:

var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;

If you need to breath up the pathname, for example a URL like http://css-tricks.com/blah/blah/blah/index.html, you can split the string on "/" characters

var pathArray = window.location.pathname.split( '/' );

Then access the different parts by the parts of the array, like

var secondLevelLocation = pathArray[0];

To put that pathname back together, you can stitch together the array and put the "/"'s back in:

var newPathname = "";
for ( i = 0; i < pathArray.length; i++ ) {
  newPathname += "/";
  newPathname += pathArray[i];
}

Tutorial Get Object Size

by in , 0

As in, the number of keys.

function objectSize(the_object) {
  /* function to validate the existence of each key in the object to get the number of valid keys. */
  var object_size = 0;
  for (key in the_object){
    if (the_object.hasOwnProperty(key)) {
      object_size++;
    }
  }
  return object_size;
}

Usage

// Arbitrary object
var something = {
  dog: "cat",
  cat: "dog"
}

console.log(objectSize(something));
// Logs: 2