Uncaught ReferenceError: load is not defined - javascript

I'm making a site that, depending on the user's time of the day, will show a night, afternoon or morning image.
But as it seems, the JS isn't working due to a Syntax Error on calling the function with "onload=" in the tag <body>. My VS Code Javascript higlighter isn't working on the words window, document nor getElementById.
Which part of my JS could be wrong?
Here's the HTML
<!DOCTYPE html>
<html lang="pt-br">
<head>
<script type="javascript" src="/script.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie-edge">
<link rel="stylesheet" href="/style.css">
</head>
<body onload="load()">
<section>
<div id="msg">
Message here
</div>
<div id="foto">
<img id="image" src="img/afternoon.png">
</div>
</section>
<footer>
<p>© Koala</p>
</footer>
</body>
</html>
And here's the JS
function load(){
var msg = window.document.getElementById('msg');
var img = window.document.getElementById('image');
var dt = new.Date();
var hour = dt.getHours();
msg.innerHTML = 'Now it is ${hour} hours.';
if (hour>= 0 && hour < 12) {
img.src = 'img/morning.png';
} else if (hour => 12 && hour < 18) {
img.src = 'img/afternoon.png';
} else {
img.src = 'img/night.png';
}
}
PS: I've tried running it on Mozilla and Chrome. No success.

The error appears to be with this line:
var dt = new.Date();
To instantiate a new Date object, you need to use this syntax:
var dt = new Date();
Once this syntax error is fixed, then the JS file should be loaded properly and then the onload attribute will be able to fire the load function.
Here's a working demo: https://codesandbox.io/s/stack-overflow-onload-8opgp?file=/script.js

Related

Random Image selector from folder

I'm a student working on an art project in which I select one of 500 created images to show up on a webpage. I'm very new to coding and only really understand html and css, with very small amount of knowledge in JavaScript. I'm stuck in getting the images to show up, when I inspect it gives me an error saying: Failed to load resource: net::ERR_FILE_NOT_FOUND $selected_image}< I'm not really sure what to do with this, I hope someone would like to help me with this.
Thankyou :)
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" media="screen" href="css/main.css">
<!-- <link rel="JavaScript" href="script.js"> -->
<meta charset='utf-8'>
<meta content='IE=edge,chrome=1' http-equiv='X-UA-Compatible'>
<title>Mother</title>
<body>
<div id="container">
<div id="inner_container">
<img id="image_shower"/>
</div>
<div id="button_container">
<button onclick="get_random_image()"></button>
</div>
</div>
<script>
image_array = [
'Lilith10.png',
'Lilith11.png',
'Lilith12.png',
'Lilith13.png',
'Lilith14.png']
function get_random_image(){
random_index = Math.floor(Math.random() * image_array.lenght);
selected_image = image_array[random_index]
document.getElementById('image_shower').src = './images/$selected_image}'}
</script>
</body>
</html>
Javascript template strings are written with oblique quotes, and variables inside it must have brackets around them (you only had the closing one):
document.getElementById('image_shower').src = `./images/${selected_image}`;
EDIT
Even if in the present case this won't stop your code from working (unless you activate "strict mode"), I also recommend that you use the appropriate keywords to declare your variables.
const image_array = [
'Lilith10.png',
'Lilith11.png',
'Lilith12.png',
'Lilith13.png',
'Lilith14.png'
];
function get_random_image() {
const random_index = Math.floor(Math.random() * image_array.length);
const selected_image = image_array[random_index];
document.getElementById('image_shower').src = `./images/${selected_image}`;
}

Firefox not executing JavaScript files that were loaded dynamically

I'm trying to load two scripts that were functionally deferred on account of their type attributes being non-standard i.e. text/javascript/defer. Doing this causes the parser to ignore them so I want to reload them using JavaScript.
My HTML is as below:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>No Title</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript/defer" src="assets/js/test3.js"></script>
<script type="text/javascript/defer" src="assets/js/test4.js"></script>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script>
$(document).ready(function(){
var defer_js_collection_obj = $("[type='text/javascript/defer']"),
el_head_rq_obj = $('head'),
el_head_obj = el_head_rq_obj[0]
;
if(defer_js_collection_obj.length > 0)
{
//Reload JavaScript
defer_js_collection_obj.each(function() {
var file_src_outer_html_str = this.outerHTML;
var file_src_res_arr = file_src_outer_html_str.match("src *\= *[\"\']{1}(.*?)[\"\']{1}");
var file_src_str = file_src_res_arr[1];
var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file_src_str);
document.getElementsByTagName("head")[0].appendChild(fileref);
});
//Unload JavaScript with defer tag
for(var j = defer_js_collection_obj.length-1; j >= 0; j--)
{
defer_js_collection_obj[j].parentNode.removeChild(defer_js_collection_obj[j]);
}
}
});
</script>
</head>
<body>
<div>Load Deferred JavaScript</div>
</body>
</html>
jquery.js is version 1.11.2. test3.js and test4.js reference the javascript files I want to load, and they contain console.log('test3.js is loaded'); and console.log('test4.js is loaded'); respectively.
The issue I'm having is that this script works virtually everywhere else except on Firefox. I'm on a Mac OS X 10.10.5 using Firefox 46.0.1, and I don't see the console.log message when I load the script.
How can I fix this?
It might be a mime type issue. Do you happen to see any message in the console stating "not well-formed"? In any case, this seemed to work for me and I agree that your code did not work in FF when I first tried it.
$(document).ready(function(){
console.log("main");
var $body = $($("body")[0]);
var $scripts = $("[type='text/javascript/defer']");
$scripts.each(function(){
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", $(this).attr("src"));
$body.append(scriptTag);
});
});
Try to append your script at the end of body, so instead do:
document.getElementsByTagName("body")[0].appendChild(fileref);

