Category Archives: javascript

Test if jQuery is loaded

So to test if jQuery is loaded or not we can use 2 methods.

Method 1:
[javascript]
if (window.jQuery) {
// jQuery is loaded
} else {
// jQuery is not loaded
}
[/javascript]
Method 2:
[javascript]
if (typeof jQuery == ‘undefined’) {
// jQuery is not loaded
} else {
// jQuery is loaded
}
[/javascript]
Load jQuery:
[javascript]
if (!window.jQuery) {
var jq = document.createElement(‘script’); jq.type = ‘text/javascript’;
// Path to jquery.js file, eg. Google hosted version
jq.src = ‘/path-to-your/jquery.min.js’;
document.getElementsByTagName(‘head’)[0].appendChild(jq);
}
[/javascript]
NOTE:
Here we are checking for jQuery function being defined or not. This is a safe way to check for jQuery library being loaded. In case you are not using any other javascript libraries like prototype.js or mootools.js, then you can also check for $ instead of jQuery.

JavaScript Switch Statement

JavaScript Switch Statement

Syntax

[code language="javascript"]
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
[/code]

Example

[code language="javascript"]
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.

var d=new Date();
var theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
[/code]

How to reload current page in Javascript

There are 3 ways how to achieve this task.

[javascript]
<input value=’Reload Page’ onclick=’window.location.reload()’ type=’button’ />
[/javascript]

[javascript]
<input value=’Reload Page’ onclick=’history.go(0)’ type=’button’ />
[/javascript]

[javascript]
<input value=’Reload Page’ onclick=window.location.href=window.location.href’ type=’button’ />
[/javascript]

The button click is used to fire the loading. You can assign the event to hyperlink or trigger event by jquery

Prompt Usage

Prompt usage snippet

			var track_number = prompt("Please enter tracking number:");
			if(track_number)
			{
				$(this).data('track_number', track_number);
				//$(this).closest('tr').children().eq(4).append('<div style="color:red; display:block;text-align: center;">[' + track_number + ']</div>');
			}
			else
			{ 
				/* do something else */
			}

Remove text from text input when get focus

<input type='text' style='margin:0 10px;background-color:#F3FAAA;width:250px;height:16px;vertical-align: text-bottom;;' name='search_text' id='search_field' value='Ex.: Dell Latitude D620 enter D620 only' onfocus='$(this).val(\"\").css(\"color\", \"#000000\")' 
	onblur='($(this).val() == \"\") ? $(this).val(\"Ex.: Dell Latitude D620 enter D620 only\").css(\"color\", \"#9B9B9B\") :  $(this)' />