You are getting the error because you are using “$w” before the page is ready.
In order to fix that, you need to put your code inside the onReady callback:
$w.onReady(function () {
// Paste your code here:
});
Let me know if it solved the problem.