Why is my span element not updating after function call? - javascript

The Problem
I'm following an intro to JS course on Udemy. The course section is updating a span element by calling a JS function from a separate JS file. I figured I might be linking the scripts in the wrong order, but switching the order does nothing. Also, I know the file paths are right since an alert() function works fine. The file with the functions is imported before the file that calls it.
Edit
I just realized that the console browser is giving me this error:
Uncaught TypeError: Cannot set properties of null (setting 'textContent')
at outputResult (vendor.js:15:35)
at app.js:5:1
I'm sure I'm making an obvious, rookie mistake. Any help diagnosing this would be appreciated.
Here's the HTML and JS files below. The 'vendor.js' file holds the functions, and 'app.js' calls them. I'm specifically trying to update the element with id='current-result' by calling the outputResult function located in 'vendor.js'. I'm expecting the element with that id to update to 10, as that is what I'm assigning to currentResult in app.js.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Basics</title>
<link
href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="assets/styles/app.css" />
<script type="text/javascript" src="/Users/sailormetz/Software Development/Javascript/JSCourseMaterials/basics-01-starting-project/assets/scripts/vendor.js">
</script>
<script type="text/javascript" src="/Users/sailormetz/Software Development/Javascript/JSCourseMaterials/basics-01-starting-project/assets/scripts/app.js">
</script>
</head>
<body>
<header>
<h1>The Unconventional Calculator</h1>
</header>
<section id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
</div>
</section>
<section id="results">
<h2 id="current-calculation">0</h2>
<h2>Result: <span id="current-result">0</span></h2>
</section>
</body>
</html>
Vendor.js
const currentResultOutput = document.getElementById('current-result');
const currentCalculationOutput = document.getElementById('current-calculation');
function outputResult(result, text) {
currentResultOutput.textContent = result;
currentCalculationOutput.textContent = text;
}
app.js
let currentResult = 0
currentResult = currentResult + 10
outputResult(currentResult, '')

You are importing the Vendor.js at the top of the html file.
Inside the Vendor.js file, you are trying to access document.getElementById('current-result') and document.getElementById('current-calculation'). Will this be available inside Vendor.js? No. Because these DOM elements will be available only once the DOM is loaded.
How to fix this?
You have to ensure that the DOM elements that you are trying to use are available while you are running the script
This can be fixed in two ways.
Option 1
Import Vendor.js at the bottom of body tag. This will loads the script file once the DOM has been loaded. So your dome elements with id 'current-result' and 'current-calculation' will be available inside Vendor.js file.
Like
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Basics</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="assets/styles/app.css" />
</head>
<body>
<header>
<h1>The Unconventional Calculator</h1>
</header>
<section id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
</div>
</section>
<section id="results">
<h2 id="current-calculation">0</h2>
<h2>Result: <span id="current-result">0</span></h2>
</section>
</body>
<!-- Import here -->
<script type="text/javascript"
src="/Users/sailormetz/Software Development/Javascript/JSCourseMaterials/basics-01-starting-project/assets/scripts/vendor.js">
</script>
<script type="text/javascript"
src="/Users/sailormetz/Software Development/Javascript/JSCourseMaterials/basics-01-starting-project/assets/scripts/app.js">
</script>
</html>
Option 2
Load scripts asychronously by ising async attribute in the script import. This will parse the script file only once the DOM content has been loaded.
Like
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Basics</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="assets/styles/app.css" />
<script type="text/javascript" async
src="/Users/sailormetz/Software Development/Javascript/JSCourseMaterials/basics-01-starting-project/assets/scripts/vendor.js">
</script>
<script type="text/javascript" async
src="/Users/sailormetz/Software Development/Javascript/JSCourseMaterials/basics-01-starting-project/assets/scripts/app.js">
</script>
</head>
<body>
<header>
<h1>The Unconventional Calculator</h1>
</header>
<section id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
</div>
</section>
<section id="results">
<h2 id="current-calculation">0</h2>
<h2>Result: <span id="current-result">0</span></h2>
</section>
</body>
</html>

Related

button onlick that i tried linking with my javascript doesn't seem to be working or highlighting orange on my vs code when i add the ""

