not able to load contents in div using javascript - javascript

this is shan and i'm a javascript noob and i'm trying to work qa code as an example here. i'm trying to load a small javascript content to a div element but it is not working any help would be great and here is the code.
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext () {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerhtml="adding 1 to 100 gives "+sum;
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>

You need to call the function. It's also a good idea to wait until the window is loaded (or you can use some more advanced JS to detect the DOM ready state.):
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext() {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML = "adding 1 to 100 gives "+sum;
}
window.onload = function(){
displaytext();
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>

3 problems:
You never actually call the function. It is only declared.
The property is innerHTML not innerhtml. Javascript is case-sensitive.
The script is above an element is is referencing. As scripts are executed as they are found (page construction is paused during execution) the element you are referring to is never found.
Also you declare the loopindex variable twice, which i think will cause a syntax error on ES5 strict.
<html>
<head>
<title>
using d for statement
</title>
</head>
<body>
<div id="targetdiv">
</div>
</body>
<script>
function displaytext () {
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML="adding 1 to 100 gives "+sum;
}
displaytext();
</script>
</html>

Related

Ask about jquery function operation [duplicate]

This question already has answers here:
How to prevent a click on a '#' link from jumping to top of page?
(24 answers)
Closed 2 years ago.
I'm student and it hasn't been long since I studied programming.
below code is simplified than real for explain.
'test()' is actually Ajax function to get data.
My goal is making 'a tag' for paging operation.
But when i clicked 'a tag', 'test()' inside of '$(document).ready' is called after 'a tag' click event occurred.
So page is always back to 1.
I don't know why this happen.
Anyone could help me?
Thank you!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
var page = 1;
$(document).ready(function(){
test();
alert(page);
});
function test(){
for(var i = 1; i <= 3; i++) {
var a = $("<a></a>").text(i).attr({
href: "",
idx: i
});
a.preventDefault;
$(a).click(function(){
page = $(this).attr("idx");
test();
alert(page);
});
$("#pageLink").append(a," ");
}
}
</script>
</head>
<body>
hello!
<div id="pageLink"></div>
</body>
</html>
For some reason you're calling test() inside of test(). There are a few minor things you need to change also
Prefix jQuery objects with $. var $a=... to avoid ambiguity.
preventDefault is used on the event, not the jQuery object. $a.click(function(event){event.preventDefault();...});
Otherwise it works as I believe you want it to, alerting the page number on click.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
createLinks();
});
function createLinks(){
for(var i = 1; i <= 3; i++) {
var $a = $("<a></a>").text(i).attr({
href: "",
idx: i
});
$a.click(function(event){
event.preventDefault();
page = $(this).attr("idx");
// why are you calling this again? // test();
// maybe you want to load something // loadSomething(page);
alert(page);
});
$("#pageLink").append($a," ");
}
}
</script>
</head>
<body>
hello!
<div id="pageLink"></div>
</body>
</html>

Why is dom.innertext was updated and rendered after the while is finished in this example?

I am pretty new to javascript and am working on an assignment.
The problem I have can be demonstrated via codes below:
For HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A3Q5</title>
<script src='xxx.js'> // external js
</script>
</head>
<body>
<div class="container">
<button id="startBtn">Start</button>
<div id="displayStart">x</div>
</div>
</body>
</html>
For the xxx.js code:
function setup(){
document.getElementById("startBtn").addEventListener('click',startRace,false);
}
function startRace(){
var test = document.getElementById("displayStart");
test.textContent = "adsasdasds";
console.log(test.textContent);
var c = 5;
while(c--){
var counter = 500000000;
while(counter--){} // try to simulate some delays
}
}
window.addEventListener('load',setup,false);
so the problem is, when I run the program and click the button, the console prints "adsasdasds" however the div element is not updated in the browser until the first while loop is done....
Doesn't js run sequentially like java / C++ if no async is specified ?
Hope someone can help me out
The desired result will be : the div is updated before entering the while loop as the sequence of code execution...
Thank you !

How do i increment a global variable in a function in java script from a button?

