Funções úteis em JS para extrair dados de URLs

Existem bibliotecas bem legais para extrair dados da URL, mas às vezes você não precisa de todas aquelas informações. Para evitar que seu código fique inchado ou a importação de bibliotecas completas, pode ser interessante usar funções específicas que retornam apenas o dados que você precisa. Tem duas delas que uso com bastante frequencia:


function getHash(url)
  if (typeof url != 'string')
    return null;
  return url.replace(/^.*(#.*)$/, '$1');

Parâmetro (GET)

function getParam(url, param)
  if (typeof url != 'string' || typeof param != 'string')
  var regex = new RegExp('[\\?&]' + param + '=' + '(.+?)([&#]|$)', 'i');
  return (value = (regex.exec(window.location.href)||[,null])[1]) 
      ? decodeURIComponent(value) 
      : null;

Opening links in new window: the XHTML way

Roger Johansson said the following about using the target attribute:

The target attribute is not allowed in strict doctypes, and since you should always use a strict doctype, the target attribute is invalid.

It’s possible to use a JavaScript trick to open a link in a new window and still having a valid XHTML Strict syntax. Continue reading “Opening links in new window: the XHTML way”

JavaScript simple image resizer

Often one needs to resize images only using client-side programming. For cases like that, I’m using a technique with JavaScript. Depending on the original size and the desired final size, it may distort a little or lose quality. But in most cases, it’s still useful.

The image is resized proportionately and limited to the maximum size set in the variables maxHeight and maxWidth. Continue reading “JavaScript simple image resizer”

Auto formatting CSS code with JavaScript

The guys from Webstandards Blog have written a guide to front-end developers on writing beautiful and efficient code. Based on their idea, I write the following code with Krause. It orders and formats CSS code with the rules designed by them.

Some text editor allows you to write plugins using Javascript. This code can be useful in that context.

Notice that only properties defined in props array are ordered. Other properties are placed at the end of the rule. You can add more properties to props as you want.

Continue reading “Auto formatting CSS code with JavaScript”