Simple Javascript error that is driving me insane - javascript

This is driving me nuts. I have put the html and javaScript code below. Whenever I refresh my page I get Uncaught TypeError: screen.addEventListener is not a function. I insert any other variable or ID for screen and it works fine.
HTML Code
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
<link rel="stylesheet" href="css/reset/reset.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="calculator">
<div id="screen">
</div>
<div id="layout">
<ul id="first-row" class="btn-row">
<li><button>C</button></li>
<li><button>=</button></li>
</ul>
<ul id="sec-row" class="btn-row">
<li><button>7</button></li>
<li><button>8</button></li>
<li><button>9</button></li>
<li><button>+</button></li>
</ul>
<ul id="third-row" class="btn-row">
<li><button>4</button></li>
<li><button>5</button></li>
<li><button>6</button></li>
<li><button>-</button></li>
</ul>
<ul id="fourth-row" class="btn-row">
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
<li><button>*</button></li>
</ul>
<ul id="fifth-row" class="btn-row">
<li><button>0</button></li>
<li><button>/</button></li>
</ul>
</div>
</div>
<script src="js/app.js">
</script>
</body>
</html>
JavaScript Code
var screen = document.getElementById('screen');
var btn = document.getElementsByTagName('button');
var clear = btn[0];
var equals = btn[1];
var seven = btn[2];
clear.addEventListener('click', here);
screen.addEventListener('click', function(){
alert('wth');
});

You have a naming issue. It is clashing with the window.screen object
console.log(window.screen);
MDN window.screen
Rename the variable to something else and it works fine.
var screenX = document.getElementById("screen");
screenX.addEventListener("click", function() { alert("x"); });
<div id="screen">Click</div>
or take it out of global scope
(function () {
var screen = document.getElementById("screen");
screen.addEventListener("click", function() { alert("x"); });
}());
<div id="screen">Click</div>

Related

Change loaded content in an HTML file with javascript

Some content, in this case a navbar (navbar.php), is loaded into the index.html by Javascript. Now I want to change a navbar list item from "Home" to "Something else" using Javascript. But it seems that the script can not see the loaded content. The console gives an „document.getElementById(...) is null“ error. Following the code:
index.html
<!DOCTYPE html>
<html lang="de">
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$("#navbar").load("navbar.php");
return false;
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<header>
<div id="navbar">
</div>
</header>
<main>
</main>
<footer>
</footer>
<script>
let myChange = document.getElementById("change").innerHTML;
myChange = "<a href='somethingelse.html'>Something else</a>";
</script>
</body>
</div>
</div>
</html>
navbar.php
<div>
<ul>
<li id="change">Home</li>
<li >Logout</li>
</ul>
</div>
Any idea what is wrong in the code?
Thanks a lot in advance.
You would need to use the load's callback function for load to know when the content has been added to the document.
$("#navbar").load("navbar.php", function() {
const myChange = document.getElementById("change");
myChange.innerHTML = "<a href='somethingelse.html'>Something else</a>";
});

Javascript - Redirect if the value in a input box is correct

