javascript error 'cannot read property of undefined' - javascript

The javascript, html and css work in this jsfiddle
but when entered into an html file like so:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
var target = $(".mypara").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
alert("made it!");
clearInterval(interval);
}
}, 250);
</script>
<style>
body {
background-color: linen;
height: 1000px;
}
p {
color: blue;
margin-top: 500px;
}
</style>
</head>
<body>
<p class="mypara">asdfasdfasf</p>
</body>
</html>
chrome console gives this error
Uncaught TypeError: Cannot read property 'top' of undefined(anonymous function) # index - Copy.html:8
This error refers to line 8:
var target = $(".mypara").offset().top;
Can someone help me understand why?

Wrap your code in
$(document).ready (function (){
// code here
});
You're trying to access an element in the DOM before it exists so when your trying to access the class the item doesnt exist yet. Or move your script below the elements in the html
Works in fiddle cause thet wrap you're code depending on your setting which defaults to domready I believe

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<style>
body {
background-color: linen;
height: 1000px;
}
p {
color: blue;
margin-top: 500px;
}
</style>
</head>
<body>
<p class="mypara">asdfasdfasf</p>
<p class="mypara">Include js files to be at the bottom so that it would be the one to be loaded accordingly</p>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
// if document is ready then
// its the only time to execute
// process withing the block
$(document).ready(function() {
var target = $(".mypara").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
alert("made it!");
clearInterval(interval);
}
}, 250);
});
</script>
</body>
</html>

Related

How can I get a div to change its background-image after a specific event has taken place?

I have made a game using JavaScript and I would like the background to change after the game is over or after isGamerOver = true to be more specific. Here is what I currently have. Right now when ever the game ends I get a Uncaught TypeError: Cannot read property 'style' of null.
function gameOver() {
console.log('game over')
isGamerOver = true
while (grid.firstChild) {
grid.removeChild(grid.firstChild)
}
grid.innerHTML = score
clearInterval(upTimerId)
clearInterval(downTimerId)
clearInterval(leftTimerId)
clearInterval(rightTimerId)
if(isGamerOver = true){
document.getElementById("grid").style.backgroundImage="url('backgrounds/background-up.png')";
}else{
document.getElementById("grid").style.backgroundImage="url('backgrounds/game-over.png')";
}
}
Here is the style sheet I am trying to change
.grid {
width: 400px;
height: 600px;
background-image: url(backgrounds/background-up.png);
position: relative;
font-size: 100px;
text-align: center;
color: #fff;
}
Here Is my HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>100% Not Doodle Jump</title>
<link rel="stylesheet" href="style.css"></link>
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<div class="grid"></div>
</body>
</html>
I also added a div in JavaScript
const grid = document.querySelector('.grid')
const doodler = document.createElement('div')
If you got your grid defined like that:
const grid = document.querySelector('.grid')
change this:
if(isGamerOver = true){
document.getElementById("grid").style.backgroundImage="url('backgrounds/background-up.png')";
}else{
document.getElementById("grid").style.backgroundImage="url('backgrounds/game-over.png')";
}
to this:
if(isGamerOver = true){
grid.style.backgroundImage="url('backgrounds/background-up.png')";
}else{
grid.style.backgroundImage="url('backgrounds/game-over.png')";
}

File won't open in Chrome or Firefox, file name in URL changes to "0"

I tried searching for "file name changes to 0 in browser" both in Google and here, but got nowhere. This is a simple file which suddenly stopped opening. I can't even get at the inspector to troubleshoot it. Undo/redo history is lost, so that will not help. I'm guessing it's a simple mistake, but I have NEVER seen this before.
<!doctype html>
<html lang="en">
<head>
<title>JS Animated Navigation Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
<!--
var location = 0;
var bar = document.getElementById("bar1");
function myMove()
{
// if (id != 0) clearInterval(id);
location = -144;
// if (location != -144) return; // don't execute onmouseover while previous onmouseover is still running.
id = setInterval(move, 1);
}
function move()
{
location++;
bar.style.left = location + 'px';
if (location == 300)
{
clearInterval(id);
id = setInterval(moveback, 1);
}
}
function moveback()
{
location--;
bar.style.left = location + 'px';
if (location == -144)
{
clearInterval(id);
// id = setInterval(move, 1);
}
}
-->
</script>
<style>
#container
{
width: 600px;
height: 100px;
position: relative;
background: white;
}
#bar1
{
width: 150px;
height: 30px;
position: absolute;
left: -144px;
background-color: white;
}
</style>
</head>
<body>
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="container">
<div id ="animate"><img src="imageGalleryBar.png" alt="Image Gallery" width="150" height="30" id="bar1" onmouseover="myMove()" /></div>
</div>
</body>
</html>
Thank you
You can't use the variable name location as it is a reserved word; what you're actually doing is setting the window.location variable to 0.
Rename it, or put it in a namespace or object.

SetTimeout executing but no delay

