Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, 30 May 2014

jQuery window.load() vs document.ready()

 
$(window).load(function () {

vs 

$(function() {
$( document ).ready(function() {


ready() executes when the DOM is fully loaded (see http://api.jquery.com/ready/).  
load() Executes always later than ready() when all the content (images, css, etc) has been loaded

Had problem when showing a confirmation dialog when the page was rendered; images where not loaded!

Thursday, 16 February 2012

Javascript:events: onbeforeunload event

Usage: When closing the tab/browser the onbeforeunload event is triggered. We can confirm the exit or abort it.
<html>
<head>

<script type="text/javascript">
window.onbeforeunload = function() {
  return "dummy string; it won't appear to user...";
}
</script>


</head>


<body>

<p>When closing the tab/browser the onbeforeunload event
is triggered...close the tab/browser....</p>


</body>

</html>

Monday, 13 February 2012

jQuery: check if a variable is defined

if($('#foo').length > 0) { alert("id 'foo' exists!"); } else { alert("id 'foo' doesn't exist!"); }

References

See also how to do the same with Javascript.

Javascript: check if a variable is defined

var foo = 1; //variable exists

if(! typeof foo == 'undefined') {
  alert("var 'foo' exists!");
}
else {
  alert("var 'foo' doesn't ex
ist!"); }

References

See also how to do the same with jQuery.

Wednesday, 18 January 2012

Javascript: How to reload current page


// tested
window.location.reload();

// not tested
history.go(0);
window.location.href=window.location.href;

References

http://www.mediacollege.com/internet/javascript/page/reload.html

Monday, 16 January 2012

Javascript: How to delete all children elements of a DOM element

HTML:

<div id="foo">
 ...
</div>

Javascript:

var foo = document.getElementById('foo');
if (!foo) alert('Element with id "foo" not found!');

while (foo.firstChild) {
  foo.removeChild(foo.firstChild);
}

The proper way to use Javascript in HTML

Goal: We want browsers not supporting Javascript to ignore the script statemantes.

1. Javascript in HTML

<script type="text/javascript">
<!--
...
//-->
</script>

2. Javascript in XHTML

<script type="text/javascript">
<!--//--><![CDATA[//><!--
...
//--><!]]>
</script>

3. Works everywhere!

<script src="foo.js" type="text/javascript"></script>

Thursday, 12 January 2012

Javascript

function randomRange(min,max){
  return Math.random()*(max-min) + min;
}

Friday, 22 April 2011

Print current date in Javascript


var today = new Date();
var msg = "This is JavaScript saying it’s now " + today.toLocaleString();
alert(msg);


output:
Tuesday, June 16, 2009. 3:12:56 AM

Go to Top of the Page (JavaScript)


Useful when clickign a submit button for showing success/failure messages on top of page...

window.scrollTo(0,0);