Collection of JavaScript code snippets

Detect if JavaScript is enabled

That one is tricky and I had no idea how to detect and react to this in the same request. However, for my purpose, I do not need to take action in the same request: I only want to tell a CGI-bin whether it should serve a page optimised for JavaScript enabled browsers. This is solved by simply adding a '&js=1' parameters to the link with JavaScript. Obviously, if JavaScript is disabled, the parameter will be missing.

function detect_javascript(cl)
{
	var nodes, i, s;
	nodes = document.getElementsByTagName('a');
	for (i = 0; i < nodes.length; i++) {
		if (nodes[i].className === cl) {
			s = nodes[i].href;
			nodes[i].href=s+'&js=1';
		}
	}
}

To tell the JavaScript which links shall be changed, you have to tag the links with a specific class

<a class="changeme" href="/cgi-bin/test.cgi">Test</a>

and pass this class to the JavaScript function call:

<script type="text/javascript">
	detect_javascript('changeme');
</script>

Detect screen size

function detect_window_size()
{
	var myWidth = 0, myHeight = 0;
	if (typeof(window.innerWidth) == 'number') {
		// All sane browsers
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		// IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		// IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	console.log('Width = ' + myWidth);
	console.log('Height = ' + myHeight);
	// window.alert('Width = ' + myWidth);
}

Test if array contains a key

if (arr.indexOf("key") !== -1) {
	console.log('Key exists');
}

Iterate through object keys (e.g. for json)

for (var key of Object.keys(obj)) {
	console.log(key + "->" + obj[key]);
}