Calling .jSignature() on div doesn't update the div

I got this code from the GitHub:
<script src="path/to/jSignature.min.js"></script>
<script>
$(document).ready(function() {
$("#signature").jSignature()
})
</script>
<div id="signature"></div>
But it doesn't pull anything up on the actual webpage. I would think there is more code required but I don't know where to start.
Here is a minimal working example
<!DOCTYPE html>
<html lang="en">
<head>
<lang>
<title>Minimal working jSignature Example</title>
<meta charset="UTF-8">
<!-- Files from the origin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://willowsystems.github.io/jSignature/js/libs/jSignature.min.js"></script>
<head>
<script>
$(document).ready(function() {
// Initialize jSignature
$("#signature").jSignature();
})
// ripped from the description at their the Github page
function getBase64Sig(){
// get the element where the signature have been put
var $sigdiv = $("#signature");
// get a base64 URL for a SVG picture
var data = $sigdiv.jSignature("getData", "svgbase64");
// build the image...
var i = new Image();
i.src = "data:" + data[0] + "," + data[1];
// and put it somewhere where the sun shines brightly upon it.
$(i).appendTo($("#output"));
}
</script>
<body>
Put your signature here:
<div id="signature"></div>
<button onclick="getBase64Sig()">Get Base64</button>
<div id="output"></div>
</body>
</html>
I hope you can go on from here.
It is really as simple as they describe it to be, only their description of the actual example is a bit lacking for beginners.

Error occurred in Chrome but not Firefox

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>a demo page</title>
</head>
<body>
<script>
var formatNum=function(num)
{
if(!/^(\+|-)?\d+(\.\d+)?$/.test(num)){
return num;
}
var re = new RegExp().compile("(\\d)(\\d{3})(,|\\.|$)");
num += "";
while(re.test(num))
num = num.replace(re, "$1,$2$3")
return num;
}
alert(formatNum(1000000));
</script>
</body>
</html>
i use these codes to fomat number look like this 1,000,000 it works well in firefox , but not work in chrome
here is the error shows in chrome Uncaught TypeError: Cannot call method 'test' of undefined
how can i resolve this error
The RegExp().compile() method is deprecated.
Why don't you use your regex like this -:
var regexp = new RegExp("(\\d)(\\d{3})(,|\\.|$)");
It's deprecated, and not working in firefox too. Maybe your version is an old one.
Deprecated and obsolete features
Use #Raoul's suggestion.
Try with this
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>a demo page</title>
</head>
<body>
<script>
var formatNum=function(num)
{
if(!/^(\+|-)?\d+(\.\d+)?$/.test(num)){
return num;
}
var re = new RegExp();
re.compile("(\\d)(\\d{3})(,|\\.|$)");
num += "";
while(re.test(num))
num = num.replace(re, "$1,$2$3")
return num;
}
alert(formatNum(1000000));
</script>
</body>
</html>
Reason is chrome doesn't return a reference to the compiled RegExp object when calling compile().
So this line var re = new RegExp().compile("(\\d)(\\d{3})(,|\\.|$)"); will not work instead a less flexible version needs to be followed.
var re = new RegExp();
re.compile("(\\d)(\\d{3})(,|\\.|$)");

grid 960 - while executing inspectSection in dmx960 grid, js error occurred.

I'm trying to run this grid extention in DW CS5. I'm a front end person so debugging other people's code isn't my thing. So when I try set the grid precepts I get this error:
while executing inspectSection in dmx960 grid, js error occurred.
Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Barefoot Development Group</title>
<link href="CSS/Style.css" rel="stylesheet" type="text/css">
<link href="CSS/text.css" rel="stylesheet" type="text/css">
<link href="CSS/reset.css" rel="stylesheet" type="text/css">
</head>
<body>
<!------start container------->
<div id = "container" class ="container_16"></div>
<div id = "social_search" class = "grid_16"></div>
<div id = "social_links" class = "grid_1 alpha"></div>
<!------Main container-------->
<!------Header start---------->
<!------Social Links---------->
<!-------End social links------>
<!----start Social icons -------->
<!----end social icons----->
</body>
</html>
I tried deleting the cache in Config folder and reinstalling the extension. Didn't work. I checked the log files and found this:
JS Error: theElem.getAttribute is not a function filename:
C:\Users\cvr\AppData\Roaming\Adobe\Dreamweaver
CS5\en_US\Configuration\Shared\DMXzone\960 Grid\dmx960grid_lib.js
lineno: 598
So I went to the JS file and here is what I found in this expression block:
function getGridClassNum(theElem) {
if (!theElem) return 0;
var cls = theElem.getAttribute("class");
if (!cls) return 0;
if (cls == 'clearfix') {
//Try to read the parent
var parent = getGridElement(theElem.parentNode);
if (parent && parent.nodeType === Node.ELEMENT_NODE) {
return getGridClassNum(parent);
}
} else {
var numMatch = cls.match(new RegExp("\\b(grid|container)_(\\d+)\\b"));
if (numMatch && numMatch.length > 1) {
return parseFloat(numMatch[2]);
// //decrease with prefix and suffix
// - getGridClassNameNum(theElem, 'prefix')
// - getGridClassNameNum(theElem, 'suffix');
}
}
return 0;
}
I don't see anything particularly amiss here. But perhaps a more expert debugger can tell me if there is something going on here. Here is what confuses me - I was looking for the function inspectSection but I couldn't find it. I'm left scratching my head here.
Could this be a problem of including the script directly into the html doc?
Thanks!

Categories

Resources