Hey I am new to coding and I'm working on a new chrome App. So far, I am trying to make a button that counts when you click on it. For some reason it's not working. Here's the HTML:
var button = document.getElementById("button"),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Button: " + count;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> This is a "Button" (I think) </h1>
<p> (Or is it?) </p>
<button id="button"> Button: 0 </button>
</body>
</html>
You have to wait until the DOM is loaded. Use the window.onload event:
window.onload = function() {
var count = 0;
const button = document.getElementById('button');
button.onclick = function() {
count += 1;
button.innerHTML = "Button: " + count;
};
};
Edit: I also just noticed you're not including your script in your HTML.
Your missing a variable type on your count.
You want make sure your button has some kind of text inside of it before you actually
start incrementing it.
Lastly you need to get the element from the html with a "document.getElementById("id_goes_in_here")
Try this instead.
document.getElementById("button").innerHTML = ` `; //Make sure to actually pull from your element in the html with this.
let count = 0;
button.innerHTML="Button " + count
button.onclick = function() {
count += 1;
button.innerHTML = "Button: " + count;
};
Related
I am trying to create a to-do list in HTML, CSS and pure JS.
const dSubmit = document.getElementById('submit');
const storeData = [];
let typer = document.getElementById('type');
let input = document.getElementById('text');
const list = document.getElementById('listHolder');
dSubmit.addEventListener("click", (e) => {
e.preventDefault();
if (input.value == "") {
typer.innerHTML = "Please enter a task";
} else {
typer.innerHTML = "";
store();
}
});
function store() {
const tData = document.getElementById('text').value;
storeData.push(tData);
updater();
input.value = "";
}
function deleter (index) {
storeData.splice(index, 1);
updater();
}
function updater() {
let htmlCode = "";
storeData.forEach(function(item, index){
htmlCode += "<div class='test'><div id = "+ index +">" + item + "</div><div class='sideBtn'><button type='button' class='edit' onClick= 'editF("+ index +")'>Edit</button><button class='delBtn' onClick= 'deleter("+ index +")'>Delete</button> </div> </div>"
})
list.innerHTML = htmlCode;
}
function editF (index) {
let tempOne = document.getElementById(index);
let tempTwo = "<input id='inputText"+String(index)+"' type='text' name='task' value ='" + String(storeData[index]) + "'><button id='saveText"+String(index)+"' onClick= 'save("+index+")' >Save</button>"
tempOne.innerHTML = tempTwo;
}
function save (index) {
console.log('test1')
let tempOne= document.getElementById('saveText'+String(index));
let tempTwo = document.getElementById('inputText'+String(index));
console.log('test2')
tempOne.addEventListener("click", function foo (){
console.log('test3')
storeData.splice(index,1,tempTwo.value)
updater()
}
)
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<title>To Do List</title>
</head>
<body>
<h1>To-do-list</h1>
<form>
<label for="task">Please enter item:</label>
<input type="text" name="task" id="text">
<button id="submit">Submit</button>
</form>
<div id='type'></div>
<div>List:</div>
<div id="listHolder" class="test"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
I am facing problems with the save function. If I edit an item in the to-do list and click the save button, the function executes up to the point of console.log('test2'). If I click save again the function executes in its entirety.
I would like to ask why the first click results in execution of the save function up to 'test2'?
Additionally would anyone be kind enough to critique my JS? are there things in dire need of improvement? or is there a more practical/efficient method of writing my JS code?
Thank you for your help in advance.
After the 'test2' log, you are adding an event listener, and the rest of the code is inside of the listener block. The code in the listener block is only executed once that listener receives a 'click' event, which is why it works the second time.
So, I am trying to write a do-while loop statement that prints out the statement of my loop, but my browser isn't printing my text. How can I edit my code to do so?
<!DOCTYPE html>
<html>
<head>
<title>9. Looping Statements in Javascript</title>
</head>
<body>
<h1>9. Looping Statements in Javascript</h1>
<div id="playlist"></div>
<div id="someResult"></div>
<script>
var playlist = [];
playlist[0] = "Willy Wesly";
playlist[1] = "Childish Gambino";
playlist[2] = "Chance The Rapper";
playlist[3] = "Travi$ Scott";
playlist[4] = "Yeezy";
// while
/*
var i = 0;
while (i < playlist.length) {
var element = document.createElement('div');
element.innerHTML = "Now Playing: " + playlist[i];
i++;
document.body.appendChild(element);
}
*/
// do - while
var someResult = false;
do {
var element = document.createElement('div');
element.innerHTML = 'Will print AT LEAST once!';
}
while(someResult);
</script>
</body>
</html>
You need to add the element to the document body.
var someResult = false;
do {
var element = document.createElement('div');
element.innerHTML = 'Will print AT LEAST once!';
//You need to add it to the body for it to show on the page
document.body.appendChild( element );
}
while(someResult);
JSFiddle showing this: http://jsfiddle.net/azgxh59q/
All browsers except for Internet Explorer properly call the javascript and add them to the page.
I see a lot of posts on JSONP problems in IE, but I haven't come across one in this form. Why is the function issuesToList not called?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="RedmineJSONP.js"></script>
<title></title>
</head>
<body>
<header>
<h1>List of Issues</h1>
</header>
<div id="container"></div>
<script src="http://www.redmine.org/issues.json?callback=issuesToList"></script>
</body>
</html>
function issuesToList(data) {
var count = data.issues.length;
for (i = 0; i < count; i++) {
var issue = data.issues[i];
loadIssue(issue);
}
}
//Create an issue instance and append to Ui
function loadIssue(issue){
var button = document.createElement("button");
button.innerHTML = "+";
button.setAttribute("onClick", "toggleInfo(this)");
var p = document.createElement("p");
var item = document.createElement("div");
item.setAttribute("id", issue.id);
item.setAttribute("class", "issue");
item.appendChild(button);
item.innerHTML += " " + issue.subject;
item.appendChild(p);
var container = document.getElementById("container");
container.appendChild(item);
}
EDIT Removed the double http://
I'm trying to get the image to change based on one second timer, but the image stays one the first object in the array
the code I have so far is
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 8 - Jackhammer Man</title>
<script type="text/javascript">
var jackhammers = new Array();
jackhammers[0] = "<img src='Images/jackhammer0.gif'>";
jackhammers[1] = "<img src='Images/jackhammer1.gif'>";
jackhammers[2] = "<img src='Images/jackhammer2.gif'>";
jackhammers[3] = "<img src='Images/jackhammer2.gif'>";
jackhammers[4] = "<img src='Images/jackhammer4.gif'>";
jackhammers[5] = "<img src='Images/jackhammer5.gif'>";
jackhammers[6] = "<img src='Images/jackhammer6.gif'>";
jackhammers[7] = "<img src='Images/jackhammer7.gif'>";
jackhammers[8] = "<img src='Images/jackhammer8.gif'>";
jackhammers[9] = "<img src='Images/jackhammer9.gif'>";
jackhammers[10] = "<img src='Images/jackhammer10.gif'>";
var curJackhammer;
function bounce() {
var img = document.getElementsByTagName("img");
var i = 0 ;
for (i = 0; i<10;i++) {
if(jackhammers[i].src == img.src) {
if(i === jackkhammers.length) {
img.src = jackhammers[0].src;
break;
}
img.src = jackhammers[i+1].src;
break;
}
}
}
</script>
</head>
<body>
<img onMouseOver="setInterval(function(){bounce},1000);" onMouseOut="clearInternval(fuction(){bounce};" src="Images/jackhammer0.gif" id="hammer" name="hammerman" alt="Jackhammer Man">
</body>
</html>
The issue I'm coming across is the mouseover event will not activate, I am having trouble finding the error in my code as the debuggers I have aren't finding any. Any help trying to get the mouseover function of the image changing ever so often would be appreciated.
you have a typo if(i === jackkhammers.length)
jackhammers[x] has no src property so to get its value use it without .src
instead of
onMouseOver="setInterval(function(){bounce},1000);"
write:
onMouseOver="setInterval(function(){bounce();},1000);"
var img = document.getElementsByTagName("img");
This returns a NodeList, or an array of elements. You need to access the index of this element with [0]
Or better yet, use querySelector which returns the first element in a NodeList
You keep referring to the src property of items in the jackhammers array:
img.src = jackhammers[0].src;
even though items in that array are strings, not objects.
Also, there's a typo here:
if(i === jackkhammers.length) {
These kinds of errors would be immediately visible the with dev tools of your browser of choise. Put a breakpoint to where you suspect things go wrong and start investigating variables and your assumptions while stepping through the code.
See here: http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820
Updated code changed a few things around based on some advice from my mentor.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 8 - Jackhammer Man</title>
<script type="text/javascript">
var jackhammers = new Array(11);
jackhammers[0] = "Images/jackhammer0.gif";
jackhammers[1] = "Images/jackhammer1.gif";
jackhammers[2] = "Images/jackhammer2.gif";
jackhammers[3] = "Images/jackhammer3.gif";
jackhammers[4] = "Images/jackhammer4.gif";
jackhammers[5] = "Images/jackhammer5.gif";
jackhammers[6] = "Images/jackhammer6.gif";
jackhammers[7] = "Images/jackhammer7.gif";
jackhammers[8] = "Images/jackhammer8.gif";
jackhammers[9] = "Images/jackhammer9.gif";
jackhammers[10] = "Images/jackhammer10.gif";
var curJackhammer = 0;
var direction;
var begin;
function bounce(){
if(curJackhammer == 10)
curJackhammer = 0;
else
++curJackhammer;
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer].src;
if(curJackhammer == 0)
direction = "up";
else if(curJackhammer == 10)
direction = "down";
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer];
}
function startBouncing(){
if (begin)
clearInterval (begin);
begin = setInterval("bounce()",90);
}
</script>
</head>
<body>
<h1>Jackhammer Man</h1>
<p><img onMouseOver="startBouncing();" onMouseOut="clearInterval(begin);" src="Images/jackhammer0.gif" height="113" width="100" alt="Image of a man with a jackhammer." /></p>
</body>
</html>
>
Used firebug to step into code, works once I set into it but simply putting a mouse over nothing happens.
I have found the below code to check the count of times the button has been clicked. However, I would like the button to redirect to an URL once it is clicked and update the click count.
<html>
<head>
<title>Increment count when button is clicked</title>
</head>
<body>
<input type="button" value="Count" id="countButton" />
<p>The button was pressed <span id="displayCount">0</span> times.</p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function(){
count++;
display.innerHTML = count;
}
</script>
</body>
</html>
button.onclick = function(){
count++;
display.innerHTML = count;
window.location = "http://jonathanmh.com";
}
This would do the trick, but nobody would ever see the number, because it simply goes away, after the user is redirected to another page. If you want to save the number for other users to see, you need to save it on the server and preferably in a database.
To achieve that you need to store click count in cookie or localStorage (or anywhere else where your data persists):
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function(){
if (isNaN(localStorage.yourCounter))
localStorage.yourCounter = 0;
localStorage.yourCounter++;
display.innerHTML = localStorage.yourCounter;
window.location = 'http://jsfiddle.net/'
}