I'm new to JS and HTML. I learned that it's possible to name a variable by code. So i tried some simple variable naming code. However, it doesn't print anything on the page.
What seems to be the problem?
javascript
for (var i = 0; i < 10; i++) {
window['var' + i] = i;
}
document.getElementById("text").innerHTML = "" + var8;
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="JScript.js"></script>
<title>Practice</title>
</head>
<body>
<p><span id="text"></span>left</p>
</body>
</html>
Enclose your javascript code in below document.ready function, so that it will execute only when your page is ready.
$(document).ready(function () {
// enter your code here
});
Related
I have a simple counting loop that counts to 10000 and logs every number to the console. Before i start the loop i want to write "TEST" to the body in my html.
Although i do this before i start the loop it appends "TEST" to the body only after the loop is done. However i can log something to the console before starting the loop. I think i am blocking the browser thread or something, i don't know how to write this in a non blocking manner. I have been trying to figure out this Problem for quite some time. Your Help would be much appreciated !!!
My HTML code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<button onclick="myfunc()">click me</button>
</body>
<script src="index.js"></script>
</html>
My javascript code:
function myfunc() {
var h1 = document.createElement("h1").innerText = "TEST"
document.body.appendChild(h1) //appends only after loop is done
console.log("test") // this works
for (var i = 0; i < 10000; i++){
console.log(i)
}
}
One solution is to put your loop code in a timeout and set the delay to 1 millisecond
function myfunc() {
var h1 = document.createElement("h1")
h1.innerText = "TEST"
document.body.appendChild(h1) //appends before the loop
console.log("test") // this works
setTimeout(()=>{
for (var i = 0; i < 10000; i++){
console.log(i)
}
},1)
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<button onclick="myfunc()">click me</button>
</body>
<script src="index.js"></script>
</html>
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>
I have written this code which I thought was correct, but although it runs without error, nothing is replaced.
Also I am not sure what event I should use to execute the code.
The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str) {
return 'Newtext'; // JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t = 0;
var tags = Array('keyword', 'locale', 'advert_ID');
if (document.readyState === 'complete') {
var str = document.body.innerText;
for (t = 0; t < tags.length; t++) {
//replace in str every instance of the tag with the correct value
if (tags[t].length > 0) {
var sToken = '{ltoken=' + tags[t] + '}';
var sReplace = getQueryVar(tags[t]);
str.replace(sToken, sReplace);
} else {
var sToken = '{ltoken=' + tags[t] + '}'
var sReplace = '';
str.replace(sToken, sReplace);
//str.replace(/sToken/g,sReplace); //all instances
}
}
document.body.innerText = str;
}
}
</script>
</head>
<body>
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type="button" onclick="searchReplace('keyword')">
</body>
</html>
So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar.
Currently it replaces nothing, but raises no errors
Your problem is the fact you don't reassign the replacement of the string back to it's parent.
str.replace(sToken,sReplace);
should be
str = str.replace(sToken,sReplace);
The .replace method returns the modified string, it does not perform action on the variable itself.
Use innerHTML instead innerText and instead your for-loop try
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str)
{
return'Newtext';// JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t=0;
var tags =Array('keyword','locale','advert_ID');
if (document.readyState==='complete'){
var str = document.body.innerHTML;
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
//tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));
document.body.innerHTML=str;
}
}
</script>
</head>
<body >
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Title</title>
<script language="JavaScript">
<!--
function showtags()
{
var tag;
for(i = 0; i < document.all.length; i++)
{
tag = document.all(i).tagName;
document.write(tag + ' ');
//document.write("<br>");
}
}
// -->
</script>
</head>
<body>
<script>
showtags();
</script>
</body>
</html>
If I un-comment the second document.write() in the loop inside the function then it hangs (it does not display anything and times out). I appreciate your help.
document.all is a "live" collection. Each time you loop, you add 2 new items. This means every time it evaluates the length property it's always going to be larger than i.
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>