~ overflow ~

Tag: javascript

label for=”id” don’t work on IE

by z3n on Sep.27, 2010, under Coding, Tips & Hints

Problem:

<input type='radio' value='x' id='something_1' name='something'>
<label for='something_1'>cool label</label>

When user clicks on the label radio should be selected, this only happens on firefox.

Solution:

$("label").click(function(){
	if ($(this).attr("for") != "")
		$("#" + $(this).attr("for")).click();
});

More info on this issue:

Stackoverflow posting

Leave a Comment :, , , , , more...

jQuery Validator scrollTo snippet

by z3n on Sep.26, 2010, under Coding, Tips & Hints

Problem:

How to automatically scroll to the first wrong input on a long form validated using jquery validator?

Solution:

invalidHandler: function(form,validator) {
	if (validator.numberOfInvalids())
		setTimeout(function(){
			$.scrollTo($("form_id").(":input.error:first"), 500);
		},250);
}
Leave a Comment :, , , more...

MarkItUp set em português (pt-br)

by z3n on Jul.10, 2010, under Coding, Tips & Hints

Variáveis de markitup em português com youtube

markitup_bbcode = {
  nameSpace:          "bbcode", // Useful to prevent multi-instances CSS conflict
  previewParserPath:  "~/sets/bbcode/preview.php",
  markupSet: [
      {name:'Negrito', key:'B', openWith:'[b]', closeWith:'[/b]'},
      {name:'Italico', key:'I', openWith:'[i]', closeWith:'[/i]'},
      {name:'Sublinhado', key:'U', openWith:'[u]', closeWith:'[/u]'},
      {separator:'---------------' },
      {name:'Imagem', key:'P', replaceWith:'[img][![Url]!][/img]'},
      {name:'YouTube', key:'Y', openWith:'[youtube]', closeWith:'[/youtube]', placeHolder:'[![Url do YouTube]!]'},
      {name:'Link', key:'L', openWith:'[url=[![Url]!]]', closeWith:'[/url]', placeHolder:'Coloque o texto do link aqui...'},
      {separator:'---------------' },
      {name:'Cores', openWith:'[color=[![Cor]!]]', closeWith:'[/color]', dropMenu: [
          {name:'Amarelo', openWith:'[color=yellow]', closeWith:'[/color]', className:"col1-1" },
          {name:'Laranja', openWith:'[color=orange]', closeWith:'[/color]', className:"col1-2" },
          {name:'Vermelho', openWith:'[color=red]', closeWith:'[/color]', className:"col1-3" },
          {name:'Azul', openWith:'[color=blue]', closeWith:'[/color]', className:"col2-1" },
          {name:'Roxo', openWith:'[color=purple]', closeWith:'[/color]', className:"col2-2" },
          {name:'Verde', openWith:'[color=green]', closeWith:'[/color]', className:"col2-3" },
          {name:'Branco', openWith:'[color=white]', closeWith:'[/color]', className:"col3-1" },
          {name:'Cinza', openWith:'[color=gray]', closeWith:'[/color]', className:"col3-2" },
          {name:'Preto', openWith:'[color=black]', closeWith:'[/color]', className:"col3-3" }
      ]},
      {name:'Tamanho', key:'S', openWith:'[size=[![Tamanho do texto]!]]', closeWith:'[/size]', dropMenu :[
          {name:'Grande', openWith:'[size=200]', closeWith:'[/size]' },
          {name:'Normal', openWith:'[size=100]', closeWith:'[/size]' },
          {name:'Pequeno', openWith:'[size=50]', closeWith:'[/size]' }
      ]},
      {separator:'---------------' },
      {name:'Quotes', openWith:'[quote]', closeWith:'[/quote]'},
      {separator:'---------------' },
      {name:'Limpar', className:"clean", replaceWith:function(h) { return h.selection.replace(/\[(.*?)\]/g, "") } }
   ]
};
Leave a Comment :, , , more...

JQuery validator method for twitter

by z3n on Jul.07, 2010, under Coding, Tips & Hints

Problem:

How to validate twitter @your_crap_name using jQuery’s validator plugin?

Solution:

jQuery.validator.addMethod("twitter", function(twitter, element) {
	return this.optional(element) || twitter.match(/^@+\b[A-Z0-9._%-]+\b/i);
}, "Twitter inválido");
Leave a Comment :, , , more...

JSLint php class

by z3n on Jul.07, 2010, under Coding, Tips & Hints

Problem:

How to lint check a javascript using php?

Solution:

// (c) z3n - R1V1@100707 - www.overflow.biz - rodrigo.orph@gmail.com
// Based on the original by Matthias Miller (http://www.JavaScriptLint.com/)

class JSLEngine {
	private $_binarypath;							// jlint exec
	private $_confpath;								// config path
	private $fn;											// temp filename (not used outside class)
	private $r;												// jlint output
	private $has_errors=0;						// error flag

	public function __construct($binarypath="", $confpath="") {

		// default paths
		base_defines(array(
			"jslint_binary_path" => _fn_fix(dirname(dirname(dirname(__FILE__)))."/3rd/jsl-0.3.0/jsl.exe"),
			"jslint_conf_path" => _fn_fix(dirname(dirname(dirname(__FILE__)))."/3rd/jsl-0.3.0/jsl.default.conf")
		));

		// startup
	  $this->_binarypath = $binarypath == "" ? jslint_binary_path : $binarypath;
	  $this->_confpath = $confpath == "" ? jslint_conf_path : $confpath;
	}

	public function __destruct() {
		if ($this->fn != null && file_exists($this->fn))
			unlink($this->fn);
	}