i have tried everything in order to fix the issue and even looked at the video of the tutorial im learning from but can't seem to get it working crrectly. Even checked around the internet. i added the javascript code so you guys can see that i did define it. im new to all this so explaining it best you can would be greatly appreciated
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"></link>
<link rel="stylesheet" href="style.css">
<title>Javascript Your Age In Days</title>
</head>
<body>
<div class="container-1">
<h2>Challenge 1: Your Age In Days</h2>
<div class="flex-box-container-1">
<div>
<button class="btn btn-primary" onclick='ageInDays()'>Click Here</button>
</div>
<div>
<button class="btn btn-danger">Reset</button>
</div>
<div class="flex-box-container-1">
<div id="flex-box-container-1"></div>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
function ageInDays() {
let birthYear = prompt("what year were you born...Good friend?");
}
It not working because you are using in line script for the invocation of the ageInDays function, but the definition is in another file that has not loaded when the browser read the inline JS so there are two ways of fixing this.
Use an inline script so the JS is already on the browser same time as HTML like
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"></link>
<link rel="stylesheet" href="style.css">
<title>Javascript Your Age In Days</title>
</head>
<body>
<div class="container-1">
<h2>Challenge 1: Your Age In Days</h2>
<div class="flex-box-container-1">
<div>
<button class="btn btn-primary" onclick="ageInDays()">Click Here</button>
</div>
<div>
<button class="btn btn-danger">Reset</button>
</div>
<div class="flex-box-container-1">
<div id="flex-box-container-1"></div>
</div>
</div>
</div>
<script>
function ageInDays() { let birthYear = prompt("what year were you born...Good friend?"); }
</script>
</body>
</html>
handle everything in the script file
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"></link>
<link rel="stylesheet" href="style.css">
<title>Javascript Your Age In Days</title>
</head>
<body>
<div class="container-1">
<h2>Challenge 1: Your Age In Days</h2>
<div class="flex-box-container-1">
<div>
<button class="btn btn-primary" id="action">Click Here</button>
</div>
<div>
<button class="btn btn-danger">Reset</button>
</div>
<div class="flex-box-container-1">
<div id="flex-box-container-1"></div>
</div>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
and in the main.js
const button = document.getElementById('action');
button.addEventListener('click', function(){
let birthYear = prompt("what year were you born...Good friend?");
});
Add this to your script.js file, and remove onclick='ageInDays()' from your button.
let btn = document.querySelector(".btn-primary");
btn.addEventListener("click", ageInDays);
function ageInDays(){
//code to be executed when you clicked the button
}

Can't transfer an image element from one file to another

I'm trying to transfer an image element, which is hosted on the cloud, from one file to another but it's not working.
I tried to insert the image in the HTML when it loads but it's telling me that the image variable is null.
MY FIRST HTML FILE(source file)
<div class="card">
<img src="https://res.cloudinary.com/mo1/image/upload/v1564584621/kobe_lq48jt.jpg" id="mentorPicOne" alt="">
<strong><p>Kobe Bryant </p></strong>
<div class="mentor-info">
<input type="checkbox" id="check_id">
<label for="check_id"></label>
<ul>
<li><strong>Bio: </strong> A 44-year old husband and father of 2.</li><br>
<li><strong>Occupation: </strong> Retired professional basketball player</li><br>
<li><strong>Expertise: </strong> 5 years</li><br>
<button class="reach-btn" onclick="openPage()"> Reach Out</button>
</ul>
</div>
</div>
MY SECOND HTML FILE (destination file)
<!DOCTYPE html>
<html lang="en">
<head>
<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="shortcut icon" type="image/x-icon" href="../images/accusoft.png">
<link rel="stylesheet" href="../assets/css/all.css">
<link rel="stylesheet" href="../css/my_mentor.css">
<title>Free Mentors | My Mentor </title>
</head>
<body onload="onload()">
<div class="main-container">
<header class="header">
<a class="logo" href="/">
<span id="logo-icon">
<i class="fab fa-accusoft"></i>
</span>
<h3>Free<span id="free-mentors">Mentors</span></h3>
</a>
<div class="register-buttons">
<button class="button">Back</button>
<button class="button" id="admin-dash">Log Out</button>
</div>
</header>
<h2>My Mentor</h2>
<main class="content-container">
<div class="selected-mentor">
</div>
</main>
<footer class="footer">
<p>© Free Mentors 2019</p>
</footer>
</div>
</body>
<script src="../js/my_mentor.js" type="text/javascript"></script>
</html>
JavaScript File (my_mentor.js)
const mentorPicOne = document.getElementById('mentorPicOne'); ;
const selectedMentor = document.querySelector('.selected-mentor')
console.log('The selected', mentorPicOne)
openPage = async ()=>{
window.location.assign('./my_mentor.html');
}
function onload(){
selectedMentor.innerHTML = mentorPicOne;
}
I want to be able to click the React Out button, hence executing the openPage function, and then go the my_mentor page having the image inside of it.
I'd really appreciate your help. Thanks.
what do you mean by transferring from one file to other? its just a url, it can be placed in both pages. the image is not really on the page, its requesting it from your url and showing it in your html.

My getElementId is null (javascript native)

I have a silly problem I think, but I've tried several answers found on the net and nothing works so far.
I'd just like to have an id=modal
Here's the code:
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Le Cabinet</title>
<link rel="shortcut icon" href="img/logo-min.png">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css">
<link rel="stylesheet" href="css/style-sheet.css">
<link rel="stylesheet" href="css/mystyles.scss">
</head>
<body>
<main>
<div class="container">
<section class="columns">
<div>
<button onclick="toggleClass()" class="button is-rounded is-info is-hidden-tablet section__btn__info">Plus d’infomartions...</button>
<div id="modal" class="modal">
<div class="modal-background"></div>
<div class="modal-card">
<section class="modal-card-body">
<p class="modal-card-title modal__title"></p>
</section>
</div>
</div>
</div>
</section>
</div>
</main>
</body>
<script type="text/javascript" src="js/burger.js"></script>
</html>
script:
const modal = document.getElementById('modal');
console.log('modal', modal);
function toggleClass() {
modal.classList.toggle('is-active');
}
And modal return null,I can't get the id.
I don't see where you inject/insert your script.
You have to inject/insert your script at the bottom of your body, because when you call document.getElementById if the script is at the top, the html is not load so we can't find your id like :
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<!-- My super html -->
<script src="path/to" type="text/javascript"></script>
</body>
</html>

