Getting CSS pseudo-element properties by Javascript

You probably wonder if you can access CSS pseudo-element's (like ::before or :: after) properties by Javascript.

The answer is yes, you can, but it's tricky :)

Let's assume you have following HTML/CSS


<p id="myid">some content</p>



#myid::after {
  display:block;
  width: 100px;
  height: 40px;
  color: blue;
  content: "Hello world";
}
#myid {
  color: red;
}


Apparently, "#myid::after" is not in the DOM tree, but following trick will allow you to get its properties:


var color = window.getComputedStyle(document.querySelector('#myid'), ':after').getPropertyValue('color')
var content = window.getComputedStyle(document.querySelector('#myid'), ':after').getPropertyValue('content')
console.log(color, content) // outputs the color and content of the pseudo-element

You might find it useful in test automation or some UI interaction manipulation.

URL parsing using native JS engine approach

The snippet bellow can come in handy when you need basic URL parsing


/**
 * @description URL parsing using native JS engine approach
 * @param {string} url - URL string
 * @returns {object} parsed data
 */

function parseURL(url) {
	var parser = document.createElement('a');
	parser.href = url;
	return {
		protocol : parser.protocol, // => "http:"
		hostname : parser.hostname, // => "domain.com"
		port : parser.port, // => "8000"
		pathname : parser.pathname, // => "/path/"
		search : parser.search, // => "?search=test"
		hash : parser.hash, // => "#hash"
		host : parser.host // => "domain.com:8000"
	}
}

console.dir(parseURL("http://domain.com:8000/path/?search=test&bar=1&bar=2&key1=val1#hash"));

Really crazy Javascript's Fibonacci implementation

Run it in console and see it's really working :)


  var fib = function (_) {
      for(_=[+[],++[[]][+[]],+[],_],_[++[++[++[[]][+[]]][+[]]][+[]]]=(((_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]]))&(((--[[]][+[]])>>>(++[[]][+[]]))))===(_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]])))?(_[++[++[[]][+[]]][+[]]]=++[[]][+[]],_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]])):+[];_[++[++[++[[]][+[]]][+[]]][+[]]]--;_[+[]]=(_[++[[]][+[]]]=_[++[++[[]][+[]]][+[]]]=_[+[]]+_[++[[]][+[]]])-_[+[]]);
      return _[++[++[[]][+[]]][+[]]];
  }

  console.assert(fib(-1) === 0);
  console.assert(fib(0) === 0);
  console.assert(fib(1) === 1);
  console.assert(fib(2) === 1);
  console.assert(fib(3) === 2);
  console.assert(fib(4) === 3);
  console.assert(fib(5) === 5);
  console.assert(fib(6) === 8);
  console.assert(fib(7) === 13);
  console.assert(fib(32) === 2178309);
  console.assert(fib(46) === 1836311903);
  console.assert(fib(47) === 2971215073);
  console.assert(fib(63) === 6557470319842);

  console.log('done!');


More could be found at: wtfsjs

Twisted logic: understanding truthy and falsy

An upcoming article I'll be doing for Smashing Magazine will look at the oddities and gotchas of Javascript — and lordie does it have a few.

One of these is the concept of truthy and falsy. These are sort of like true/false-lite, which will anger you somewhat if you majored in logic or philosophy. You mean you didn't know true and false were in fact gradable, not absolute concepts!?

In Javascript, every value has an in-built flag denoting its boolean equivalent. This is called upon when you ask the value to behave like a boolean, e.g. by comparing it to a real boolean. Javascript coerces your value into a boolean, such that the comparison is possible (after all, you can't compare apples with pears). See below for more on data coercion. So:

var someVar = 0;
alert(someVar == false); //evaluates true

Since we are attempting to compare zero to a boolean, Javascript coerces the zero to its truthy/falsy equivalent — and zero is a falsy (along with null, undefined, NaN, empty strings and false — everything else is a truthy). So the expression effectively becomes:

alert(false == false); //evaluates true, of course


It's important to realise that this does not mean your value is a boolean — it simply means Javascript temporarily converts it to a boolean to make the comparison possible. If we did the same comparison with the === operator (which compares not only by value but also by type), the result would be different:

alert(someVar === false); //evaluates false - someVar is a number, not a legitimate boolean


It gets worse

Clear enough? It gets more complex.

A well known quirk of Javascript is that an empty array appears to be equal to false.


( Read more )

Simple example how-to extend JavaScript built-in methods

Let say you want to replace all spaces in string by dashes,
of course you can implement distinct function that does it:



 function ReplaceByDashes(string){
    return string.replace(/\s/g,'-');
 }

 // run it
 var string = "Hello my beautiful world!";
 string=ReplaceByDashes(string);
 alert(string); 



However, we can add our custom method to string object that already built-in in JavaScript:



  if(typeof String.prototype.rbd==='undefined'){ // we have to check if someone hasn't added it already
     String.prototype.rbd = function(){
        return this.replace(/\s/g,'-');
     }
  }

 // run it

 var string = "Hello my beautiful world!";
 string=string.rbd();
 alert(string); 



Some useful example, capitalize first letter of string



String.prototype.ucFirst = function () {
  return (this.substr(0,1).toUpperCase() + this.substr(1,this.length));
}

print_r for Javascript


function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}