Category Archives: javascript

fading image using javascript

Show me what it does!


HideShow

Click on a link above to make the image disappear and re-appear by gradually fading in/out. It uses CSS transparency, in CSS you can set the transparency in different ways. To ensure that it works on most browsers we use all three.

  • opacity: 0.5;
    This one is the official CSS3 method, at the moment it works in newer Mozilla (Gecko) browers, Safari and Opera.
  • -moz-opacity: 0.5;
    This one works in older versions of Mozilla browsers.
  • -khtml-opacity: 0.5;
    This is used by older versions of browsers that use the KHTML and WebKit rendering engine, namely Konquerer on Linux and Safari on Mac OS X.
  • filter: alpha(opacity=50);
    This one works only in MSIE.

MSIE warning

This trick however doesn’t work with MSIE all the time. For example, it won’t work unless it has a specified width and/or height. Yes, that’s weird. MSIE sucks. Normal browsers like Mozilla will do it right.


This <div> has a can be made transparent in MSIE, it has a specified width of 300px.

0%50%100%


This <div> has no specified width, transparency doesn’t work in MSIE.

0%50%100%

Mozilla warning

No browser is perfect, Mozilla (latest version at the time of writing is 1.6) has a few bugs too.

JavaScript fun

OK, here is the real work being done. This JavaScript has two separate functions. The first one, opacity() is called first, it sets the timer and speed.

Then the if() looks whether opacStart is larger then opacEnd, if so, the Opacity will go backwards, else, it will go forward.

setTimeOut() will cause a short delay before calling changeOpac() so that we can actually see the fading effect.

The function changeOpac() does nothing more than setting the 3 different opacity styles for the appropriate element. Notice that you can’t use dashes (-) in style names in JavaScript, instead you must use a CAPITAL letter. In this example you can see changing -moz-opacity changing into MozOpacity, the same thing applies to all styles that contain dashes.

function opacity(id, opacStart, opacEnd, millisec) {
//speed for each frame
var speed = Math.round(millisec / 100);
var
timer = 0;

//determine the direction for the blending, if start and end are the same nothing happens
if(opacStart > opacEnd) {
for(
i = opacStart; i >= opacEnd; i–) {
setTimeout(“changeOpac(” + i + “,’” + id + “‘)”,(timer * speed));
timer++;
}
} else if(
opacStart < opacEnd) {
for(
i = opacStart; i <= opacEnd; i++)
{
setTimeout(“changeOpac(” + i + “,’” + id + “‘)”,(timer * speed));
timer++;
}
}
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
var
object = document.getElementById(id).style;
object.opacity = (opacity / 100);
object.MozOpacity = (opacity / 100);
object.KhtmlOpacity = (opacity / 100);
object.filter = “alpha(opacity=” + opacity + “)”;
}

Fade in/out with only one link

There is more that can be done! What about a single link to hide and show an element?


hide/show

<a href="javascript:shiftOpacity('digicam2', 1000)">show/hide</a>

It’s easy! With only a tiny bit of JavaScript! We’ll make another function named shiftOpacity(). It only requires two parameters:

  • The element’s ID
  • The duration of the transition in milliseconds.

This function does nothing more than checking whether the element is transparent and then calls the function opacity() to do the transition. This is what it looks like:

function shiftOpacity(id, millisec) {
//if an element is invisible, make it visible, else make it ivisible
if(document.getElementById(id).style.opacity == 0) {
opacity(id, 0, 100, millisec);
} else {
opacity(id, 100, 0, millisec);
}
}

source: http://brainerror.net/scripts/javascript/blendtrans/





javascript form validation

validateEmpty ( )

The function below checks if a required field has been left empty. If the required field is blank, we return the error string to the main function. If it’s not blank, the function returns an empty string.

function validateEmpty(fld) {
var error = “”;

if (fld.value.length == 0) {
fld.style.background = ‘Yellow’;
error = “The required field has not been filled in.\n”
} else {
fld.style.background = ‘White’;
}
return error;
}

validateUsername ( )The function below checks if the user entered anything at all in the username field. If it’s not blank, we check the length of the string and permit only usernames that are between 5 and 15 characters. Next, we use the JavaScript regular expression /\W/ to forbid illegal characters from appearing in usernames. We want to allow only letters, numbers and underscopes.

function validateUsername(fld) {
var error = “”;
var illegalChars = /\W/; // allow letters, numbers, and underscores

if (fld.value == “”) {
fld.style.background = ‘Yellow’;
error = “You didn’t enter a username.\n”;
} else if ((fld.value.length < 5) || (fld.value.length > 15)) {
fld.style.background = ‘Yellow’;
error = “The username is the wrong length.\n”;
} else if (illegalChars.test(fld.value)) {
fld.style.background = ‘Yellow’;
error = “The username contains illegal characters.\n”;
} else {
fld.style.background = ‘White’;
}
return error;
}

validatePassword ( )The function below checks the password field for blankness and allow only letters and numbers – no underscopes this time. So we should use a new regular expression to forbid underscopes. This one /[\W_]/ allow only letters and numbers. Next, we want to permit only passwords that contain letters and at least one numeral. For that we use the seacrh() method and two more regular expressions: /(a-z)+/ and /(0-9)/.

