Uncaught ReferenceError - Function is not defined - javascript

I have created a small website with a couple of buttons. Each button should call a previously defined JS function. But with every button press I get a ReferenceError stating that the function is not defined.
(index):1 Uncaught ReferenceError: mainLightOn is not defined
Here's the code of my site:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Home Cinema Control Center</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
<style type="text/css">
td {
padding: 10px;
}
body {
font-family: Segoe UI, Arial, sans-serif;
background-color: #636363;
}
p {
color: #3b3b3b;
font-size: 4.0em;
}
.btn-xlarge {
padding: 18px 28px;
font-size: 3.5em;
line-height: normal;
border-radius: 8px;
}
.box {
background-color: #fbfbfb;
margin: 120px auto;
padding: 20px;
border-radius: 5px;
box-shadow: 10px 15px 20px rgba(0, 0, 0, 0.3);
}
</style>
<script type="text/javascript">
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// Add stuff later
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
function mainLightOn() {
httpGetAsync("/api/mainlight/1");
}
function mainLightOff() {
httpGetAsync("/api/mainlight/0");
}
</script>
</head>
<body>
<div class="box" style="width:90%; display:table">
<table style="width:100%">
<tr>
<td style="width:40%;">
<p>Main Light</p>
</td>
<td style="width:30%;">
<button type="button" class="btn btn-success btn-xlarge btn-block" onclick="mainLightOn()">On</button>
</td>
<td style="width:30%;">
<button type="button" class="btn btn-danger btn-xlarge btn-block" onclick="mainLightOff()">Off</button>
</td>
</tr>
</table>
</div>
</body>
</html>
Strangely the error does only occur when I open the website from my server. When I open the html locally on my laptop, the functions are called fine.

Your function definitions are inside the $().ready(function() {... }) body, so the scope is just that function. Javasript that's executed from HTML elements is executed in the global scope.
There's no need to put those functions inside $().ready(). You only need to put code there if it has to wait until the DOM is ready before running. But these functions will only be executed when the user clicks on the elements, which can't happen until the DOM is ready.

The error can be reproduced if named functions are within .ready() handler, where this is set to document
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Home Cinema Control Center</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
<style type="text/css">
td {
padding: 10px;
}
body {
font-family: Segoe UI, Arial, sans-serif;
background-color: #636363;
}
p {
color: #3b3b3b;
font-size: 4.0em;
}
.btn-xlarge {
padding: 18px 28px;
font-size: 3.5em;
line-height: normal;
border-radius: 8px;
}
.box {
background-color: #fbfbfb;
margin: 120px auto;
padding: 20px;
border-radius: 5px;
box-shadow: 10px 15px 20px rgba(0, 0, 0, 0.3);
}
</style>
<script type="text/javascript">
$().ready(function() {
function httpGetAsync(theUrl) {
console.log(theUrl);
}
function mainLightOn() {
httpGetAsync("/api/mainlight/1");
}
function mainLightOff() {
httpGetAsync("/api/mainlight/0");
}
})
</script>
</head>
<body>
<div class="box" style="width:90%; display:table">
<table style="width:100%">
<tr>
<td style="width:40%;">
<p>Main Light</p>
</td>
<td style="width:30%;">
<button type="button" class="btn btn-success btn-xlarge btn-block" onclick="mainLightOn()">On</button>
</td>
<td style="width:30%;">
<button type="button" class="btn btn-danger btn-xlarge btn-block" onclick="mainLightOff()">Off</button>
</td>
</tr>
</table>
</div>
</body>
</html>
Solution, since it does not appear to be possible to set this to other than document using .ready(), where the onclick handler is expecting this to be window, is to place the named functions outside of .ready() handler
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Home Cinema Control Center</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
<style type="text/css">
td {
padding: 10px;
}
body {
font-family: Segoe UI, Arial, sans-serif;
background-color: #636363;
}
p {
color: #3b3b3b;
font-size: 4.0em;
}
.btn-xlarge {
padding: 18px 28px;
font-size: 3.5em;
line-height: normal;
border-radius: 8px;
}
.box {
background-color: #fbfbfb;
margin: 120px auto;
padding: 20px;
border-radius: 5px;
box-shadow: 10px 15px 20px rgba(0, 0, 0, 0.3);
}
</style>
<script type="text/javascript">
function httpGetAsync(theUrl) {
console.log(theUrl);
}
function mainLightOn() {
httpGetAsync("/api/mainlight/1");
}
function mainLightOff() {
httpGetAsync("/api/mainlight/0");
}
</script>
</head>
<body>
<div class="box" style="width:90%; display:table">
<table style="width:100%">
<tr>
<td style="width:40%;">
<p>Main Light</p>
</td>
<td style="width:30%;">
<button type="button" class="btn btn-success btn-xlarge btn-block" onclick="mainLightOn()">On</button>
</td>
<td style="width:30%;">
<button type="button" class="btn btn-danger btn-xlarge btn-block" onclick="mainLightOff()">Off</button>
</td>
</tr>
</table>
</div>
</body>
</html>

