Archive for the ‘JavaScript’ Category.

JavaScript Tween function

This is a function I wrote to use for creating advanced easing effects without using JQuery, MooTools or other JS libraries.

The function can be called as follows:
tween(element, property, from, to, duration, [optional] function)
Parameters
element: The id of the HTML element you want to animate

property: The CSS property that you want to animate

from: The initial value (like [...]

JavaScript round float to n decimal points

The best you can do with built in JavaScript functions is to round a number to the nearest integer using the method Math.round(x), so to round a float to n decimal points we need to come up with our own function.

The function round_float() rounds a floating point number x to n decimals, if you ommit [...]

setAttribute/getAttribute(“style”) crossbrowser alternative

The JavaScript methods setAttribute and getAttribute are very handy when you are designing dynamic effects for your website, but those methods have a lot of bugs in IE (6 an 7 at least), I use these two crossbrowser functions as alternatives instead of using directly setAttribute() and getAttribute(), I’ve been using them for quite a [...]

Print HTML code from JavaScript variable

This also was about to drive me crazy so I will not let it go without writing about it..

Let’s say you have some long HTML code contained on a PHP variable, something like this

<?php

# define the $html variable using the
# Nowdoc syntax to avoid parsing

$html = <<<’HTML’
<div id=”box”>
<h1>Title</h1>
<p>Article contents + comments</p>
</div>
HTML;

# [...]

A note on JavaScript arrays creation & initialization

I use PHP a lot in my projects and it happens that sometimes I combine PHP with another language and write completely useless code.

PHP arrays can be created and initialized with like this:

<?php
$cities[] = “mecca”;
$cities[] = “medina”;
?>

I thought that the same would apply to javascript… Yes, it can work, but only [...]

Generate passwords with JavaScript

The function generatePassword() is a simple yet customizable function that generates a random password string, the default password length is 6, you can override it by calling the function like thisĀ  generatePassword(n) where n is the password length. The possible characters are defined within the function with the variable chars

function generatePassword(len){
len = parseInt(len);
if(!len)
len = 6;
var password [...]

Generate a negative random number using JavaScript

Ok, so you already know how to generate positive rondom numbers but let’s do it again:

To generate a random number varying from 0 to 9 we will use this code:
var randomN = Math.floor(Math.random()*10)
This expression on the right

produces a random number from 0 to 1 (excluding 1, say 0.917) with Math.random()
multiplies it by 10 (9.71)
removes decimals [...]