How do you window.onload Javascript classes? - javascript

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>

Related

Do the exact contrary of append in Jquery

I'm working on a 3D interface with Babylonjs, so I need a canvas. Around that canvas I want to implement html elements (with Holy grail layout : nav to the left, main which is canvas at the middle and aside to the right) according to 2 modes : visualisation and edition.
I have a script to handle the canvas and play with babylonjs functions, and another one to manage the construction of the html according to the chosen mode.
As you can see in my code, I assign my html code to a variable, and append that variable to my holygrail main. However, I don't want my canvas to be recreated each time I change mode, so I implemented it directly in the HTML, it's constant.
My problem is : I want to append elements to my div #insertHere, but also to remove all the elements (excepted my canvas which has to remain) of this #insert div before appending new ones (else I would have several navs and asides).
Can anyone help me ?
Thank for your time !
Here's my construction script :
var content = "";
var construct = true;
var visualize = false;
function Create(){
content = "";
if(construct == true && visualize == false){
content += "<div id='1'> <p> hello</p></div><div><p>Insert a lot of html here</p></div>";
$("insertHere").append(content);
}
if(construct == false && visualize == true){
content += "<div id='not1'><p> Definitely not the same content as the construct one</p></div>";
$("insertHere").append(content);
}
}
$(window).ready(function(){
Create();
$("#switchmode").click(function(){
construct = !construct;
visualize = !visualize;
// INSERT THE SOLUTION TO CLEAR THE HTML HERE
CreationPage();
});
});
And here's my HTML (both are short representation of what I really have) :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
</head>
<body id="body" class="HolyGrail">
<header>
<link rel="stylesheet" type="text/css" href="style.css" media="all">
<link rel="stylesheet" href=".\bootstrap\css\bootstrap.css">
<link rel="stylesheet" href="justcontext.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" defer></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<script style="text/javascript" src="scripts/construction.js" defer></script>
</header>
<div id='menuonglets' class='btn-group' role='group' aria-label='Basic example'>
<button type='button' class='btn btn-secondary' id='switchmode'>Mode Visu/ Mode Constru</button>
</div>
<div class='HolyGrail-body' id='insertHere'>
<main class='HolyGrail-content'>
<canvas id='renderCanvas'></canvas>
</main>
<!-- Things are inserted here -->
</div>
</body>
</html>
You could use jQuery's filter() function to remove all elements but the canvas.
Here's a working example:
$("#btn_clear").on("click", function(e){
e.preventDefault();
$("#insertHere").children().filter(":not(.HolyGrail-content)").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='HolyGrail-body' id='insertHere'>
<main class='HolyGrail-content' style="background: orange;">
<canvas id='renderCanvas'></canvas>
</main>
<p>I'm a paragraph</p>
<ul>
<li>Foo</li>
<li>bar</li>
</ul>
</div>
Remove all elements but the canvas
So:
$(window).ready(function(){
Create();
$("#switchmode").click(function(){
construct = !construct;
visualize = !visualize;
// Remove all elements, except for the canvas and its container.
$("#insertHere").children().filter(":not(.HolyGrail-content)").remove();
CreationPage();
});
});

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>

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

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.

"Uncaught TypeError" when executing a Javascript function from a <script> HTML tag

I'm working on a basic quiz Javascript game, but when I use
document.getElementById("demo").innerHTML = "text";
I get this error message:
Uncaught TypeError: Cannot set property 'innerHTML' of null
in the Chrome Console. I have no idea why this no longer works, it has worked for me in the past. However, if I open up a new
tag, the function runs and the code works. It's only when I run the function in the same
tag.
My code is below:
<!DOCTYPE html>
<html>
<head>
<title>Study Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script>
function quiz() {
var rnd = Math.floor(Math.random() * 4);
document.getElementById("demo").innerHTML = rnd;
}
quiz(); //this one does not work
</script>
</head>
<body>
<p id="qarea"><p>
<p id="demo"></p>
<script>
quiz(); //this one does work
</script>
</body>
</html>
You forgot to include id in front of your ="demo" it should look like <p id="demo"> instead of
<p="demo"></p>
Second the reason the first call to quiz does not work is that your document has not loaded yet. you want to do this on pure js
<body onload="myFunction()">
Like this should work: http://jsfiddle.net/t8jnhmhg/1/ <p="demo" is wrong
It should be the following.
Where you would have to add the id attribute to the p tag.
<!DOCTYPE html>
<html>
<head>
<title>Study Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script>
function quiz() {
var rnd = Math.floor(Math.random() * 4);
document.getElementById("demo").innerHTML = rnd;
}
quiz(); // Will not work here because there is no such
// element with ID "demo" at this point in the page load.
</script>
</head>
<body>
<p id = "qarea"><p>
<p id = "demo"></p>
<script>
document.addEventListener( "DOMContentLoaded", function(){
quiz(); // Will work here because the DOM is loaded at this point.
});
</script>
</body>
</html>

how to use QUnit Callbacks api

I am in progress learning how to use QUnit and Javascript and html. So far i only know how to use some of Qunit APIs like OK(), equal(), notequal(), test(), and expect(), but i have tough time to understand how to use the callbacks like qunit.done or qunit.log. Can someone give me an example? i have some code below:
<head>
<title>My Tests</title>
<script src="jquery/jquery-2.1.0.min.js" type="text/javascript"></script>
<script src="qunitsrc/qunit-1.14.0.js" type="text/javascript"></script>
<link rel="stylesheet" href="qunitsrc/qunit-1.14.0.css" type="text/css" media="screen">
<script src="tests/calculator.js" type="text/javascript"></script>
<script src="tests/calculatortests.js" type="text/javascript"></script>
</head>
<body>
<h1 id="qunit-header">My Tests</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
calculator.js
function MathOperations(){
}
MathOperations.prototype.add = function(num1,num2)
{
var result = num1 + num2;
return result;
}
calculatortests.js
test("Add should add 2 items", function(){
var math = new MathOperations();
var result= math.add(1,2);
equal(result,3,"Result of 1+2 should be 3");
});
Basically, it sounds like you want to use these callbacks write a custom reporter. There are several existing ones that you can base yours off of. Here's an example for a JUnit compatible XML reporter:
https://github.com/jquery/qunit-reporter-junit

Categories