Related

Underlining links

I am writing a site to order. But I ran into the problem for the first time - I can not remove the underscores from the bottom of the link. Already tried through
a: hover {text-decoration: none}
as well as on another.
From below I will provide HTML code as well as CSS code
I ask to help to correct such unexpected error
body{background: #efefef
url("images/geometry2.png");
margin: 0; padding: 0;
font: 16px/24px Arial, Tahoma, Sans-serif;
}
div.mid{
width: 1000px; margin: 0 auto;
}
a:hover {
text-decoration: none;
}
div.header{
background: #101417;
}
/*Шапка сайта*/
div.topmenu{float: right;height: 70px; line-height: 70px;}
div.topmenu a{margin: 0 0 0 10px; color: #0000FF;}
div.topmenu a:hover{color: #fff}
div.afisha {padding: 20px 50px 0 50px; background: #f2f2f2 url("images/headline.png") top repeat-x;}
div.afisha img {float: left; }
div.afisha h3 {font-size: 24px; font-weight: normal; text-align: center; color: #830000;}
div.afisha p{text-align: center;}
div.afisha a{font-size: 20px; color: #fff; font-weight: bold; background: #b23600; border: 1px solid #862900;}
div.clear{clear: both;}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Мой сайт</title>
<link rel="shortcut icon" type="image/x-icon" href="images/logomin.png">
<link rel="stylesheet" href="style.css" media="all">
</head>
<body>
<div class="header">
<div class="mid" >
<header>
<div class="topmenu" style='float:right;height: 70px; line-height: 70px'
</div>
<aside>
Главная
Тренинг
Шаблоны
Контакты
</aside>
</div>
<img src="images/logo.png" alt="Логотип сайта" title="Логотип сайта">
<div class="afisha"</div>
<img src="images/v5.jpg" alt="Обложка тренинга" title="Обложка тренинга">
<h3>Стань профессиональным верстальщиком<br>всего за 2 месяца<br> и зарабатывай по 30 000 рублей!</h3>
<p>Смотрите здесь<p>
<div class="clear"></div>
</header>
</div>
</div>
<div class="menu">
<div class="mid" >Привет мир</div>
</div>
<div class="conten">
<div class="mid" ></div>
</div>
<div class="footer">
<div class="mid" ></div>
</div>
</body>
</html>
try with
div.mid{
width: 1000px; margin: 0 auto;
}
a {
text-decoration: none;
}
a:hover {
text-decoration: none;
}
also clear caches before checking results..
With :hover you can set CSS properties when the link in hovered(i.e. mouse is over the link).
It seems you want to remove the default underline property of the link. To do so you need to apply CSS directly to the a tag:
a{text-decoration: none}

How do I make all my javascript external with the window onload function?

I am trying to make all my JavaScript external including the onclick for the submit button, I have a commented out window.onload function that I can't get to work. When I remove the onclick="checkInput();" from the submit input and uncomment the window.onload event in the script , my form doesn't work.
Can someone explain what I am doing wrong besides being new to JavaScript.I have included a working snippet, just not external, thanks for any guidance.
/*----------------------------------------------
css settings for HTML div exactCenter
------------------------------------------------*/
#import url(http://fonts.googleapis.com/css?family=Raleway);
#main{
width:960px;
margin:50px auto;
font-family:raleway;
}
span{
color:black;
font-weight:bold;
}
h2{
background-color: white;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 30px;
}
hr{
border:0;
border-bottom:1px solid blue;
margin: 10px -40px;
margin-bottom: 30px;
}
#form_layout{
width:300px;
float: left;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 25px;
margin-top: -2px;
}
input[type=text],input[type=password]{
width:99.5%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
}
input[type=submit]{
width: 100%;
background-color:#0467fc;
color: white;
border: 2px solid #0467fc;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: 15px;
}
a{
text-decoration:none;
color: cornflowerblue;
}
i{
color: cornflowerblue;
}
p{
font-size:16px;
font-weight:bold;
color:red;
}
<!DOCTYPE html>
<html>
<head>
<script>
//window.on onload functionload = function() {
//document.getElementById('submit').onclick = function(evt) {
//checkInput();
//}//end onload onclick
</script>
</head>
<body>
<div id="main">
<div id="form_layout">
<h2>Palindrome Test</h2>
<br>Enter a 10 character Palindrome.
<!-- Form starts here-->
<form name="pForm" id="pForm" method="post" >
<label>Palindrome:</label>:
<input type="text" name="uput" id="uput"/><br>
<!-- ... all the other stuff ... -->
</form><br>
<input type='submit' id="submit" value="Check Palindrome" onclick="checkInput();"/><br>
<p><span id="eMsg" class="error"></span><p/><br>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>isPalindrome</title>
<script>
//window.on onload functionload = function() {
//document.getElementById('submit').onclick = function(evt) {
//checkInput();
//}//end window.onload
Palindrome(str);
</script>
</head>
<body>
<div id="main">
<div id="form_layout">
<h2>Palindrome Test</h2>
<br>Enter a 10 character Palindrome.
<!-- Form starts here-->
<form name="pForm" id="pForm" method="post" >
<label>Palindrome:</label>:
<input type="text" name="uput" id="uput"/><br>
<!-- ... all the other stuff ... -->
</form><br>
<input type='submit' id="submit" value="Check Palindrome" onclick="checkInput();"/><br>
<p><span id="eMsg" class="error"></span><p/><br>
</div>
</div>
</body>
</html>
You have to wait for the DOM to finish loading before you can query it to find DOM elements and atach events.
The simplest fix would be placing your <script> at the end of body.
Another fix is to attach handlers in window onload event ( that's how it works in code snippet below)
In code snippet provided in question the the way window.onload was attached was unclear. Also at the end of script expression Palindrome(str); raised error as var str is undefined, so i've fixed it.
See working snippet below:
document.getElementById('submit').onclick = function(evt) {
checkInput();
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function(){
document.getElementById('submit').onclick = function(evt) {
checkInput();
};};
function checkInput() {
alert('Check input fired');
}//end check input
</script>
</head>
<body>
<div id="main">
<div id="form_layout">
<h2>Palindrome Test</h2>
<br>Enter a 10 character Palindrome.
<!-- Form starts here-->
<form name="pForm" id="pForm" method="post" >
<label>Palindrome:</label>:
<input type="text" name="uput" id="uput"/><br>
<!-- ... all the other stuff ... -->
</form><br>
<input type='submit' id="submit" value="Check Palindrome" /><br>
<p><span id="eMsg" class="error"></span><p/><br>
</div>
</div>
</body>
</html>

Highlight comment and remove class when delete button is clicked

I am new to web development and currently learning jQuery from codecademy.
I made a simple opinion pull.
Problem: Besides add comment, i would like to delete the comment when i highlight the comment and press trash button.
index.html
<!doctype html>
<html>
<head>
<!--Boostrap CSs stylesheet-->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!--jQuery script-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!--Bootsrap js-->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!--CSS stylesheet-->
<link href="index.css" media="screen" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<form>
<div class="form-group">
<textarea class="form-control status-box" rows="2" placeholder="What's on your mind?"></textarea>
</div>
</form>
<div class="button-group pull-right">
<p class="counter">140</p>
<div class= "glyphicon glyphicon-pencil" ></div>
<div class= "glyphicon glyphicon-trash" ></div>
</div>
<ul class="posts">
</ul>
</div>
<!--JavaScript script-->
<script src="index.js"></script>
</body>
</html>
index.css
html,body {
font-family: courier, sans-serif;
color: #404040;
background-color: #eee;
}
.container {
width: 520px;
margin-top: 20px;
}
.button-group {
margin-bottom: 20px;
padding: 5px;
}
.counter {
display: inline;
margin-top: 0;
margin-bottom: 0;
margin-right: 10px;
}
.posts {
clear: both;
list-style: none;
padding-left: 0;
width: 100%;
}
.posts li {
background-color: #fff;
border: 1px solid #d8d8d8;
padding-top: 10px;
padding-left: 20px;
padding-right: 20px;
padding-bottom: 10px;
margin-bottom: 10px;
word-wrap: break-word;
min-height: 42px;
}
index.js
var main = function() {
//btnPost
$('#btnPost').click(function() {
var post = $('.status-box').val();
$('<li>').text(post).prependTo('.posts');
$('.status-box').val('');
$('.counter').text('140');
$('#btnPost').addClass('disabled');
});
$('.status-box').keyup(function() {
var postLength = $(this).val().length;
var charactersLeft = 140 - postLength;
$('.counter').text(charactersLeft);
if(charactersLeft < 0) {
$('#btnPost').addClass('disabled');
}
else if(charactersLeft == 140) {
$('#btnPost').addClass('disabled');
}
else {
$('#btnPost').removeClass('disabled');
}
});
$('#btnPost').addClass('disabled');
//btnDelete
$('#btnDelete').click(function(){
});
}
$(document).ready(main);
I have created a fiddle to provide something close to the desired functionality. I'm not sure what you mean by "highlight" the comment, but what you are looking for is event delegation. Using jQuery's .on() function, you can listen for events on dynamically created elements:
$('body').on('click', '.btnDelete', function(){
$(this).closest('li').remove();
});
See this jsFiddle: http://jsfiddle.net/voveson/5gL44z6m/2/
And for more info on how the .on() function works, see here.

Button not clickable

I have created page that would allow the user to enter information then submit that to js for validation and modification of a database. The page should have a pop up that notifies the user is successful or not. The pop up is color coded for errors or informational messages.
However, it needs a way to remove the pop once the user acknowledges the message. There is a button on the pop up (div) that appears and had the event listener on the button but the button is not clickable.
The html code:
<div id="panel">
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/static/css/msd.css"></link>
<script src="/static/lib/d3-3.3.8.min.js"></script>
</head><div id="info-msg">
<p></p>
<button id="ok">Ok</button>
</div>
<div id="reportAnomaly" >
<table id="anomaly-table" cols="2">
<tr>
<td>
<input id="submit" type="submit" value="Submit">
</td>
<td>
<input id="reset" type="reset" value="Reset Form">
</td>
</tr>
</table>
</div>
</div>
</div>
<script src="static/js/dbanomaly.js"></script>
</body>
</html>
The JavaScript code:
var infoMsgDiv = d3.select("#info-msg");
d3.select("#submit").on('click', reportAnomaly);
d3.select("#reset").on('click', resetForm);
d3.select("#ok").on('click', resetForm);
function reportAnomaly() {
insertResults();
}
function insertResults () {
displayMessage('warn', "Successfully added.");
}
function resetForm () {
_log("resetForm");
infoMsgDiv.style("opacity", 0);
}
function displayMessage (level, message) {
_log("displayMessage");
if (level === 'crit') {
infoMsgDiv.style("background-color", "red");
} else if (level === 'warn') {
infoMsgDiv.style("background-color", "yellow");
}
infoMsgDiv.style("opacity", 1);
infoMsgDiv.select("p").html(message);
}
the CSS is:
#info-msg {
position: absolute;
top: 0;
box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
border: 1px solid #ddd;
border-radius: 10px;
font: 10pt sans-serif;
text-align: center;
line-height: 1.2em;
opacity: 0;
transition: opacity 500ms ease-in 250ms;
pointer-events: none;
color: black;
}
#info-msg{
top: 50%;
left: 50%;
padding: 10px;
background-color: #FFFF9F;
}
Any ideas why the "#ok" button would not be clickable?

Create separate js file for inclusion

I have a html file in which currently resides all my javascript code. I want to make a separate .js file, put all the javascript code in that and include that in my .html file. I tried doing it, and also removed the opening/closing tags in the .js file and put this line in .html file -
<script type='text/javascript' src="myfile.js"></script>
However, this is not working. Any ideas on what's wrong?
Thanks in advance.
---------------------EDIT-----------------------------
<html>
<title>Process Details</title>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="myfile.js">
</script>
<style type="text/css">
body { font-size: 80%; font-family: 'Lucida Grande', Verdana, Arial, Sans-Serif; }
ul#tabs { list-style-type: none; margin: 30px 0 0 0; padding: 0 0 0.3em 0; }
ul#tabs li { display: inline; }
ul#tabs li a { color: #42454a; background-color: #dedbde; border: 1px solid #c9c3ba; border-bottom: none; padding: 0.3em; text-decoration: none; }
ul#tabs li a:hover { background-color: #f1f0ee; }
ul#tabs li a.selected { color: #000; background-color: #f1f0ee; font-weight: bold; padding: 0.7em 0.3em 0.38em 0.3em; }
div.tabContent { border: 1px solid #c9c3ba; padding: 0.5em; background-color: #f1f0ee; }
div.tabContent.hide { display: none; }
.heading { font-size:110%; font-family:'Century Schoolbook'; color: maroon; }
.data { font-size:110%; font-family:'Century Schoolbook'; color:black; }
</style>
</head>
<body onload="init()">
<center>
<font face='Calibri' size='3' color='Blue'>PID : </font>
<select id='list' onchange="refreshData()">
</select>
<form>
<input type="button" id="Refresh" onclick="refreshPage()" value="Refresh Data"/>
</form>
</center>
<ul id="tabs">
<li>Memory</li>
<li>Thread</li>
<li>Summary</li>
</ul>
<div class="tabContent" id="memory">
<table id="graphtab" align="center">
<tr>
<td id="heap" align="center"></td>
<td id="nonheap" align="center"></td>
</tr>
<tr>
<td id="resident" align="center"></td>
<td id="pagefaults" align="center"></td>
</tr>
</table>
</div>
<div class="tabContent" id="thread">
<table id="threadtab" align="center">
<tr>
<td id="cpuusage" align="center"></td>
<td id="count" align="center"></td>
</tr>
<tr>
<td id="threadlist" align="center"></td>
<td id="threaddets" align="center"></td>
</tr>
</table>
</div>
<div class="tabContent" id="summary">
</div>
Home Page
</body>
</html>
Use http protocol instead of https. Using https throws a GET exception in Chrome but not Firefox.
And your <title> should be inside the <head> tag.

Categories