this might be a dumb thing to ask but I am getting a lot of trouble with this for and quiz I need to make for and assignment, and I am trying to increment the score when the user clicks to the correct button. However, the score is not incrementing. here is a little sample of what it looks like.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Increment Button</title>
</head>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
var score = 0;
function IncrementScore()
{
score++;
}
console.log(score);
</script>
</body>
</html>
You have a few issues.
You probably want to console.log from within the IncrementScore function.
You want to increment the variable using += 1 or ++.
<!DOCTYPE html>
<html>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
var score = 0;
function IncrementScore() {
score++;
console.log(score);
}
console.log(score);
</script>
</body>
</html>
Change your code to score += 1 and move you console call to inside of your function.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Increment Button</title>
</head>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
var score = 0;
function IncrementScore()
{
score += 1;
console.log(score);
}
console.log(score);
</script>
</body>
</html>
On each click you increment variable. And in next line assign to variable "1". You should delete line
score = 1;
TL;DR: Actually the score did increment, but not be printed out via the click handler.
As I know in your snippet, all your script in <script> tag (include console.log) will all execute once initially. Then it sits there to listen to the events, like your click. Then when you click on the button, the IncrementScore function is called, it increments the score variable, but not print it out. You know why? because you don't tell it to do so, (in the IncrementScore handler). If you notice, you'll see that you only have one 0 printed out, not each 0 per click.
You should read about the call stack,etc.. to know more about the order which code is executed...
The fixes snippet can be found in other's answer, here is the code for when the variable actually "does not change", and be printed out for each click.
<!DOCTYPE html>
<html>
<body>
<button onclick="IncrementScore()"> Increment</button>
<script>
var score = 0;
function IncrementScore() {
//score++;
console.log(score);
}
</script>
</body>
</html>

Replacing inner HTML fails despite onload function

I rarely have to do any Javascript and I seem to fail doing the easiest tasks. I am trying to replace a string in two divs. The first div gets replaced, the second one is not found with the error message:
drawings.html:20 Uncaught TypeError: Cannot set property 'innerHTML' of null
However I tried the usual remedies of putting my code in an 'onload' function and putting the script at the end of the body tag. What else could possibly go wrong?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="cell1">test<div>
<div id="cell2">test<div>
<script>
window.onload = function() {
replace();
}
function replace() {
console.log("replace");
document.getElementById("cell1").innerHTML = "cell1";
document.getElementById("cell2").innerHTML = "cell2";
}
</script>
</body>
</html>
just close your divs elements.
<html>
<head>
</head>
<body>
<div id="cell1">test</div>
<div id="cell2">test</div>
<script>
window.onload = function() {
replace();
}
function replace() {
console.log("replace");
document.getElementById("cell1").innerHTML = "cell1";
document.getElementById("cell2").innerHTML = "cell2";
}
</script>
</body>
</html>

Javascript/HTML Image Change

My task for my Javascript class is to create a script for this page that changes the image every 3 seconds. I think my code is correct, however Firebug tells me "document.getElementByID is not a function." Can someone show me what I am doing incorrectly?
This is my JS script.
<script type="text/javascript">
var i = 0
var lightArray = ["pumpkinOff.gif", "pumpkinOn.gif"]
var currentLight = document.getElementByID('light')
// ChangeLight Method Prototype
function changeLight() {
currentLight.src = lightArray[i++];
if (i == lightArray.length) {
i = 0;
}
}
setInterval(changeLight, 3000)
</script>
Here is my edited HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript for Programmers</title>
</head>
<body>
<h2>Happy Halloween!</h2>
<img id="pumpkin" src="pumpkinoff.gif" alt="pumpkin">
<script src="../Script/spooky.js"></script>
</body>
</html>
Incorrect capitalisation on
var currentLight = document.getElementByID('light')
Should be:
var currentLight = document.getElementById('pumpkin')
I have attached a working fiddle:
http://jsfiddle.net/11csf4k2/
It's a typo it should be:
var currentLight = document.getElementById('light'); //Not ID
It should be Id not ID:
document.getElementById('light');
Also note that you don't have element with id light on your page. It probably should be
document.getElementById('pumpkin');

Categories