	/* returns error on failure; returns true on success */
	public function Lint($code) {
	  if (!$this->_launchLintBinary($code, $output))
	      die('The JavaScript Lint online service is currently unavailable.');

	  // store lint
	  $this->r=$output;
	  $output=explode("\n",$output); // break lines
	  $x=$output[count($output)-2]; // X error(s), X warning(s) (total lines -2)
	  $x=trim(substr($x,0,strpos($x," ")));
	  if ($x > 0) { // has errors
	  	$this->has_errors=1;
	  	return false;
	  } else { // clean
	  	$this->has_errors=0;
	  	return true;
	  }
	}

	/* assumes path and that SERVER_SOFTWARE env is set */
	private function _launchLintBinary($input, &$output) {
    $descriptorspec = array(
        0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
        1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
        2 => array("pipe", "w")
    );

    $this->fn=_fn_fix(dirname(__FILE__).'/tmp.js');

    file_put_contents($this->fn,$input);
    /* launch process */
    $path = PHP_OS == "WINNT" ? $this->_binarypath : escapeshellcmd($this->_binarypath);
    $path.= ' --nologo --conf '.escapeshellarg($this->_confpath).' --process '.escapeshellarg($this->fn);

    $process = proc_open($path, $descriptorspec, $pipes);
    if (!is_resource($process))
        return false;

    $output = '';
    while (!feof($pipes[1]))
       $output .= fgets($pipes[1], 1024);
    fclose($pipes[1]);
    fclose($pipes[2]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);
    return true;
	}

	public function output() {
		return $this->r;
	}
}

Helper functions:


function _fn_fix($fn,$force="") { // v1.02
	if (strpos($fn,"://") === false) {
		if ((PHP_OS == "WINNT" && $force == "") || $force == "WINNT")
			$fn=str_replace("/","\\",$fn);
		else
			$fn=str_replace("\\","/",$fn);
	}
	if (strpos($fn,":/") !== false && strpos($fn,"://") === false)
		$fn=substr($fn,2);

	return $fn;
}

function base_defines($x) { // define default
	foreach ($x as $k => $v) {
		if (!defined($k)) {
			define($k,$v);
		}
	}
}

Usage:

$lint=new JSLEngine();
if (!$lint->Lint($js)) {
    echo "bad js code! full output:\n";
    echo $lint->output();
}

Required:

jslint binaries from http://www.JavaScriptLint.com/

Make sure you set the default path on the __construct, so you don’t need to keep setting it on every call.

Leave a Comment :, , , , , more...

jQuery validator validate a single field

by z3n on Jul.06, 2010, under Coding, Tips & Hints

Problem:

How to programatically validade a single non keyup field with jquery validator?

Solution:

$("input[name=YOUR_FIELD_NAME]").valid()
Leave a Comment :, , , , more...

Javascript ParseInt Vs. ParseFloat

by z3n on May.01, 2010, under Coding, Tips & Hints

Problem:

While debbuging an javascript application i found out a wrong calculation result.

Solution:

Apparently javascript been developed my microsoft, due the extensive issues with many misbehaviors it’s quite sad to find out that there’s no way to escape from them.

var test="08";

alert(parseInt(test)+1); // will return 1
alert(parseFloat(test)+1); // will return 9, as supposed to
Leave a Comment :, , , , more...

Javascript Const Note

by z3n on Apr.13, 2010, under Notes

In order to keep my code clean i wrote a javascript with const variable declarations, those were constants anyway and there were no reason to declare them as var, right?

Wrong, big mistake, IE don’t support consts right, turns out it gives javascripts errors (on the wrong position, of course), i will not even go deep into this, cuz it will just turn into more shit, so i’m just replacing const per var;

So, note to self, never use consts on javascript.

Leave a Comment :, , , more...

Javascript Floating Point Issues

by z3n on Apr.01, 2010, under Coding, Tips & Hints

Problem:

Javascript floating point issues.

Solution:

It’s well known that javascript has major issues when it comes to precision math, even the simplest operations tend to be a nightmare. Although i was aware of that i suddenly found myself into another tricky thing with zeros on the left (eg: 025).

To avoid issues with javascript rounding issues I get all numbers converted to strings, stripping their floating point, this only works if all numbers are from the same precision or if you do a function do that, since there’s no rounding function (besides .toFixed) that does that proprietly.

So, in sum, 1.23 will be calculated as 123, eg:

var a = 1.23;
var b = 4.56;
a = parseInt(a.toString().replace(/\./g,"")); // 1.23 -> 123
b = parseInt(b.toString().replace(/\./g,"")); // 4.56 -> 4.56
var x = a + b; // = 579
x=x.toString();
return x.substr(0,x.length-2)+"."+x.substr(x.length-2);

Now that’s good, right…?? Apparently yes, but let’s do another example:

var a= 0.25;
a = parseInt(a.toString().replace(/\./g,"")); // 0.25 -> 025
var x = 1*a; // 1* 025 = 025  -- right? js will return 021
return x.substr(0,x.length-2)+"."+x.substr(x.length-2);

When there’s a zero on the left, javascript goes nuts. An easy fix would be:

while (x.toString().substr(0,1) == "0")
    x=x.substr(1);

and problem solved!

References:

w3Schools

webmasterworld

jibbering

Leave a Comment :, , , , more...

packable qTip

by z3n on Mar.19, 2010, under Coding, Tips & Hints

Problem:

I was looking around and found this great jQuery plugin, qTip, i added to my auto packer javascript script and then it didn’t worked at all.

Reading further on their site i found out that they have a YUI compressed version which is not what i need.

Solution:

After hunting a lot of missing ; and extra ;, i’ve got a working packable version.

download here

Leave a Comment :, , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!