I am trying to change <img> SRC through JavaScript [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Node.js document is not defined
(7 answers)
Closed 14 days ago.
I am building a dice game and I am trying to insert an image containing text in the image src through JavaScript
Here is my JavaScript Code:
var randomNumber = 6;
// Player 1
var p1 = () => {
var randomNo1 = Math.floor((Math.random()*randomNumber)+1);
return randomNo1;
}
var diceP1 = p1();
var test1 = document.getElementsByClassName("img1").src = `./images/dice${diceP1}.png`;
console.log(test1);
// Player 2
var p2 = () => {
var randomNo2 = Math.floor((Math.random()*randomNumber)+1);
return randomNo2;
}
var diceP2 = p2();
var test2 = document.getElementsByClassName("img2").src = "./images/dice"+diceP2+".png";
console.log(test2);
// Output
if(diceP1 > diceP2){
var result = "Player 1 wins";
console.log(result);
} else if(diceP1 < diceP2){
var result = "Player 2 wins";
console.log(result);;
} else{
var result = "Game drawn";
console.log(result);;
}
Here is my HTML Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Dicee</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Indie+Flower|Lobster" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Refresh Me</h1>
<div class="dice">
<p>Player 1</p>
<img class="img1" src="">
</div>
<div class="dice">
<p>Player 2</p>
<img class="img2" src="">
</div>
</div>
</body>
<footer>
www 🎲 Dice Game 🎲 com
</footer>
<script src="index.js"></script>
</html>
Whenever I start Live Server it doesn't do anything and when I am just running JavaScript file to see the output of the following line:
var test2 = document.getElementsByClassName("img2").src = "./images/dice"+diceP2+".png";
The system gives the following ERROR:
$ node index.js
/home/ahmed/Tutorials/Dicee Challenge - Starting Files/index.js:10
var test1 = document.getElementsByClassName("img1").src = `./images/dice${diceP1}.png`;
^
ReferenceError: document is not defined
at Object.<anonymous> (/home/ahmed/Tutorials/Dicee Challenge - Starting Files/index.js:10:13)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.12.1

Related

Fails to Generate Message

My message does not display after I run the code. Need some direction, I double checked my code. Might be a syntactical error somewhere
HTML-
<!doctype html>
<html>
<head>
<title>Message Generator</title>
<link rel="stylesheet" href="index.css">
<center><div class="wordart blues"><span class="text">Message Generator</span></div></center>
</head>
<body>
<div class="quoteDisplay"><center>Your random message will be displayed here</center></div>
<div id="quote">
<!--Quote will display here-->
</div>
<center><button onclick="messageGenerator()">Click Here</button></center>
<script src="index.js"></script>
</body>
</html>
Javascript-
const first = ["Mom", "Dad", "Uncle", "Dog", "Cat", "Brother", "Sister", "Aunt", "Random Stranger", "Respect", "Honor", "Dignity", "Brain", "Life"]
const second = ["Ocean", "Sea", "Volcano", "Tornado", "Ditch", "Cave", "Typhoon", "Asia", "India"]
const third=["Unknown","To explore","To prove a point","To live life with no constraints","Just cause"]
function randomGenerate(value) {
var item = value[Math.floor(Math.random() * value.length)];
return item;
}
const messageGenerator = () => {
let person = randomGenerate(first);
let place = randomGenerate(second);
let reason = randomGenerate(third);
let finalSentence = `Your ${person} jumped in the ${place}\nReason: ${reason}`;
document.getElementById("quoteDisplay").innerHTML=finalSentence;
}
document.getElementById("quoteDisplay") looks for an element with ID of "quoteDisplay". In this case, your targeted element is a class.
document.querySelector('.quoteDisplay').innerHTML = finalSentence
Although, I think you are trying to target #quote, which in this case, getElementById is the right method but the wrong id
document.getElementById("quote").innerHTML = finalSentence;
Looking at your HTML
<div class="quoteDisplay"><center>Your random message will be displayed here</center></div>
<div id="quote">
Looking at your javascript
document.getElementById("quoteDisplay").innerHTML=finalSentence;
It should be document.getElementById("quote").innerText = finalSentence;

Cannot read properties of null (reading 'addEventListener') in a Javascript file (not script tag) [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed last year.
I am a JavaScript beginner and when I was making a HTML, CSS, JS project with VSCode, I encountered the following error:
Uncaught TypeError: Cannot read properties of null (reading at 'addEventListener')
Also, My project was: Make a login + register system with just JavaScript dictionaries, and a logged_in variable (that will redirect people to the registration page if it's false)
HTML Registration file:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>BeedHub Register</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='style.css'>
<script src='index.js'></script>
</head>
<body>
<h1 class="hello_world">Welcome!</h1>
<p class="aaa">We're so excited to see you!</p>
<div class="usernamediv">
<input id="main_usr" placeholder="Write username here" type="text">
</div>
<div class="passworddiv">
<input id="main_pw" placeholder="Write password here" type="password">
</div>
<div class="btn">
<button id="main_register">Register!</button>
</div>
<div class="login_instead">
Login Instead
</div>
</body>
</html>
JavaScript file:
// Variables
var db = {
};
var logged_in = false;
// Register Elements
var rg_usr = document.getElementById("main_usr");
var rg_pw = document.getElementById("main_pw");
var rg_submit = document.getElementById("main_register");
// Event Listeners
rg_submit.addEventListener('click',function() {
if (db[rg_usr.innerHTML]) {
var error_usr_taken = document.createElement("p");
error_usr_taken.innerHTML = "Error: Username Already Taken!";
} else if (rg_usr.innerHTML == "" || null) {
var error_usr_none = document.createElement("p");
error_usr_none.innerHTML = "Error: Username is null!";
} else if (rg_pw.innerHTML == "" || null) {
var error_pw_none = document.createElement("p");
error_pw_none.innerHTML = "Error: Password is null!";
} else {
db[rg_usr.innerHTML] = rg_pw.innerHTML;
logged_in = true;
window.location.pathname = "/successpage";
};
});
If you want me to provide more information, comment with a ping.
P.S. I have also used the script tag on my /login/index.html file, but the web says that multiple HTML files using the same JavaScript file have no problem.
Thanks in advance,
Beedful
Your script is being executed before the markup is on the page and that's why you're getting an error.
So, you can either move the script tag at the very end of the body like this:
<body>
<!-- All contents here -->
<script src='index.js'></script>
</body>
Or you can add defer to your script tag and let it continue to be in the head, like this:
<script src='index.js' defer></script>

Javascript to change HTML giving errors

I am trying to calculate values using javascript then update the HTML with them. If I don't defer both scripts then I get the error
"Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') at updateDetailsHTML (breakeven-calc.js:2) at (index):72"
If I defer both scripts I get the error
"(index):72 Uncaught ReferenceError: updateDetailsHTML is not defined at (index):72"
HTML Coded
<head>
<script defer src="../static//js/breakeven-calc.js"></script>
<script defer type="text/javascript"> /* Creates vars to pass to function */
let G22_Car = parseFloat("{{data.get('G22_Car')}}")
let G23_Car = parseFloat("{{data.get('G23_Car')}}")
let Q23_Car = parseFloat("{{data.get('Q23_Car')}}")
let Q24_Car = parseFloat("{{data.get('Q24_Car')}}")
let G22_Truck = parseFloat("{{data.get('G22_Car')}}")
let G23_Truck = parseFloat("{{data.get('G23_Car')}}")
let Q23_Truck = parseFloat("{{data.get('Q23_Truck')}}")
let Q24_Truck = parseFloat("{{data.get('Q24_Truck')}}")
let pre_icev_car = G22_Car + G23_Car
let pre_ev_car = Q23_Car + Q24_Car
let pre_icev_truck = G22_Truck + G23_Truck
let pre_ev_truck = Q23_Truck + Q24_Truck
console.log(pre_ev_car)
console.log(pre_icev_car)
console.log(pre_ev_truck)
console.log(pre_icev_truck)
/* Function in breakeven-calc*/
updateDetailsHTML(pre_icev_car, pre_ev_car, pre_icev_truck, pre_ev_truck)
</script>
</head>
<body>
<p id="car-details">
Pre-ownership CO2e emissions (reference values apply): <br>
EV: MTCO2e/Year <br>
ICEV: MTCO2e/Year
</p>
</body>
Javascript file "breakeven-calc"
function updateDetailsHTML(pre_icev_car, pre_ev_car, pre_icev_truck, pre_ev_truck){
document.getElementById("car-details").innerHTML = "worked"
}
copy paste as below
<!doctype html>
<html>
<head>
<script>
<!--
let G22_Car = parseFloat("{{data.get('G22_Car')}}")
let G23_Car = parseFloat("{{data.get('G23_Car')}}")
let Q23_Car = parseFloat("{{data.get('Q23_Car')}}")
let Q24_Car = parseFloat("{{data.get('Q24_Car')}}")
let G22_Truck = parseFloat("{{data.get('G22_Car')}}")
let G23_Truck = parseFloat("{{data.get('G23_Car')}}")
let Q23_Truck = parseFloat("
{{data.get('Q23_Truck')}}")
let Q24_Truck = parseFloat("
{{data.get('Q24_Truck')}}")
let pre_icev_car = G22_Car + G23_Car
let pre_ev_car = Q23_Car + Q24_Car
let pre_icev_truck = G22_Truck + G23_Truck
let pre_ev_truck = Q23_Truck + Q24_Truck
console.log(pre_ev_car)
console.log(pre_icev_car)
console.log(pre_ev_truck)
console.log(pre_icev_truck)
/* Function in breakeven-calc*/
function updateDetailsHTML(pre_icev_car, pre_ev_car,
pre_icev_truck, pre_ev_truck){
document.getElementById("car-details").innerHTML =
"worked"
updateDetailsHTML(pre_icev_car, pre_ev_car,
pre_icev_truck, pre_ev_truck)
}
-->
</script>
</head>
<body>
<div id='car-details'>
Pre-ownership CO2e emissions (reference values apply):
<br>
EV: MTCO2e/Year <br>
ICEV: MTCO2e/Year
</div>
</body>
</html>
Regarding the defer script , you wont need that , it only affect the code within the script if it only has src attribute on it .
and make sure you define the function above then call it in sequence
Have you ever tried moving your scripts inside your body tag?
<body>
<p id="car-details">
Pre-ownership CO2e emissions (reference values apply): <br>
EV: MTCO2e/Year <br>
ICEV: MTCO2e/Year
</p>
{{-- put all your scripts here--}}
</body>

Problem with require() function in javascript

I am trying to implement the following code in which i try to read a json file in javascript. I have two files , let one be main.html which has the main javascript code let it be called main.js , and the other is imported.js
This is the main.html file
<!Doctype html>
<html>
<head>
Dwell time for workers
</head>
<script src = https://requirejs.org/docs/release/2.3.6/r.js></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" src="text.json"></script>
<script src="testing_file.js"></script>
<script type = "text/javascript"></script>
<script>
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2]);
</script>
<body>
<h1> worker time : </h1>
</body>
</html>
This is the imported.js file
var that = null;
class import_file
{
constructor(title)
{
this.title = title;
that = this;
}
dwell_times()
{
console.log('osama')
var x = [5,4,3,2,1] ;
var y = x.toString();
console.log(y)
let parsed = require('./updated.json')
console.log(parsed) ;// Arham
return parsed;
}
}
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2])
I am getting the following error
Uncaught Error: Module name "updated.json" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
at makeError (r.js:417)
at Object.localRequire [as require] (r.js:1685)
at requirejs (r.js:2046)
at import_file.dwell_times (testing_file.js:16)
at imported.js:23
What do i do to solve this error ?
Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax :
var moduleName = './updated.json';
require([moduleName], function(fooModule){
// do something
})

Error in executing a python function from a javascript code using flask

I have am running a python flask application and from the html page I am calling a javascript file(using <script src=....>). Here is my html file:
HTML FILE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title1</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="static/chat/js/jquery.timeago.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script data-main="scripts/main" src="require.js"></script>
<link rel="stylesheet" href="speech.css">
</head>
<body>
<meta charset="UTF-8">
<nav class="navbar-left" height="100" style="background-color: #092A66 !important;">
<a class="navbar-brand" padding-top=0 padding-bottom=0 href="#">
<img src="image.jpg" height="100" alt="">
</a>
</nav>
<br><br>
<div class="container">
<div id="chat" class="jumbotron" style="height:600px;background-color:white">
<div id="conversations" style="overflow-y: scroll; height:500px;overflow:auto; ">
<div class="arrow"></div>
<ul class="ChatLog">
</ul>
</div>
</div>
<div id="compose-message">
<label for="new-input-message">{{gettext('Message')}}</label>
<input type="text" id="new-input-message" class="speech-input" aria-describedby="new-input-message-help-block" name="eng-input" lang = "en" disabled="false">
<small id="new-input-message-help-block" class="form-text text-muted">
{{gettext('Hit enter to send message')}}
</small>
</div>
</div>
</div>
<script src="static/speech-in.js"></script>
<script async defer src="https://buttons.github.io/buttons.js"></script>
</body>
</html>
<script>
$( document ).ready(function()
{
var socket = io.connect('http://localhost:5000');
// OTHER IMPORTANT CODE FOR FURTHER PROCESSING
.
.
.
});
</script>
In the above code I am including the socket.io in the head of the html file and then I am including speech-in.js file in which I want to use socket connection. My current code in speech-in.js is:
speech-in.js:
(function() {
'use strict';
// check for support (webkit only)
if (!('webkitSpeechRecognition' in window)) return;
var talkMsg = 'Speak now';
// seconds to wait for more input after last
var defaultPatienceThreshold = 6;
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
console.log('Check 1');
var inputEls = document.getElementsByClassName('speech-input');
[].forEach.call(inputEls, function(inputEl) {
var patience = parseInt(inputEl.dataset.patience, 10) || defaultPatienceThreshold;
var micBtn, micIcon, holderIcon, newWrapper;
var shouldCapitalize = true;
// gather inputEl data
var nextNode = inputEl.nextSibling;
var parent = inputEl.parentNode;
var inputRightBorder = parseInt(getComputedStyle(inputEl).borderRightWidth, 10);
var buttonSize = 0.8 * (inputEl.dataset.buttonsize || inputEl.offsetHeight);
// default max size for textareas
if (!inputEl.dataset.buttonsize && inputEl.tagName === 'TEXTAREA' && buttonSize > 26) {
buttonSize = 26;
}
// create wrapper if not present
var wrapper = inputEl.parentNode;
if (!wrapper.classList.contains('si-wrapper')) {
wrapper = document.createElement('div');
wrapper.classList.add('si-wrapper');
wrapper.appendChild(parent.removeChild(inputEl));
newWrapper = true;
}
console.log('Check 2');
// create mic button if not present
micBtn = wrapper.querySelector('.si-btn');
if (!micBtn) {
micBtn = document.createElement('button');
micBtn.type = 'button';
micBtn.classList.add('si-btn');
micBtn.textContent = 'speech input';
micIcon = document.createElement('span');
holderIcon = document.createElement('span');
micIcon.classList.add('si-mic');
holderIcon.classList.add('si-holder');
micBtn.appendChild(micIcon);
micBtn.appendChild(holderIcon);
wrapper.appendChild(micBtn);
// size and position mic and input
micBtn.style.cursor = 'pointer';
micBtn.style.top = 0.125 * buttonSize + 'px';
micBtn.style.height = micBtn.style.width = buttonSize + 'px';
inputEl.style.paddingRight = buttonSize - inputRightBorder + 'px';
}
// append wrapper where input was
if (newWrapper) parent.insertBefore(wrapper, nextNode);
console.log('Check 3');
// GOING TO CALL PYTHON FUNCTION
$( document ).ready(function(){
//Receive a new message
socket.on('speech', function(msg) {
var time = new Date();
time_str = time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
new_msg='<li class="ChatLog__entry"> <img class="ChatLog__avatar" src="static/chat/images/Assistant.png" /> <p class="ChatLog__message"> '+msg+' <time class="ChatLog__timestamp">'+time_str+'</time> </p> </li>'
$("#conversations ul").append(new_msg)
$('#new-input-message').prop('disabled', false);
});
});
});
console.log('Check 4');
})();
As you can see I am making use of socket.on but it throws error because socket is unrecognizable. I am including the socket.io class in my html file and I am establishing a connection to it also in the html file but that connection is not visible in this javascript file.
I also have the python flask application executing which has a function with route #socket.on('speech') qualified to it.
What mistake I am making here and how can I correct it?
socket object is not available in your speech-in.js file since it is not in global scope.
All socket events should be subscribed to in callback after connect event received:
var socket = io.connect('http://localhost:5000');
socket.on('connect', function() {
// subscribe to events here
socket.on('custom_event_from_flask', function (data) {
console.log('Event received data:' + JSON.stringify(data));
});
});
One of the options is to move socket initialization into your speech-in.js file from index.html. However, if you expect your project to grow it would be better to change client side (JS) to have it more logically organized using at least JS es6 modules.

Categories