Can't figure why my function is not a function? - javascript

I am trying to build a simple single page web app and I am stuck. I am trying to use the module pattern :
var spa = (function () {
var initModule = function( $container ) {
$container.html(
'<h1 style="display:inline-block; margin: 25px;">'
+ 'hello world!'
+ '</h1>'
);
};
return { initModule: initModule };
})();
Which in theory should be invoked here:
<!doctype html>
<html>
<head>
<title>SPA Starter</title>
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" href="css/spa.css" />
<link rel="stylesheet" type="text/css" href="css/spa.shell.css" />
<!-- third-party javascript -->
<script src="js/jq/jquery-1.11.3.js"> </script>
<script src="js/jq/jquery.uriAnchor-1.1.3.js"</script>
<!-- my Javascript -->
<script src="js/spa.js"> </script>
<script src="js/spa.shell.js"></script>
<script>
$(function() { spa.initModule( $('#spa') ); });
</script>
</head>
<body>
<div id="spa"></div>
</body>
</html>
I tried to do spa.initModule( $('#spa') ); in console and it's working, but in my code it isn't.
When I try to run I got Uncaught TypeError: spa.initModule is not a function
Thanks in advance.

http://jsfiddle.net/AlexeiTruhin/4rg0mdgb/ - works for me.
It means you have an error, for example in declaring the script:
<script src="js/jq/jquery.uriAnchor-1.1.3.js"</script>
Close the < script ..>

well,I met the same error,but the different reason that
I didn't insert "()" between "}" and ");" where in the end of the spa object definition.

Related

How do you window.onload Javascript classes?

