Javascript - Useful Tips & Tricks

:cool:
thx for sharing

change background color to black:

void(document.bgColor=‘#000000’);

change foreground color to white:

void(document.fgColor=‘#ffffff’);

this could help :slight_smile: :wink: :slight_smile:

An external “Breakout-script” to prevent forrein websites from capturing your website in a frame.

/*Does the browser support DOM?*/
ie = (document.all) ? true:false; // IE4+
dom = ((document.getElementById) && (!ie)) ? true:false; // Mozilla
/*Call to the help function*/
setEventByObject(window,"load", breakingOutOfFrames);
/*Help function*/
function setEventByObject(ob, ev, fu) {
if(dom) {
ob.addEventListener(ev, fu, false);
}
if(ie) {
ob.attachEvent('on' + ev, fu);
}
}
/*Breaks out of frames*/
function breakingOutOfFrames() {
if (top.location != location) {
top.location.href = document.location.href;
}
}

“Bookmark this site” Button to be put within the head tags
of your HTML document, or even better, put it in an external file(without script tags) and link to that file in the head:

<script language="JavaScript" type="Text/Javascript">
<script language="JavaScript" type="Text/Javascript">
<!-- //
/*Avgör läsaren*/
var ie = (document.all) ? true:false; // IE4+
var dom = ((document.getElementById) && (!ie)) ? true:false; // Mozilla
var url = "http://www.webpelican.com/internet-programming-3/";
var pageName = "Client side programming";
function bookmark() {
if (ie)
window.external.AddFavorite(url, pageName)
else if(dom)
window.sidebar.addPanel(pageName, url,"");
else {
alert("Sorry! Your browser doesn't support function. Use the bookmark option in your browser instead.");
return true;
}
} // --></script>

Put this somewhere in the body section of your HTML document:
Button:

<input type="button" value="Bookmark" name="Bookmark" onclick="bookmark()" />

or

Simple link:

<a
href="javascript:bookmark()">Bookmark
</a>

(and of course change the URL to whatever URL you would like to bookmark )

Thanks for the details! they’re very useful!:slight_smile:

javascript newbie needs help! :smiley:

Writing a simple script (yeah right):

Have the following:
<html>
<head>
<script language=“javascript” type=“text/javascript”>
<!–
var radzvalue=0

function setrad(num){
radzvalue = num;
}
function button1_onclick() {
var answer, radiovalue=0;
answer=text1.value;

if (checkbox1.checked){
answer=num1-num2;
}else if (checkbox2.checked){
anser=num1*num2;
}else{
answer=num1/num2
}
if (radiox[0].checked)radiovalue=1;
else if (radiox[1].checked)radiovalue=2;
else if (radiox[2].checked)radiovalue=3;
}

</head>
<body>
<p><span id=“num1”>10</span>
<p><span id=“num2”>20</span>
<span>
<input id=radiox type=radio name=radiox value=1 />Subtract
<input id=“Radio2” type=“radio” />Multiply
<input id=“Radio3” type=“radio” />Divide</span></p>

<input id=“Text1” style=“width: 49px” type=“text” />
</body>
</html>

What should happen is when a number(answer) is entered into the textbox, the script should check to see of the answer is correct. i.e. the default is subtract so 10-20 = -10 etc. Then, random numbers need to be generated to take the place of the default num1 & num2 and the process starts again.

Any help or guidance would be appreciated.

Oak

usage:


var d = new Date();

d.addToDate("week",3,false); // adds 3 weeks to date, not time accurate
alert(d);
d.addToDate("minute",650); // adds 650 minutes to date, time accurate
alert(d);
d.addToDate("quarter",-6,false); // subtracts 6 quarters from date, not time accurate
alert(d);
d.addToDate("ms",15000); // adds 15000 milliseconds to date, time accurate
alert(d);

etc


Date.prototype.addToDate = function () {
/*
similar to the DateAdd function in VBS

accepts up to 2 parameters

param1 (unit) <string> optional, default="day"
	the type of unit to add to the date
	can be any of
	"year","quarter","month","week","day","hour","minute","second","ms" (millisecond)

param2 (qty) <integer> optional, default=1
	the number of units to add to the date

param3 (useTime) <boolean> optional, default=true
	set this to false if you are only doing date calculations, otherwise you may run into savings time errors!
	leave it set to true if you are doing time-accurate calculations
*/
	
	// default params
	var unit = "day";
	var qty = 1;
	var useTime = true;
	
	// get the params if they exist
	if (arguments.length > 2) {
		useTime = arguments[2];
	}
	if (arguments.length > 1) {
		qty = arguments[1];
	}
	if (arguments.length > 0) {
		unit = arguments[0];
	}
	
	// allow accidental use of "seconds" eg instead of "second"
	if (unit.charAt(unit.length - 1) == "s" && unit != "ms") {
		unit = unit.substr(0,unit.length -1);
	}
	
	// make sure we have a valid qty
	if (parseInt(qty) != qty) {
		alert("Bad quantity parameter: " + qty + ", date unchanged");
	} else {
		qty = parseInt(qty);
		
		// if time-accurate calculations are not used, set the time to 1:00:00AM so we don't have daylight savings errors
		if (useTime) {
			var dt = Date.UTC(this.getUTCFullYear(), this.getUTCMonth(), this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds(), this.getUTCMilliseconds());
		} else {
			// add getTimezoneOffset() minutes to 1:00 to get 1:00 =)
			var dt = Date.UTC(this.getUTCFullYear(), this.getUTCMonth(), this.getUTCDate(), 1, this.getTimezoneOffset(), 0, 0);
		}
		var dat = new Date(dt);

		// do stuff depending on which unit was used
		switch (unit.toLowerCase()) {
		case "year":
			// easy, add the quantity to years
			dt = Date.UTC(dat.getYear() + qty, dat.getMonth(), dat.getDate(), dat.getHours(), dat.getMinutes(), dat.getSeconds(), dat.getMilliseconds());
			break;
		case "quarter":
			// more complicated, calculate months and years to add
			qty = qty * 3;

			var yearsToAdd = parseInt(qty/12);
			var monthsToAdd = qty - yearsToAdd * 12;
			
			if (dat.getUTCMonth() + monthsToAdd > 11) {
				yearsToAdd += 1;
				monthsToAdd -= 12;
			} else if (dat.getUTCMonth() + monthsToAdd < 0) {
				yearsToAdd -= 1;
				monthsToAdd += 12;
			}

			dt = Date.UTC(dat.getUTCFullYear() + yearsToAdd, dat.getUTCMonth() + monthsToAdd, dat.getUTCDate(), dat.getUTCHours(), dat.getUTCMinutes(), dat.getUTCSeconds(), dat.getUTCMilliseconds());
			break;
		case "month":
			// more complicated, calculate months and years to add
			var yearsToAdd = parseInt(qty/12);
			var monthsToAdd = qty - yearsToAdd * 12;
			
			if (dat.getUTCMonth() + monthsToAdd > 11) {
				yearsToAdd += 1;
				monthsToAdd -= 12;
			} else if (dat.getUTCMonth() + monthsToAdd < 0) {
				yearsToAdd -= 1;
				monthsToAdd += 12;
			}
			
			dt = Date.UTC(dat.getUTCFullYear() + yearsToAdd, dat.getUTCMonth() + monthsToAdd, dat.getUTCDate(), dat.getUTCHours(), dat.getUTCMinutes(), dat.getUTCSeconds(), dat.getUTCMilliseconds());
			break;
		case "week":
			// the rest just add a number of milliseconds since eg 1 week = 1 week always and forever
			dt = dat.valueOf() + qty * 1000 * 60 * 60 * 24 * 7;
			break;
		case "day":
			dt = dat.valueOf() + qty * 1000 * 60 * 60 * 24;
			break;
		case "hour":
			dt = dat.valueOf() + qty * 1000 * 60 * 60;
			break;
		case "minute":
			dt = dat.valueOf() + qty * 1000 * 60;
			break;
		case "second":
			dt = dat.valueOf() + qty * 1000;
			break;
		case "ms":
			dt = dat.valueOf() + qty;
			break;
		default:
			alert("bad unit parameter: " + unit + ", date unchanged");
			break;
		}

		// would have been nice to do this part some other how but I couldn't figure it out
		dat = new Date(dt);
		
		this.setUTCMilliseconds(dat.getUTCMilliseconds());
		this.setUTCSeconds(dat.getUTCSeconds());
		this.setUTCMinutes(dat.getUTCMinutes());
		this.setUTCHours(dat.getUTCHours());
		this.setUTCDate(dat.getUTCDate());
		this.setUTCMonth(dat.getUTCMonth());
		this.setUTCFullYear(dat.getUTCFullYear());
		
	}
}

Sometimes, I find myself with a “test function” and the “real function” residing within the same function/object. When I want to run the test, I comment out the non-test and vice versa. The trouble is, I hate having to type the /* and */ over and over again to do my tests.

So, I’ve discovered a really cool way to handle this (borrowed from PHP). You can override /* and */ using line comments // to comment/uncomment your code:


function testFunction() {
  alert("test function");
}
function realFunction() {
  alert("real function");
}

In that block, I want to switch back and forth between my test and real functions regularly while testing, so I write my comment blocks a special way.

In this example, the real function is commented out, but the test function is exposed.


//*
function testFunction() {
  alert("test function");
}
/*/
function realFunction() {
  alert("real function");
}
// */

In this second example, by removing a single ‘/’ above “test function”, I’m able to comment out the test function block while at the same time exposing the real function.


/*
function testFunction() {
  alert("test function");
}
/*/
function realFunction() {
  alert("real function");
}
// */

You can see by the use of creative commenting, you can quickly comment/un-comment blocks of code by only adding or removing a single slash ‘/’ character and not having to worry about any lingering */ that will cause your code to choke.

Thnx for the detail.They are really useful

Hi.
Excellent thread buddies.
My little share for trivial tasks (ie el.offsetWidth).
I think it is quicker than parseInt.
function getInt(v){
return +v;
}
var v1= ‘test1’;
var v2= ‘300’;
var v3= 300;
alert(getInt(v1));
alert(getInt(v2));
alert(getInt(v3));

Best wishes :smiley:

I’m a relative newbie to this forum and I would just like to add my thanks to the contributors to this thread. Good stuff!!

Thanks for good information!!

A discussion of how prototypes work inside and outside of constructor functions.
http://www.room51.co.uk/js/prototypePlacement.html

Very nice thread… i learn some about javascript with this thread… Thanks for all…:drink::drinky::weee::wavey:

Very useful thread. I have been looking for some of these.

Wow, very nice guys. I am going to be referencing this as I read a beginner’s JavaScript book that I got from Sitepoint a couple weeks ago.

i am currently studying javascript and thanks that i have viewed your threads… it helps me a lot and i have learned very much

I’m newbies and try to do website with html and java.

Java could be making hard work for yourself. Javascript is much more suited for websites.

can someone tell me where i can find good javascript libraries???