Parse server js error Uncaught ReferenceError: require is not defined

So, I'm trying to connect to my Parse Server using Javascript.
Problem is I keep getting that parse is undefined.
I included the unpkg resource file.
I also manually downloaded that file and saved it in a parse.js file and made a reference it on my site.
Here's the code for my website
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/purecss#1.0.0/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<link rel="stylesheet" href="css/login-css.css">
<link rel="stylesheet" href="css/backend.css">
<title> iCheckIn Backend</title>
<link href='http://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD-EJG_73OiPF-fZEu-QkEUwRoq75Ew60E"></script>
<script src="https://unpkg.com/parse/dist/parse.js"></script>
<script src="js/parse.js"></script>
</head>
<body>
<div id="sideBar">
<div id="standName">
<span id="pageName">iCheck In </span>
</div>
<div id="avatar">
<div id="admin">
<img src="img/user.png" id="img"><br>
<span id="welcomeSpan">Welcome, Admin.</span> <br><br>
</div>
<div id="menu">
<button class="pure-button menuBtn" onclick="CreateUser()">Map</button>
<button class="pure-button menuBtn" >List</button>
<button class="pure-button menuBtn " >Add Location</button>
<button class="pure-button menuBtn" onclick="CreateUser()" >Add Person</button>
</div>
</div>
</div>
<div id="fullContentDiv">
<div id="topDiv"></div>
<div id="fullCarContent">
<div id="carModels">
<span id="span"> All Tracking Records</span>
</div>
<div id="showSearchDiv">
<hr>
<span id="entrySpan">Show Entries</span>
<div id="search">
<form class="pure-form">
<button class="pure-button" >Search</button>
<input class="pure-input-1-4">
</form>
</div>
</div>
<div id="map">
</div>
</div>
</div>
<footer>
Copyright © 2017 Hugo Monteiro
</footer>
</body>
</html>
And the simple function I'm using is
function CreateUser(){
var Parse = require('parse');
Parse.initialize("mykey");
Parse.server('myurl');
var TestUser = parse.Object.extend("TestUser");
var testuser = new TestUser();
testuser.set("name","Hugo");
testuser.save(null,{
sucess: function(testuser){
alert("Object Created!");
},
error: function(testuser,error){
alert(error.message);
}
});
}
I've already done some searching and I'm unable to come across the solution.
Thanks in advance !

jQuery Load Local html file in Phonegap

I am creating multi page phone gap app
I have basic structure including css and scripts in index.html , i am trying to load content dynamically into container from other html pages.
When I load content of other dynamic page css is not reflecting on pages.
I have style sheets locally but still that style sheet is not applying on login.html after load
Style sheet cdn path for any one sing
https://cdn.syncfusion.com/js/mobile/ej.mobile.all-latest.min.css
script cdn path https://cdn.syncfusion.com/js/mobile/ej.mobile.all-latest.min.js
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no" />
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>Login</title>
<link href="css/font-awesome.min.css" rel="stylesheet" />
<link href="css/ej.mobile.all.min.css" rel="stylesheet" />
<link href="css/index.css" rel="stylesheet" />
</head>
<body>
<div data-role="appview">
<div id="header" data-role="ejmheader" data-ej-title="Leap Agent Portal"></div>
<div id="content"></div>
</div>
<!-- Cordova reference, this is added to your app when it's built. -->
<script src="cordova.js"></script>
<script src="scripts/jquery-2.1.1.min.js"></script>
<script src="scripts/jquery.validate.min.js"></script>
<script src="scripts/jsrender.js"></script>
<script src="scripts/ej.mobile.all.min.js"></script>
<script src="scripts/platformOverrides.js"></script>
<script>
var loadPage = function(url) {
$.ajax({
url: url,
}).done(function (data) {
$("#content").html(data);
});
}
(function () {
"use strict";
document.addEventListener('deviceready', onDeviceReady.bind(this), false);
function onDeviceReady() {
loadPage("views/login.html");
};
})();
</script>
</body>
</html>
login.html
<form id="loginform" method="post">
<h1>Enter Login Credentials</h1>
<br />
User Name
<input type="text" required id="username" name="username"><br>
<br />
Password
<input type="password" required id="password" name="password">
<div align="center">
<button type="submit" data-role="ejmbutton" data-ej-contenttype="textimage" data-ej-rendermode="auto"
data-ej-imageclass="fa fa-key" id="btnlogin">
Login
</button>
</div>
<div id="message"></div>
</form>
If I write everything on single without load style sheets are rendering
No Style rendered if I loaded with jquery load
Have you try safari development inspector to check your DOM/CSS ? sometimes it helps ,-)

Categories

Resources