I have a problem, I'm doing a little game and I made a level, where you just have to change the level number to go to the next level, but when the correct value is sent it's supposed to redirect to the next level but it doesn't work ...
function getVal() {
var nmb = document.getElementById('input').value;
var element = document.getElementById('input');
element.addEventListener('keyup', function(event) {
if(nmb == 3) {
document.location.href = "aw3za.html"; //If the value is correct it redirects to the level 3
}
else {
document.location.href = "2ksdkwa.html"; //If the value isn't correct it stays on the level 2
}
})
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>RodrigueSS 2 | Level 2</title>
<link rel="stylesheet" href="assets/style/level_template.css">
<link rel="stylesheet" href="assets/style/level2_style.css">
<script src="https://kit.fontawesome.com/57d547920e.js" crossorigin="anonymous"></script>
<script src="assets/script/level2.js"></script>
<script type="text/javascript" src="assets/script/jquery-3.4.1.js"></script>
</head>
<body>
<header>
<div class="prev-page-container">
<img class="prev-page-arrow" src="assets/img/prev-arrow.svg" alt="Back arrow">
</div>
</header>
<!--This is the interesting part--------->
<div class="level-number-wrapper"></div>
<div class="level-number-container">
<form method="GET" name="form1">
<input onclick="getVal()" id="input" name="numbox1" class="level-number" type="number">
</form>
</div>
</div>
<!--------------------------------------->
<footer>
<div class="media-container">
<ul>
<li><a class="media-link" href="https://www.instagram.com/r_dr_go/"><i class="fab fa-instagram"></i></a></li>
<li><a class="media-link"href="https://twitter.com/Rodrigu40035063"><i class="fab fa-twitter"></i></a></li>
<i class="fas fa-arrow-right"></i>
</ul>
</div>
</footer>
</body>
</html>
To the people that have this problem, Here is the JS, I put a window.onload, it means that it only launch when the page is completely loaded :
window.onload = function() {
document.getElementById('input').addEventListener('keyup', function(event) {
if(document.getElementById('input').value == 3) {
window.location.href = "aw3za.html"
}
})
}
document.location has been deprecated for almost as long as JavaScript has existed. Don't use it So use window.location
function getVal() {
var nmb = document.getElementById('input').value;
var element = document.getElementById('input');
element.addEventListener('keyup', function(event) {
if(nmb == 3) {
window.location = "aw3za.html"; //If the value is correct it redirects to the level 3
}
else {
window.location = "2ksdkwa.html"; //If the value isn't correct it stays on the level 2
}
})
}
I don't understand why you need trigger onClick function on input box. that function only execute when you click on that. So when you clicking that value is empty. then when you try to perform keyup the value will be empty. Actually you can use document.location.href.
Problem is your arrangement. Try this
var element = document.getElementById('input');
element.addEventListener('keyup', function(event) {
var nmb = document.getElementById('input').value;
if(nmb == 3){
console.log('in');
document.location.href = "new.html";
}
})
<div class="level-number-wrapper">
<div class="level-number-container">
<form method="GET" name="form1">
<input id="input" name="numbox1" class="level-number">
</form>
</div>
</div>
Several things here:
First you have an extra div closing in the interesting part of your code here:
<div class="level-number-wrapper"></div>
you should erase it.
Second, you don't need to use the function getVal() to add an event listener, you should add it directly.
Last, if you are staying in the same page if unless you change the value to 3 then you don't need the else part of the if.
This being said, this code works for me, check it out:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>RodrigueSS 2 | Level 2</title>
<link rel="stylesheet" href="assets/style/level_template.css">
<link rel="stylesheet" href="assets/style/level2_style.css">
<script src="https://kit.fontawesome.com/57d547920e.js" crossorigin="anonymous"></script>
<script src="assets/script/level2.js"></script>
<script type="text/javascript" src="assets/script/jquery-3.4.1.js"></script>
</head>
<body>
<header>
<div class="prev-page-container">
<img class="prev-page-arrow" src="assets/img/prev-arrow.svg" alt="Back arrow">
</div>
</header>
<!--This is the interesting part--------->
<div class="level-number-wrapper">
<div class="level-number-container">
<form method="GET" name="form1">
<input id="input" name="numbox1" class="level-number" type="number">
</form>
</div>
</div>
<!--------------------------------------->
<footer>
<div class="media-container">
<ul>
<li><a class="media-link" href="https://www.instagram.com/r_dr_go/"><i class="fab fa-instagram"></i></a></li>
<li><a class="media-link"href="https://twitter.com/Rodrigu40035063"><i class="fab fa-twitter"></i></a></li>
<i class="fas fa-arrow-right"></i>
</ul>
</div>
</footer>
<script>
document.getElementById('input').addEventListener('keyup', function(event) {
if(document.getElementById('input').value == 3) {
document.location.href = "aw3za.html"
}
})</script>
</body>
</html>
I think you can use both location and window but window is a bit better for cross browser safety as stated here:
What's the difference between window.location and document.location in JavaScript?
window.open
Calling window.open function in the listener had made the browser open the tab.
Here is the working code:
1. index.html
<!DOCTYPE html>
<html>
<body>
<div class="level-number-wrapper">
<div class="level-number-container">
<form method="GET" name="form1">
<input id="input" name="numbox1" class="level-number" type="number">
</form>
</div>
</div>
<script>
document.getElementById('input').addEventListener('keyup', function(event) {
if(document.getElementById('input').value == 3) {
window.open("aw3za.html")
}
})</script>
</body>
</html>
2. aw3za.html
<!DOCTYPE html>
<html>
<head>
<title> Level 2</title>
</head>
<body>
<h1>AW3ZA</h1>
</body>
</html>
Try to replace
document.location.href
By
window.location

Javascript variable's value not changing

I am making a website and trying to change the value of active car variable which doesn't change even after click on the division the value of activecar remains as .blueimg only even after clicking on the divisions
What is incorrect?
actions.js file
var activecar=".blueimg";
$(".redimg").hide();
$(".greyimg").hide();
$(".silverimg").hide();
$(".red").click(function(){
hideshow(".redimg",activecar);
});
$(".blue").click(function(){
hideshow(".blueimg",activecar);
});
$(".grey").click(function(){
hideshow(".greyimg",activecar);
});
$(".silver").click(function(){
hideshow(".silverimg",activecar);
});
function hideshow(colour,activecar) {
console.log("before");
console.log(activecar);
$(activecar).hide();
$(colour).show();
activecar = colour;
console.log("After");
console.log(activecar);
}
This is my index.html file
<!doctype html>
<html lang="en">
<head>
<title>CollegeDunia</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<img src="./assets/blue.jpg" class="blueimg"/>
<img src="./assets/red.jpg" class="redimg"/>
<img src="./assets/grey.jpg" class="greyimg"/>
<img src="./assets/silver.jpg" class="silverimg"/>
<div>
<a class="blue">Blue</a>
</div>
<div >
<a class="grey"> Grey</a>
</div>
<div >
<a class="red">Red</a>
</div>
<div >
<a class="silver">Silver</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="actions.js"></script>
</body>
</html>
change function's parameter name. It has same name with your global variable.
function hideshow(colour, car) { //activecar changed to car

Element.insertAdjacentHTML() API throws error in chrome 55.0.2883.87

I found the explaination about the API here, which tells me the second parameter is a string.
It's perform normal in firefox. However, in chrome, it shows the errors below:
I just curious about what makes this? Is it because the api is still stay Working Draft status and different browsers do the different implementation?
The following is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div">
<ul>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
</ul>
</div>
<script>
//normal
// var pTag=document.createElement("p");
// div.insertAdjacentElement("beforeend",pTag);
//throw error:
// Uncaught TypeError: Failed to execute 'insertAdjacentElement' on 'Element': parameter 2 is not of type 'Element'.
var txt = "<p>testtest</p>";
div.insertAdjacentElement("beforeend",txt);
</script>
</body>
</html>
Just Change div.insertAdjacentElement to div.insertAdjacentHTML:
<!-- <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Coding revoltion</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="parent">
<ul class="ul"></ul>
</div>
<script src="dom.js"></script>
</body>
</html>
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div">
<ul>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
<li>xxx</li>
</ul>
</div>
<script>
//normal
// var pTag=document.createElement("p");
// div.insertAdjacentElement("beforeend",pTag);
//throw error:
// Uncaught TypeError: Failed to execute 'insertAdjacentElement' on 'Element': parameter 2 is not of type 'Element'.
var txt = "<p>testtest</p>";
div.insertAdjacentHTML("beforeend",txt);
</script>
</body>
</html>
The parameters are incorrect. The second parameter should be html element, in your case it's a string.
Your txt variable must be an element. You can try this :
var txt = document.createElement("p")
txt.innerHTML = "testtest";
div.insertAdjacentElement("beforeend",txt);
There are two methods to insert new block of elements :
insertAdjacentElement(position, element)
The second parameter should be an element and not html text.
E.g.
var newDiv = document.createElement('div');
newDiv.style.backgroundColor = 'white';
parentElement.insertAdjacentElement('beforeend',newDiv);
insertAdjacentHTML(position, text)
text is valid html text or xml.
e.g.
var newDiv = `<div>This is a new div</div>
<p> Hello !! </p>`;
parentDiv.addAdjacentHTML('beforeend',newDiv);
first create a new html element programatically var htmlObject = document.createElement('div'); then assign your string to newly created object htmlObject.innerHTML=htmlString;.
var htmlString = `<div class="item clearfix" id="income-${obj.id}">
<div class="item__description">${obj.descripiton}</div>
<div class="right clearfix">
<div class="item__value">${obj.value}</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>`
var htmlObject = document.createElement('div');
htmlObject.innerHTML=htmlString;
document.querySelector(".income__list").insertAdjacentElement('beforeend', htmlObject);
You can use either Obj.innerHTML or Obj.insertAdjacentHTML() if you want to continue with String HTML
const html = `
<li>enter code here
<div class="collapsible-header grey lighten-4">${ title }</div>
<div class="collapsible-body white">${ content }</div>enter code here
</li>
`;
PARENTELEMENT.insertAdjacentHTML('beforeend', html);
I have change div.insertAdjacentElement to div.insertAdjacentHTML:
and it will work for me

When I click the button, function doesn't get called [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
I'm new to JavaScript and JQuery, and I'm trying to figure out why my function doesn't get called when I press the button. My only clue is that the Firefox Console is showing TypeError: document.getElementById(...) is null. I found this example, which says "document.write will overwrite the entire DOM if it's called after the document has finished being parsed" and that's why it's happening. I took a look at my code, and I moved the button into my div tag and it's still happening. I also tried moving the button into it's own div tags. Compiler didn't seem to like syntax when I tried adding html tags where the button is. I'm not sure what I'm supposed to do to fix this.
I'm following this example for the function call on button click. Hopefully I'm applying it ok to my project.
This is my code:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>jQuery Michele Project</title>
<link href="css/skins/polaris/polaris.css" rel="stylesheet">
<link href="css/skins/all.css" rel="stylesheet">
<link href="css/demo/css/custom.css" rel="stylesheet">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/jquery.ui.core.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.js"></script>
<script src="js/icheck.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.input').iCheck({
checkboxClass:'icheckbox_polaris',
radioClass:'iradio_polaris',
increaseArea:'10%'
});
});
</script>
<script type="text/javascript">
// Returns an array with values of the selected (checked) checkboxes in "frm"
function getSelectedChbox(frm) {
// JavaScript & jQuery Course - http://coursesweb.net/javascript/
var selchbox = []; // array that will store the value of selected checkboxes
// gets all the input tags in frm, and their number
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
// traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true)
selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function() {
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
</script>
<style type="text/css">
ul {list-style-type: none}
img {padding-right: 20px; float:left}
#infolist {width:500px}
</style>
</head>
<body>
<form>
<div class="skin skin-line">
<div class="arrows">
<div class="top" data-to="skin-flat"></div>
<div class="bottom" data-to="skin-polaris"></div>
</div>
</div>
<div class="skin skin-polaris">
<div class="arrows">
<div class="top" data-to="skin-line"></div>
<div class="bottom" data-to="skin-futurico"></div>
</div>
<h3>Select Items for Column Headings</h3>
<dl class="clear">
<dd class="selected">
<div class="skin-section">
<h4>Live</h4>
<ul class="list">
<li>
<input tabindex="21" type="checkbox" id="polaris-checkbox-1">
<label for="polaris-checkbox-1">Checkbox 1</label>
</li>
<li>
<input tabindex="22" type="checkbox" id="polaris-checkbox-2" checked>
<label for="polaris-checkbox-2">Checkbox 2</label>
</li>
<li>
<input type="checkbox" id="polaris-checkbox-3" >
<label for="polaris-checkbox-3">Checkbox 3</label>
</li>
<li>
<input type="checkbox" id="polaris-checkbox-4" checked >
<label for="polaris-checkbox-4">Checkbox 4</label>
</li>
</ul>
</div>
<script>
$(document).ready(function(){
$('.skin-polaris input').iCheck({
checkboxClass: 'icheckbox_polaris',
radioClass: 'iradio_polaris',
increaseArea: '20%'
});
});
</script>
//$('#checkbox').prop('checked')
</dd>
</dl>
</div>
<div id="loading">
<input type="button" value="Click" id="btntest" />
</div>
</form>
</body>
</html>
The issue is you assign the click handler before the element is available in the DOM. To resolve, you should wrap it in a DOM ready function:
$(function(){
document.getElementById('btntest').onclick = function() {
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
});
Note: $(function(){ ... }); is a shortcut for $(document).ready(function(){ ... });
You're running document.getElementById('btntest') before that element exists. Put this script after your button on the page, not before it:
<script>
document.getElementById('btntest').onclick = function() {
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
</script>

Categories

Resources