I'm trying to dynamically change my html by calling my Javascript class in jQuery. I keep getting an Uncaught Reference error. I know I have to window.onload my class somewhere. I've tried to load it before and after the class, before and after my jquery, right before the end of my HTML body, but I keep getting Uncaught Reference errors for the class I'm calling and the prototype (randomCard()) that I use in my jQuery.
I've also tried switching the order of script files at the end of my HTML body. I'm new to Javascript.
game.js
function CardsAgainstHumanity () {
this.blackCards = [
"How did I lose my virginity?",
"Why can't I sleep at night?",
"What's that smell?",
"I got 99 problems but ______________ ain't one.",
"Maybe she's born with it. Maybe it's ______________.",
"What's the next Happy Meal toy?",
"Here is the church. </br> Here is the steeple. </br> Open the doors </br> And there is ________________.",
"It's a pity that kids these days are all getting involved with _______________."
];
this.whiteCards = [];
this.score = 0;
randomCard();
}
CardsAgainstHumanity.prototype.randomCard = function () {
var random = this.blackCards[Math.floor(Math.random() * this.blackCards.length)];
return random;
};
index.js
$(document).ready (function() {
$(".black-cards").on("click", function () {
$(this).text(randomCard());
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>Cards Against Humanity</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link type="text/css" rel="stylesheet" href="css/style.css" media="screen">
</head>
<body>
<div class="container">
<div class="black-cards"> </div> <!-- Black Cards -->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="js/game.js"></script>
<script src="js/index.js"></script>
</body>
</html>

Javascript Function works inside HTML page but doesn't work from external .js file

I am trying to place some Javascript code inside a .js file so that I can call it from multiple HTML pages. The problem is, my Javascript code works fine if I place it in a script within the HTML page, but when placed in a external .js file, it simply does not work. I've looked at these questions quite a few times and still cannot find the error.
Here's the HTML page:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/global.css" />
<link rel="stylesheet" type="text/css" href="css/contacts.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src ="js/contactsModule.js"></script>
<title>Hall of Heroes</title>
</head>
<body onload = "contactsModule.getContacts();">
<!-- Global Header Starts Here -->
<div class="header">
<div class="cancel">
<img src="img/cancel.png" /><!-- if screen is triggered from onboarding, then go back to onboarding screen instead of home -->
</div>
<h1>My Contacts</h1>
</div>
<div class="wrapper">
<h3>A</h3> <!-- letter header goes here -->
<!-- Begin Contact Unit -->
<div class="feed">
</div>
<!-- End Contact Unit -->
</div>
</body>
</html>
And here is the .js file:
var contactsModule = (function($){
function getContacts()
{
dbContacts();
}
function displayContacts(contactArray){
window.alert('displayContacts now running!');
var jsonObject = $.parseJSON(contactArray);
jsonObject.forEach(function (dat) {
//Begin Contact Unit
$('.feed')
.append('<div class="feed-img"><img src="' + dat.avatarUrl + '"/>\
</div><div class="feed-text"><p><span class="name_highlight">\
' + dat.firstName + ' ' + dat.lastName + '</span></p></div>');
//End Contact Unit
});
}
function dbContacts() {
var avatarUrl;
var firstName;
var lastName;
$.ajax({
type: "GET",
url: "http://www.hallofheroesapp.com/php/contacts.php",
data: {avatarUrl: avatarUrl, firstName: firstName, lastName: lastName},
success: function (response) {
window.alert('AJAX ran successfully!');
displayContacts(response);
},
error: function(response){
alert("Error:" + response);
}
});
}
}(jQuery));
Thank you for your help!
You aren't returning anything from your IIFE. contactsModule will then not contain anything, ie equal undefined. Also just defining functions doesn't make those functions part of some object, with the exception of globally defined functions. You have to assign them, or define them as part of an object literal
Your code should be something like
var contactsModule = (function($){
return {
getContacts: function() {
/* code */
},
displayContacts: function(contactArray){
/* code */
}
dbContacts function() {
/* code */
}
};
}(jQuery));
How about using
$(document).ready(function(){
///// your code here...
});
... change ...
<body onload = "contactsModule.getContacts();">
... to ...
<body>
... and add event handler using jquery ...
(function($){
function getContacts()
{
dbContacts();
}
/* ... etc ... */
// use jquery's onready handler
$(getContacts);
}(jQuery));
Had the same problem. Easy thing when you research on google.
Your Js code loads before the DOM loads. Which should be the other way around. So you have to use this
$(document).ready(function(){
//only jQuery is recommended, global JavaScript functions outside!
});
Also JavaScript
document.addEventListener("DOMContentLoaded", function(event) {
//global function outside!
});
Only this way you can be sure that your DOM is loaded before your jquery finds your elements.

Getting ReferenceError for own date method in JavaScript

I'm using Mozilla Firefox 43.0 on Ubuntu 12.04 LTS. I wrote the following JavaScript method saved in mainScript.js:
function writeDateHu() {
var days = ["Hétfő", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat", "Vasárnap"];
var current = new Date();
var s = "";
s.concat("<p>", current.getFullYear(), ". ", (current.getMonth() + 1), ". ", current.getDate(), ".<br />", days[current.getDay()], "</p>");
document.getElementById("datum").innerHTML = s;
}
I've also tried to add them by using + instead of concat.
In the main.html I have the following:
<!DOCTYPE html>
<html>
<head>
<title>HomePage</title>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="mainStyle.css" />
<script type="text/css" src="mainScript.js"></script>
</head>
<body onload="writeDateHu();">
<div class="alap">
<div class="fejlec">
</div>
<div class="bal" id="datum">
</div>
<div class="tartalom">
</div>
<div class="lablec">
</div>
</div>
</body>
</html>
After loading page, the inspector says me ReferenceError: writeDateHu is not defined. Also, sometimes (e.g. I insert the script in the html) I don't get the error, but nor the date.
Thanks for any advance.
You have loaded a JavaScript file as CSS.
<script type="text/css" src="mainScript.js"></script>
All you should have done is this
<script src="mainScript.js"></script>

Simple AngularJS Click-To-Animate "Argument 'AppCtrl' is not a function, got undefined"

I'm trying to figure out how to write a very basic AngularJS app that performs an animation when a button is clicked, I can't figure out why it's not working I copied a tutorial in verbatim and can't figure out why the tutorial is wrong.
UPDATE: I got it working, for some reason there was another ng-app inside the html tag. You can copy the code below and load it up immediately and play around with animations if you copy everything:
Here's what animatetest.html looks like:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Top Animation</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body ng-app="app" ng-controller="AppCtrl as app">
<button id="my-button" class="btn-primary" ng-click="app.fadeIt()">Click to fade</button>
<div id="my-badge" class="badge" hide-me="app.isHidden">Fade me</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-animate.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.11.6/TweenMax.min.js"></script>
<script src="test.js"></script>
</body>
</html>
And here's what test.js looks like:
var app = angular.module("app", ["ngAnimate"]);
app.controller("AppCtrl", function () {
this.isHidden = false;
this.fadeIt = function () {
this.isHidden = !this.isHidden;
}
});
app.directive("hideMe", function () {
return function (scope, element, attrs) {
scope.$watch(attrs.hideMe, function (newVal) {
if (newVal) {
TweenMax.to(element, 1, {opacity: 0});
}
})
}
});
UPDATE 2: Here's a sample plunker that's 10x better than the example above since it removes the need for a third party TweenMax library to do the actual animation:
http://plnkr.co/edit/WU6y8ka0udXHzZvCeZPc
No. Well yes... but the biggest problem is you're following a tutorial that is buggy. You have ng-app twice... once nested. It's got jquery selectors inside an angular function on an element... and jquery isn't even loaded.
And you're using a fairly old version of bootstrap (relatively speaking).
There are 2 better options than using jquery in your tween function... First, you could specify exactly which element by passing it as a parameter in your fadeIt function, or better yet, handle this via a custom directive using isolate scope.
<!doctype html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Top Animation</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body ng-controller="AppCtrl as testApp">
<div id="my-button" class="btn btn-primary" click-fade>Fade me</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-animate.js"></script>
<script src="test.js"></script>
</body>
</html>
test.js:
angular.module("app",['ngAnimate'])
.directive('clickFade',function(){
return function(scope, element) {
element.bind("click", function() {
TweenMax.to(element, 1, {opacity: 0});
})
}
})
Notice how I removed the use of jQuery, and also your function for clicking/fading was on the wrong element.

I copied just 3 lines of script from vimeo example - and it causes an 'undefined' error

I copied 3 lines of code from Vimeo, and Chrome's javascript debugger says they cause an undefined error. It tries to do a 'split' on an element that does not exist. Here is the 3 lines of script, plus all the html, since its obviously very short. Any help is appreciated.
<!DOCTYPE html >
<html>
<head><meta http-equiv="Content-Type" content="Type=text/html; charset=utf-8" /><title>
</title><link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/sunny/jquery-ui.css" /><link href="/Styles/common.css" rel="stylesheet" type="text/css" />
<script src='/Scripts/utilities.js' type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
var f = $('iframe'),
url = f.attr('src').split('?')[0],
status = $('.status');
</script>
</head>
<body>
<center>
<table><tr><td>
<div id="ContainPlayer" style="position:relative;">
<iframe src="//player.vimeo.com/video/79036140?autoplay=1&api=1"
player_id="vimeoplayer" id="vimeoplayer"
width="1000" height="454"
frameborder="0" ></iframe>
</div> </td>
</tr></table>
</center>
</body>
</html>
This is because you put the javascript before content is loaded, before the page is rendered. Move the script code after the iframe or put the block in a domready event.
$(function(){
var f = $('iframe'),
url = f.attr('src').split('?')[0],
status = $('.status');
});
You have to wrap your code in $(document).ready(function () {});
Either write your code...
$(function() {
here
})
or before the closing body tag.
The problem is that your script is executed before the html is rendered.

Categories