function validatePassword(fld) {
var error = “”;
var illegalChars = /[\W_]/; // allow only letters and numbers

if (fld.value == “”) {
fld.style.background = ‘Yellow’;
error = “You didn’t enter a password.\n”;
} else if ((fld.value.length < 7) || (fld.value.length > 15)) {
error = “The password is the wrong length. \n”;
fld.style.background = ‘Yellow’;
} else if (illegalChars.test(fld.value)) {
error = “The password contains illegal characters.\n”;
fld.style.background = ‘Yellow’;
} else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
error = “The password must contain at least one numeral.\n”;
fld.style.background = ‘Yellow’;
} else {
fld.style.background = ‘White’;
}
return error;
}

validateEmail ( )Next we want to see if the email address the user entered is real. This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign.At first we check if the user entered anything at all in the email field. Next, we use regular expression and the test() method to check the field for a compliance. Also we will use trim() function that will trim leading whitespace off the string. This won’t be perfect validation — it is possible to slip not compliant addresses by it — but it’s normally good enough.
function trim(s)
{
return s.replace(/^\s+|\s+$/, ”);
}

function validateEmail(fld) {
var error=”";
var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

if (fld.value == “”) {
fld.style.background = ‘Yellow’;
error = “You didn’t enter an email address.\n”;
} else if (!emailFilter.test(tfld)) {              //test email for illegal characters
fld.style.background = ‘Yellow’;
error = “Please enter a valid email address.\n”;
} else if (fld.value.match(illegalChars)) {
fld.style.background = ‘Yellow’;
error = “The email address contains illegal characters.\n”;
} else {
fld.style.background = ‘White’;
}
return error;

}
validatePhone ( )The function below checks if the phone number is valid. At first we use regular expression and the replace() method to clear out any spacer characters. Next, we use the isNaN() function to check if the phone number contain only numbers. At last we check the length of the string and permit only phone numbers with 10 digits.

function validatePhone(fld) {
var error = “”;
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, ”);

if (fld.value == “”) {
error = “You didn’t enter a phone number.\n”;
fld.style.background = ‘Yellow’;
} else if (isNaN(parseInt(stripped))) {
error = “The phone number contains illegal characters.\n”;
fld.style.background = ‘Yellow’;
} else if (!(stripped.length == 10)) {
error = “The phone number is the wrong length. Make sure you included an area code.\n”;
fld.style.background = ‘Yellow’;
}
return error;
}

source: http://www.webcheatsheet.com/javascript/form_validation.php





javascript: escape()

Problem: Getting error on ajax when passing url with “&” on it.
Solution: escape()

Definition and Usage

The escape() function encodes a string, so it can be read on all computers.

Syntax

escape(string)
Parameter Description
string Required. The string to be encoded

Tips and Notes

Note: The escape() function encodes special characters, with the exception of:
* @ – _ + . /

Tip: Use the unescape() function to decode strings encoded with escape().

Note: The escape() and unescape() functions should not be used to encode or decode URIs. Use encodeURI() and decodeURI() functions instead!


Example

In this example we use escape() to encode strings:

<script type=”text/javascript”>

document.write(escape(“Visit W3Schools!”) + “<br />”);
document.write(escape(“?!=()#%&”));

</script>

The output of the code above will be:

Visit%20W3Schools%21
%3F%21%3D%28%29%23%25%26

source: http://www.w3schools.com/jsref/jsref_escape.asp

javascript: test()

Definition and Usage

The test() method is used to search for a match of a regular expression in a string.

This method returns true if a match is found, and false if not.

Syntax

RegExpObject.test(string)
Parameter Description
RegExpObject Required. The regular expression to use
string Required. The string to search

Example

In the following example we will search for “W3Schools”:

<script type="text/javascript">
var str = "Visit W3Schools";
var patt1 = new RegExp("W3Schools");
var result = patt1.test(str);
document.write("Result: " + result);
</script>
source: http://www.w3schools.com/jsref/jsref_test_regexp.asp

multi level menu js less

Meet the markup

To start, we should use the best method for defining a navigation menu — a list. For this example, we will work on a simple HTML unordered list. {Line wraps are marked ». –Ed.}

<ul>
  <li>Sunfishes
    <ul>
      <li><a href="">Blackbanded»
        sunfish</a></li>
      <li><a href="">Shadow bass</a></li>
      <li><a href="">Ozark bass</a></li>
      <li><a href="">White crappie</a></li>
		</ul>
	</li>

  <li>Grunts
    <ul>
      <li><a href="">Smallmouth grunt
        </a></li>
      <li><a href="">Burrito</a></li>
      <li><a href="">Pigfish</a></li>
    </ul>
  </li>

  <li>Remoras
    <ul>
      <li><a href="">Whalesucker</a></li>
      <li><a href="">Marlinsucker</a></li>
      <li><a href="">Ceylonese remora</a></li>
      <li><a href="">Spearfish remora</a></li>
      <li><a href="">Slender suckerfish</a></li>
    </ul>
  </li>
</ul>

Quite straightforward really — nice and neat HTML that, as a result, is highly accessible. But now we want to transform this into a dynamic list — the first level of list items will make up a horizontal menu bar from which the second level lists will drop down.

Continue reading