TinyMCE: Cannot call method ‘add’ of undefined

As I was implementing TinyMCE 4.0.5 on a site I got a funny error in my console in chrome:

Uncaught TypeError: Cannot call method ‘add’ of undefined

My implementation looked something like this:

	tinyMCE.init(
	{
		selector: ".WritingArea",
		plugins: "link lists preview anchor spellchecker emoticons textcolor paste",
		toolbar1: "bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",
		toolbar2: "cut copy paste | bullist numlist | undo redo | link unlink | forcolor backcolor",
		menubar: false,
        toolbar_items_size: 'small',
		height: "100%",
		resize: false,
		setup: function(ed)
		{
			ed.onInit.add(function(ed)
			{
				tinyMCE.get(ed.target.id).hide();				
			});
		}
	});

The problem turned out to be the change in event handler management. The event onInit isn’t used anymore, instead you bind it like this:

...
		setup: function(ed)
		{
			ed.on("init", function(ed)
			{
				tinyMCE.get(ed.target.id).hide();
			});
		}
...

The documentation is, as I’m writing this, a bit weak on this point but now you know 🙂

Javascript: parsing an int with a leading zero

As I had to parse some strings numbers with leading zeroes into int some days ago I thought I’d just use the old parseInt function and everything would work out well. What could go wrong? Well it turned out that parseInt had a bit of a weird feature when it came to parsing string numbers with leading zeroes.
The documentation explains it like this:

If radix is undefined or 0, JavaScript assumes the following:

If the input string begins with “0x” or “0X”, radix is 16 (hexadecimal).
If the input string begins with “0”, radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
If the input string begins with any other value, the radix is 10 (decimal).
If the first character cannot be converted to a number, parseInt returns NaN.
 

This means that if you run the following code:

parseInt("08");

you will get 0 and not 8.

In most browsers.

In IE9 and IE10 you will actually get 8. And in Chrome version 26+ (possible lower, haven’t tried) you will get 8. But in IE10 quirks mode you will get 0.

So it isn’t actually all sorted out what you’re going to get.

To be sure of what you are about to receive you are better of defining the base from the start:

parseInt("08", 10); //Defining a 10 base

This will guarantee that you get the parsing done with a 10 base all the time.

JQuery: Handle left-click, right-click and double-click at the same time

I just had to handle a left-click, right-click and a dbl-click at the same time which turned out to be a bit tricky at first using just the mousedown function, but the solution was simple:

$("#Foo")
	.click(function() //Left click
	{
		//Do something
	})
	.mousedown(function(e) //Right click
	{
		if(e.which == 3) //1: left, 2: middle, 3: right
		{
			//Do something
		}
	})
	.dblclick(function() //Double click
	{
		//Do something
	});

Windows 8: Using jQuery in your Windows Store app

Right, so I thought it would be great to write a HTML5 app in windows 8 since it’s supported and everything. The one thing I refuse to skip though is jQuery. So, I added jQuery 1.9.1 to my app, referenced it in my html-file and ran the app. The following popup showed up:

JavaScript runtime error: Unable to add dynamic content. A script attempted to inject dynamic content or elements previously modified dynamically that might be unsafe. For example, using the innerHTML property to add script or malformed HTML will generate this exception. Use the toStaticHTML method to filter dynamic content or explicitly create elements and attributes with a method such as createElement.
The error I received

I searched the web and I found that the only solution that seems safe at the time of writing is to use a “fixed” version for Windows 8, supplied by a company called AppendTo. The files can be downloaded here:
https://github.com/appendto/jquery-win8

Currently the latest jQuery release is 1.9.1 and the AppendTo conversion is 1.8.2 but it’s close enough and it works for me.

According to a couple of videos floating around and some articles on the subject the jQuery 2.0 release will have full support for Windows 8 so that should be great. But until then the AppendTo solution seems to be the best one out there.

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!