I'm new to JavaScript and I've been trying to get the title text to switch between different texts for a day now. I've gathered some code snippets and put them together, so I'm not quite sure what's going on.
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function switchingText(); {
document.getElementByID("title").innerHTML = "Text";
sleep(2000);
document.getElementByID("title").innerHTML = "Text2";
sleep(2000);
switchingText();
}
I would appreciate any help greatly.
This is a sample solution for your dilemma:
const title= document.getElementById("title");
const switchHeading = () => {
if (title.innerHTML== "Text"){
title.innerHTML = "Text2";
}else{
title.innerHTML = "Text";
}
}
setInterval(() => {
switchHeading()
}, 2000);
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<h1 id="title">Text</h1>
<script src="./script.js" async defer></script>
</body>
</html></html>
Helpful links:
W3Schools Set Interval
All you need to do is get the title element like you did but instead of changing the InnerHTML, change the value, like so:
document.getElementByID('title').value="Text"
Hope you found what you were looking for.
Instead of doing
document.getElementByID("title").innerHTML = "Text";
in the switching text function,
you need to do
document.title = 'your text'
Related
The thing i wanna do is when user writes something to input and sumbits it, the page will change to the input.
Example:
If user writes "Web" to the input, the page title should change to "Web"
Here's the code:
JS:
document.getElementById("titleSumbitBtn").onclick = function (){
var newTitle = document.getElementById("newTitle").textContent;
document.getElementById("title").innerHTML = newTitle;
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title id="title">Web Editor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center><label id="originLabel">Welcome to Web Editor!</label><br></center>
<br><label id="changeTitleLabel">Change the title of Web: </label><br>
<input type="text" id="newTitle"><br>
<button type="button" id="titleSumbitBtn">Change</button>
</body>
</html>
You can assign new title to the document like this:
document.getElementById("titleSumbitBtn").onclick = function (){
var newTitle = document.getElementById("newTitle").value;
document.title = newTitle;
}
This is actual implementation but keep in mind that it must run after the DOM element with id newTitle.
If you put your <script> tag inside <head>, you'll need DOMContentLoaded:
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("titleSumbitBtn").onclick = function (){
var newTitle = document.getElementById("newTitle").value;
document.title = newTitle;
}
})
try this:
document.getElementById("titleSumbitBtn").addEventListener("click", function (){
var newTitle = document.getElementById("newTitle").value;
document.getElementById("title").innerText = newTitle;
})
Here is my HTML and JS code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
<script src="functions.js"></script>
</body>
</html>
Here is my Javascript code
'use strict'
const buttonclick = document.getElementById('button')
const list = document.getElementById('lists')
const a = "<span><button class = 'rbutton'>X</button></span>" //list-item button
const clickhandler = () => {
const text = document.getElementById('text')
//creating a list element
if(text.value != ''){
let Newdiv = document.createElement('div')
// appending elements
Newdiv.innerHTML = text.value + a
list.appendChild(Newdiv)
let b = document.getElementsByClassName('rbutton')
if(b !=[]){
for(let i = 0; i < b.length; i++){
b[i].addEventListener('click', function(){
b[i].parentElement.parentElement.remove();
console.log(b)
})
}
}
//reseting the textarea value
text.value = ''
}
}
buttonclick.addEventListener('click', clickhandler)
An error in shown on delete a item: Cannot read property 'parentElement' of undefined at HTMLButtonElement. .
Can someone please explain what is wrong in my code and what does the error mean.
thankyou
On every click of the button you are attaching event handlers to the whole group again.
On the first iteration, 1st button has one delete handler.
On second iteration, 1st button has 2 event handler(one for buttons[0] and one for buttons[1]), and 2nd has one.
So on.
Use this. It will always point to the element to the event on which the event handler is attached:
this.parentElement.parentElement.remove();
Another way is to simply use this.parentElement.parentElement.remove()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
<script>
"use strict";
const buttonclick = document.getElementById('button');
const list = document.getElementById('lists');
const a = "<span><button class = 'rbutton'>X</button></span>"; //list-item button
const clickhandler = () => {
const text = document.getElementById('text');
//creating a list element
if(text.value != '') {
let Newdiv = document.createElement('div');
// appending elements
Newdiv.innerHTML = text.value + a;
list.appendChild(Newdiv);
let b = document.getElementsByClassName('rbutton');
for(let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function() {
this.parentElement.parentElement.remove();
});
}
//reseting the textarea value
text.value = '';
}
}
buttonclick.addEventListener('click', clickhandler);
</script>
</body>
</html>
You should use window.event.target.parentElement... to get the button instead of b[i].parentElement....
"use strict";
const buttonclick = document.getElementById('button');
const list = document.getElementById('lists');
const a = "<span><button class = 'rbutton'>X</button></span>"; //list-item button
const clickhandler = () => {
const text = document.getElementById('text');
//creating a list element
if(text.value != '') {
let Newdiv = document.createElement('div');
// appending elements
Newdiv.innerHTML = text.value + a;
list.appendChild(Newdiv);
let b = document.getElementsByClassName('rbutton');
for(let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function() {
window.event.target.parentElement.parentElement.remove();
});
}
//reseting the textarea value
text.value = '';
}
}
buttonclick.addEventListener('click', clickhandler);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
</body>
</html>
I'm learning web development and I'm trying to do the simplest things in javascript to learn how it works. I have this problem, the h1 text is not changing on the page but when I open the console it prints the changed value each time , here's the code (Hint, the sleep() function is from the internet and I don't know anything yet about it but it works):
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script>
let counter = 0;
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function change(){
while(true)
{
document.querySelector("#show").innerText = counter;
counter++
console.log(document.querySelector("#show").innerText);
sleep(1000);
}
}
</script>
</head>
<body>
<button onclick="change()" id="button" >COUNT</button>
<h1 id="show">0</h1>
</body>
</html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script>
function change() {
let counter = 0;
setInterval(() => {
document.querySelector("#show").innerText = counter;
counter++;
}, 1000);
}
</script>
</head>
<body>
<button onclick="change()" id="button" >COUNT</button>
<h1 id="show">0</h1>
</body>
</html>
try changing your change function using setInterval. you can find how to use set interval using https://www.w3schools.com/jsref/met_win_setinterval.asp
I'm trying to display contents of an API but for some reason I'm getting an error in the console that says Uncaught (in promise) TypeError: Cannot read property 'appendChild' of null which sort doesn't make sense to me because I've set to innerHTML = <p>${this.items[i]}</p>.
What am I doing wrong and how can I fix this? If you need more information, please let me know.
Here's my html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="baseball">
<h1>test</h1>
</div>
<script type="application/javascript" src="index.js"></script>
<script type="text/javascript">
window.addEventListener("load", function() {
console.log("document is loaded");
var baseballStats = new BaseballStats();
baseballStats.init("https://statsapi.mlb.com/api/v1/people/660670/stats?stats=byDateRange&season=2018&group=hitting&startDate=&endDate=&leagueListId=mlb_milb", true);
});
</script>
</body>
</html>
Here's my javascript
class BaseballStats {
constructor() {
this.totalItems = 0;
this.list = document.querySelector("baseball");
}
init(url, bool) {
this.bool = bool;
var that = this;
console.log(url);
fetch(url)
.then(resp => resp.json())
.then(data => {
console.log(data.stats);
that.data = data;
if (this.bool) {
that.items = that.data.stats;
this.totalItems = that.items.length;
console.log("about to loop");
for (var i = 0; i < this.totalItems; i++) {
var listNode = document.createElement("LI");
listNode.innerHTML = `<p>${this.items[i]}</p>`;
console.log("did it reach here");
this.list.appendChild(listNode);
}
}
});
}
}
Try to console.log the list variable. You will see it's null. You're treating this variable as an object, but the content of the variable is null.
Your problem is the BaseballStats' list member is null. This is because you're misusing document.querySelector - it selects in the same way as CSS, so to select an element with a class you need to use the . selector - https://www.w3schools.com/cssref/css_selectors.asp.
You are selecting for 'baseball' however, which means it is trying to find an element with the tag name <baseball>. Change this to '.baseball' and it will work
I have just started learning Javascript, and I attempted to write code for hit counter for a webpage using Javascript. I know that we have to use cookies to get the correct number and use PHP to modify data stored in servers. But could you please debug this for me ? I'm getting the output as "The number of visitors is: NaN"
This is my code:
<!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">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = counter.value;
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You are trying to get the valuefrom a span element, which is wrong.
Your counter.value is undefined so it will give you the wrong answer.
You can get the 0 from the span by using document.getElementById("cntr").innerHTML. But the value returned is in string. So you need to do parseInt to convert it into integer and only then your addition will give you the correct value.
<!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">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.innerHTML);
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to use parseInt
<script>
function counter_fn(){
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
UPDATE
As #Anurag Singh Bisht commented, you cannot get value from a span element . So to get value from <span> you need to use $('span').text();
<html>
<body>
<div id="cntr">
The number of visitors is :
<span>0</span>
</div>
<script>
function counter_fn(){
var counter = $('#cntr span').text(); // geting value from span
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to parse the string to an integer and you need to get the innerHTML.
<script>
function counter_fn(){
var counterElement = document.getElementById("cntr")
var counterNumber = parseInt(counterElement.innerHTML)
counterNumber = counterNumber + 1
counterElement.innerHTML = counterNumber
}
window.onload = counter_fn;
</script>
The correct way to do it would be storing this value somewhere else, like localStorage and reading it from there. You are not supposed to read your own HTML to update the value. HTML elements are supposed to be results, not your input.
var counterNumber = 1
if (localStorage.getItem("count")) {
counterNumber = parseInt(localStorage.getItem("count")) + 1
}
else {
localStorage.setItem("count", counterNumber)
}