28 January 2011

Some Useful JavaScript Snippets


1. Close Window
< form>
< input onclick="javascript:window.close();" type="button" value="Close Window" />< /form>


2. Add to Favorites
< a href="javascript:window.external.AddFavorite('http://www.skills2earn.com', 'skills2earn')">Add to Favorites< /a>

3. To prevent your page being framed by someone else put this event handler into the body tag.
< body onLoad="if (self != top) top.location = self.location">

4. Pop up window
< HTML>
< HEAD>
< TITLE> A Window< /TITLE>
< SCRIPT>

function open_window(url) {
mywin = window.open(url,"win",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=520,height=350');
}

< /SCRIPT>
< /HEAD>

< BODY>

< A HREF = "javascript:open_window('page1.html')">
< IMG SRC ="image.gif">
< /A>

< A HREF = "javascript:open_window('page2.html')">
< IMG SRC ="image.gif">
< /A>

< /BODY>
< /HTML>

5. Determine if Browser Understands HTML5 Video
// Check if the browser understands the video element.
function understands_video() {
return !!document.createElement('video').canPlayType; // boolean
}

if ( !understands_video() ) {
// Must be older browser or IE.
// Maybe do something like hide custom
// HTML5 controls. Or whatever...
videoControls.style.display = 'none';
}

6. Delayed Redirect
setTimeout( "window.location.href =
'http://walkerwines.com.au/'", 5*1000 );

7. Email Validation
< script language="JavaScript1.2">
var testresults
function checkemail(){
var str=document.validation.emailcheck.value
var filter=/^.+@.+\..{2,3}$/

if (filter.test(str))
testresults=true
else {
alert("Please input a valid email address!")
testresults=false
}
return (testresults)
}
< /script>
< script>
function checkbae(){
if (document.layers||document.all)
return checkemail()
else
return true
}
< /script>

8. Select All
< script language="Javascript">

function selectAll(theField) {
  var tempval=eval("document."+theField)
  tempval.focus()
  tempval.select()
}

< /script>

No comments: