JavaScript: Calculate font-size on mobile devices

As I am making a HTML5 app for android devices using the Intel XDK I ran into a problem with the fonts. I use only em thinking that would work great on any screen size since its relative. I soon realized that it didn’t and that the text got reeeaally small on my phone when I uploaded the app. The reason seems to be zoom-related but I can’t swear to what the problem is aside from the fact that the screen has around 800px width and the standard font-size is still 16px which makes it unreadable. So I had to calculate the size myself and I found that the following formula worked like a charm:

 

var fontSize = Math.round(window.innerWidth * 0.04);
$('body').css('font-size', fontSize + "px");

This sets your font to a relatively easy reading size. Change the percentage if you need to alter the size!

CSS: Opacity without effecting child elements

Just thought I’d write down how to add opacity to an element without having it effect the child elements. If you just set opacity to an element then all child elements will have the same opacity. So, instead of opacity use rgba and set the opacity as the fourth parameter as in this example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" >
		<title>CSS: Use opacity without having it effect its children</title>
		<style type="text/css">
			* { margin: 0; padding: 0; } 
			body
			{
				background: transparent url(http://maffelu.net/test/css/opacity_child_elements/simple_tiled_background.jpg) repeat top left;
			}
			
			#wrapper
			{
				background-color: rgba(255, 255, 255, 0.7);
				width: 800px;
				margin: 20px auto;
				padding: 20px;
			}
			
			#wrapper > div
			{
				width: 100px;
				height: 100px;
				background-color: red;
			}
		</style>
	</head>
	<body>
		<div id="wrapper">
			<h2>This is a CSS example</h2>
			<div>
				Test text
			</div>
		</div>
	</body>
</html>

This is what it could look like. I’ve added a horrible tiled background to make the opacity more visible (you can also see a real example here):

An opacity example
An opacity example

CSS: Using multiple selectors

I was fiddling around with a Windows 8 app today which I’m developing using HTML 5 and I was making some changes to the HTML structure. One of the things I was changing was that some parts of the content was supposed to be inactive at the opening of the app and later on activated. I wanted to display these things as inactive by changing their text color to gray.
To do this I gave them the class Inactive and set the color of the text in that class to gray using CSS. One problem though that some of inactive content was going to have one kind of gray and other inactive content was going to have another kind if gray but they were both using the class Inactive.
One thing I could do is to create two separate classes but I liked the name Inactive as it was descriptive and concise. What I actually wanted to do is to say all the elements with the class Inactive AND the class XXX. Luckily, this could be done. Look at the following example:

<!DOCTYPE html>
<html>
	<head>
		<title>CSS Test</title>
		<meta charset="UTF-8" />
		<style type="text/css">
			/* Will affect all elements with the class Inactive */
			.Inactive
			{
				color: LightSlateGray ;
			}
			
			/* Will affect all elements with the class Content AND Inactive */
			.Content.Inactive
			{
				color: DimGray;
			}
		</style>
	</head>
	<body>
		<div class="Content Inactive">
			<p>Some of my content</p>
		</div>
		<div class="Content Active">
			<p>Some of my content</p>
		</div>
		<div class="Stuff Inactive">
			<p>Some of my stuff</p>
		</div>
		<div class="Navigation">
			<ul>
				<li>Home</li>
				<li class="Inactive">Links</li>
				<li>Guestbook</li>
			</ul>
		</div>
	</body>
</html>

I want to inactive the stuff in the class Content but not in the class Stuff. But I can’t do “.Content .Inactive” because they are set to the same element. Luckily I could combine to two into “.Content.Inactive“. Notice that there is no space between the classes:

/* Will affect all elements with the class Inactive */
.Inactive
{
	color: LightSlateGray ;
}

/* Will affect all elements with the class Content AND Inactive */
.Content.Inactive
{
	color: DimGray;
}

This can be very handy. I don’t know why I haven’t seen it before. There is supposed to be compatibility issues with IE6 but it’s 2013 so either you don’t support IE6 anymore or, if you do, you will have learned how to handle IE6 specific issues already (the problem in IE6 with .Content.Inactive is that it will only read the first class, .Content, and skip the rest).

Javascript: Looping through radio buttons without jQuery

There are times when you don’t have access to a third-party library such as jQuery to make life easy and those are the times where you regret not paying any attention to how actual javascript works. Going through radio buttons with jQuery is very easy, but with javascript it is a little bit more unclear if you haven’t done it before.

I’m going to show you a very simple example where I have four radio buttons and I want to know which one is selected:

index.htm

<!DOCUMENT html>
<html>
	<head>
		<title>Javascript Radio Button Demo</title>
		<script type="text/javascript" src="MyScript.js"></script>
	</head>
	<body>
		<h1>My Form with radio buttons!</h1>
		<form id="MyForm" name="MyForm" action="#" method="GET">
			<p><input type="radio" name="direction" value="north"> North</p>
			<p><input type="radio" name="direction" value="east"> East</p>
			<p><input type="radio" name="direction" value="south"> South</p>
			<p><input type="radio" name="direction" value="west"> West</p>
			
			<p><input type="submit" name="submit" value="Submit"></p>
		</div>
	</body>
</html>

MyScript.js

window.onload = function()
{
	//Fetch the form element
	var form = document.getElementById("MyForm");
	
	//Bind the 'onsubmit' event to an anonymous function
	form.onsubmit = function()
	{
		//Find out how many radio buttons you have
		var numberOfDirections = form.direction.length;
		
		//Loop through the radio buttons
		for(var i = 0; i < numberOfDirections; i++)
		{
			//Select a radio button
			var direction = form.direction[i];
			
			//Check if the radio button is checked
			if(direction.checked)
			{
				alert("You selected " + direction.value);
			}
		}
		
		return false;
	}
}

What is important is that the name-tag is the same for all radio buttons that are considered to be part of the same group. This way the document-object will generate array properties in the form-objects for the radio buttons. As we loop through that array we can check if the radio button checked-property is true. If it is, we found the checked radio button.

JavaScript: Basic form validation

This is a follow-up article to a previous article about basic DOM manipulation with JavaScript which you might want to read if you’re new to JavaScript.

The simplest way to get the element from the document object using the getByElementId() method and then checking the value property of the element:

var name = document.getElementById("Name");

This finds the element with the ID Name and put it in the variable name. We can now use the element to validate it. The following code is an example of how to check that the name isn’t empty and that the age is numeric and above 0. If there is an error it wil return false and color the background of the faulty input box red:

index.htm

<!DOCUMENT html>
<html>
	<head>
		<title>Javascript DOM manipulation Example</title>
		<script type="text/javascript" src="demo.js"></script>
	</head>
	<body>
		<h1>Javascript form validation test!</h1>
		<form id="MyForm" onsubmit="return validateForm()">
			<p>Name: <input type="text" id="Name" /></p>
			<p>Age: <input type="text" id="Age" /></p>
			<p><input type="submit" id="Submit" value="Submit"/></p>
		</form>
	</body>
</html>

demo.js

function validateName(name)
{
	if(name == "" || name == null || name === "undefined")
	{
		return false;
	}
	
	//Name must be more than one letter
	if(name.length <= 1)
	{
		return false;
	}
	
	return true;
}

function validateAge(age)
{
	if(age == "" || age == null || age === "undefined")
	{
		return false;
	}
	
	if(isNaN(age))
	{
		return false;
	}
	
	if(parseInt(age) <= 0)
	{
		return false;
	}
	
	return true;
}

function validateForm()
{
	//Check name
	var name = document.getElementById("Name");
	var isNameOk = validateName(name.value);
	console.log(name);
	
	if(isNameOk)
	{
		name.style.background = "#FFFFFF";
	}
	else
	{
		name.style.background = "#FF0000";
	}
	
	//Check age
	var age = document.getElementById("Age");
	var isAgeOk = validateAge(age.value);
	
	if(isAgeOk)
	{
		age.style.background = "#FFFFFF";
	}
	else
	{
		age.style.background = "#FF0000";
	}

	return isNameOk && isAgeOk;				
}

We hook up to the onsubmit event on the form element in HTML and we return the value we get from the validation method validateForm. If we return false the form won’t submit and that’s why we alter the form and color it, so that the user can identify where the errors are. This can be made even better by adding text or something but in this demo we’ll keep it simple.

Try a demo here if you want!

JavaScript: Basic DOM manipulation

JavaScript as a language has a couple of built-in objects ready to use such as Array, Boolean, Date, Function, Math, Number, Object, RegExp and String. Depending on your executing environment you may, however, have more objects pre-defined to work with. Most people use JavaScript on their web sites which means the running environment is a browser and it comes with several useful objects. One of these objects is called document and it is the object that we’ll be looking at in this article.

The document object represents the entire HTML structure of the current page and allows for you to easily search the HTML structure using methods such as getElementById and getElementsByClassName. The name of the methods are quite self explanatory and we’ll be using the getElementById method to manipulate a button. We’ll change its text, its background and the font-weight of it:

 

<!DOCUMENT html>
<html>
	<head>
		<title>Javascript DOM manipulation Example</title>
		<script type="text/javascript">
			function handleClick()
			{
				var button = document.getElementById("MyButton");	
				button.innerHTML = "This value just changed!";		
				button.style.background = "#FFF";					
				button.style.fontWeight = "bold"; 					
			}
		</script>
	</head>
	<body>
		<h1>Javascript Button test!</h1>
		<button id="MyButton" onclick="handleClick()">Click here!</button>
	</body>
</html>

What we do here is that we create a function called HandleClick which we hook up to the onclick event of the button. When the button is clicked the function is executed and in it we fetch the button by using the getElementById method of the document object.
The method will return a reference to the button object which is now open for manipulation. We change the text of the button by utilizing the innerHTML property of the button-object. We can manipulate the CSS of the element by going through the style property of the button which contains all the CSS elements ready to be read or written to. Note, however, that some CSS element are hyphenated and they are changed to camelCasing (i.e. font-weight becomes fontWeight and padding-left becomes paddingLeft).

Click here for an example!