I am developing a Binary Tree Search visualization program using JSAV library. The problem is that all the nodes are getting highlighted instantly and I want to show it step by step without any pressing of button again and again.
I tried to highlight a node and use timeout function to stop the execution for few seconds and then unhighlight the node and then proceed with next selected node, however there is no effect at all. Can anybody suggest me what can I do to modify my program to incorporate this type of feature?
Code: (Uses JSAV library)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/JSAV.css" type="text/css" media="screen" title="no title" charset="utf-8" />
<title>Test Binary Tree Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="lib/jquery.transit.js"></script>
<script src="lib/raphael.js"></script>
<script src="lib/JSAV.js"></script>
<Script src="lib/includeall.js"></Script>
<style>
.highlight
{
background-color: blue;
}
.unhighlight
{
background-color: white;
}
#av {
width: 98%;
position: relative;
}
.jsavcounter {
position: absolute;
top: 15px;
}
.jsavtree {
position: relative;
width: 500px;
height: 300px;
}
svg {
height: 600px;
}
path {
pointer-events: visible;
}
</style>
</head>
<body>
<div id="av">
</div>
<script>
var jsav=new JSAV("av");
var bt=jsav.ds.binarytree();
addNode(bt,20);
addNode(bt,5);
addNode(bt,40);
addNode(bt,50);
addNode(bt,60);
addNode(bt,70);
addNode(bt,4);
function donothing()
{
}
function searchBinarytree()
{
var value=parseInt(document.getElementById("value").value);
var test=bt.root();
while(test!=null)
{
test.addClass("highlight");
setTimeout(donothing,20000);
if(test.value()==value)
{
break ;
}
if(test.value()<=value)
{
test.toggleClass("unhighlight");
test=test.right();
}
else
{test.toggleClass("unhighlight");
test=test.left();
}
bt.layout();
}
}
</script>
<div id="valuebox">
Value to search:<input id="value" type="text"> <button type="button" onclick="searchBinarytree()"> Search</button>
</div>
</body>
</html>
setTimeout is calling donothing which is "doing nothing". You should instead call the function you want repeated from within setTimeout. I assume you expect it to pause at that call, but that's not how setTimeout works. More info can be found at https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
Something like this should work (not tested)
var test;
function searchBinarytree() {
test = bt.root();
test.addClass("highlight");
setTimeout(updateNode, 20000);
}
function updateNode() {
var value = parseInt(document.getElementById("value").value);
if (test != null) {
if (test.value() != value) {
test.removeClass("highlight");
if (test.value() <= value) {
test = test.right();
} else {
test = test.left();
}
if (test != null) {
test.addClass("highlight");
}
setTimeout(updateNode, 20000);
}
bt.layout();
}
}
Not really sure that it's your issue but:
When you use setTimeout use it like that
setTimeout(yourFunction, timeout);
not
setTimeout(yourFunction(), timeout);
you have to pass the function to be invoked, you don't invoke the function

Why isn't importNode executing when everything is fine?

I want to use HTML import so I created two files.
File1:
<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 300px;
width: 300px;
background-color: yellow;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
File2:
<!DOCTYPE html>
<html>
<head>
<link rel='import' href='test.html' id='LINK'>
<script>
var LINK = document.getElementById('LINK');
var test = LINK.import;
var content = document.importNode(test.content, true);
document.body.appendChild(content);
</script>
</head>
<body>
</body>
</html>
I should see a yellow square when I execute File2 but instead I'm getting this error:
Uncaught TypeError: Failed to execute 'importNode' on 'Document': parameter 1 is not of type 'Node'.
at Import.html:8
When I log the "test" variable to the console, I am getting the document that contains File1 so it's fine there. I just don't get what the error is supposed to mean and why it's not working.
When you write:
var content = document.importNode(test.content, true);
...you suppose that test is a <template> element.
So in the document you import, you should have a <template> element.
test.html:
<html>
<head>
<style>
div {
height: 300px;
width: 300px;
background-color: yellow;
}
</style>
</head>
<body>
<template><div></div></template>
</body>
</html>
In the main file, use querySelector() (or another selector function) to get the template:
var LINK = document.getElementById('LINK');
var test = LINK.import.querySelector('template');
var content = document.importNode(test.content, true);
...

how to get the cssText of external style?

I have tried hours to get the results, but failed, below, I will post all I have done, hope I can get some tips, BTW,Thanks.
from the error message, yeah It's cssRules is null, surely error!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="index.css">
<title>css style</title>
<style type="text/css">
#demo {
font-size: 10px; /*first css rule */
}
p {
border: 1px solid green; /*second one*/
}
</style>
</head>
<body>
<div id="demo" style="color: red;">
<p>how to access of document's css!</p>
</div>
</body>
external css
#demo {
font-weight: 900;
}
p {
padding: 20px;
}
Javascript
<script>
/*1,to get the inline style, this maybe the most easy one*/
var cssInline = document.getElementById('demo').style;
var cssInText = cssInline.cssText, cssColor = cssInline.color;
console.log(cssInText, cssColor);
/*2.a to get the style in head*/
var cssInHeada = document.getElementById('demo');
// using the computed css of inline
var cssHeadText = getComputedStyle(cssInHeada, null);
console.log(cssHeadText);
// 2.b to get the style directly
var cssInHeadb = document.getElementsByTagName('style')[0];
console.log(cssInHeadb.textContent);
// 2.c or like this
var cssInHeadc = document.styleSheets[1];
console.log(cssInHeadc.cssRules[0].cssText); //per rule
/*3, but I cant get the extenal style*/
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
</script>
Thank your guys!
I suspect your JavaScript is running before the stylesheet is loaded. Try this:
document.addEventListener('DOMContentLoaded', function () {
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
}, false);
Or if you happen to be using jQuery, this is more universal:
$('document').ready(function(){
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
});
Update: another possibility is that you're using Chrome and either loading the CSS cross-domain or using the file:// protocol. This appears to be a known issue and is not considered a bug.

Categories

Resources