I need help with Javascript fundamentals the issue I am having is with my start button when it clicks on it supposed to create a prompt that asks the user for the first name and have it stored within that variable you created. I have the doc ready function working okay however the button is not working properly.
Here is my code and thank you for helping me
<!-- Name: <Put name here> Date: <Put date here> Class: CSCI2447, Javascript Fundamentals Project X \-->
<!DOCTYPE html>
<html>
<head>
<title>POP-The- Bubble (CSCI2447)</title>
<!-- CSS styles: This is for me to worry about; not you. -->
<link href="css/game.css" rel="stylesheet" />
<link href="[https://fonts.googleapis.com/css2?family=Sunshiney&display=swap](https://fonts.googleapis.com/css2?family=Sunshiney&display=swap)" rel="stylesheet">
<script src = "jquery-3.5.1.min.js"> </script>
<script> $( document ).ready(function() { var first Name = prompt("Enter First Name of Gamer:"); </script>
</head>
<body>
<div id="content">
<h1>Pop-The-Bubble</h1>
<p>After clicking "start", you will have 30 seconds to click
on as many bubbles as you can. The bubbles will appear quickley so be ready!
</p>
<div id="controls">
<span id="score">0 pts</span>
<button type="button" id="start\_button">Start!</button>
</div>
<div id="gamespace">
<img class="gameimage" src="img/bubblefun2.png" height = "120" width = "120"
</div>
</body>
</html>
Your function should close with the closing curly braces } and bracket ) => })
$( document ).ready(function() { var firstName = prompt("Enter First Name of Gamer:") });
Also you have a space between first and Name, this will throw an error in javascript Unexpected identifier. Remove the space so it is one string as the variable name firstName
Related
I'm new to javascript and this has been driving me nuts for the last hour
Here's the html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Number Guessing Game</title>
<link rel="stylesheet" href="styles/main.css">
</head>
<body>
<h1>Number Guessing Game</h1>
<p>Greetings hominid. I've selected a number between 1 and 100. See if you can guess it in 10 turns or fewer. I'll tell you if your guess was too high or too low.</p>
<label for="guess">Enter your guess:</label>
<input id="guess">
<button id ="submit">Submit</button>
<p id="response"></p>
<p id="guess-count"></p>
<p id="previous-guesses"></p>
<script src = scripts/game.js ></script>
</body>
</html>
And here's the javascript
const submitButton= document.getElementById('submit')
alert('hi')
submitButton.onClick = function submitGuess() {
alert('button is live')
}
For some reason the submitGuess function is not being executed at all (at least I'm not seeing the alert). I had a lot more javascript but I reduced it to find out why it wasn't working.
Any help is much appreciated
As pointed out in the comments, you can add the event handler in the JavaScript via EventTarget.addEventListener, rather than the inline HTML attribute. For example:
document.querySelector('#submit').addEventListener('click', event => {
console.log(`${event.target.id} was clicked`)
});
<h1>Number Guessing Game</h1>
<p>Greetings hominid. I've selected a number between 1 and 100. See if you can guess it in 10 turns or fewer. I'll tell you if your guess was too high or too low.</p>
<label for="guess">Enter your guess:</label>
<input id="guess">
<button id="submit">Submit</button>
<p id="response"></p>
<p id="guess-count"></p>
<p id="previous-guesses"></p>
const submitButton = document.getElementById('submit')
this line get the value before the DOM fully loaded the solution is to define the const after the page load like this
window.onload = function(){
const submitButton = document.getElementById('submit')
alert('hi')
if(submitButton){
submitButton.addEventListener('click', function() {
alert("Clicked!");
});
}else{
alert("Something Wrong")
}
}
I've a landingpage with dynamic html tags.
The Problem is, that i can't select directly the tag. Its a link.
the following code is the construct:
<div id="testid"><div><div>Button 1<div><div><div>
Every time someone clicks on the link (a-tag) I want to fire an event like the following code:
Button 1
the question: what is the Javascript code to add the onclick="dataLayer.push({'event': 'button1-click'}) attribute to the a tag.
I tried the following code:
var d = document.getElementById("testid").firstchild;
d.setAttribute("onclick", "dataLayer.push({'event': 'button1-click'})");
but it seems to the code is incorrect. The a tag is also not the first child; there are 2 divs between :(
Use querySelector and addEventListener:
document.addEventListener('DOMContentLoaded', function () {
var dataLayer = [];
var d = document.querySelector("#testid a[name=button1]");
d.addEventListener("click", function () {
dataLayer.push({ 'event': 'button1-click' });
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="testid">
<div>
<div>
Button 1
<div>
<div>
<div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="script.js">
</script>
</body>
</html>
There's a few things you were missing from your JS.
Using a more specific selector (#testid a[name=button1] vs. the firstchild of #testid, which was not accurate).
Wrapping all the code in a DOMContentLoaded listener. JS that depends on elements on a page needs to wait for the page to build first, that's what DOMContentLoaded is.
Check out my solution. Hope this helps.
var d = document.querySelector("#testid a");
var dataLayer = []
d.onclick = function () {
dataLayer.push({'event': 'button1-click'})
console.log(dataLayer.length)
}
<div id="testid"><div><div>Button 1<div><div><div>
I'm trying to improve my Javascript by starting a simple web interface, but every time I try to add an event listener to an input field, it breaks my code.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="colors.css">
<script src="spot.js"></script>
</head>
<div id="ask">
Search for an artist to see their top songs:
</div>
<form>
<input type="text" name="artist" id="artist-search">
</form>
<div id="sub">
submit
</div>
</html>
And here's my Javascript:
window.onload = loaded;
var inField;
function loaded() {
document.getElementById("sub").addEventListener("click", search);
inField = document.getElementById("artist-search");
}
//https://api.spotify.com/v1/search?q=tania%20bowra&type=artist
function search() {
alert();
//var query = "//https://api.spotify.com/v1/search?q=";
}
When I add the getElementById to "artist-search", the alert in the search function stops working. Why is this? And is there a better way to get the text in an input field when someone clicks a submit button using vanilla Javascript?
I'm messing around with Handlebars.js and I'm doing a very simple example consisting of a tutorial from a website(the shoes section) and my own simple little template(the heading, where the problem is)
handlebardemo.html
<head>
<meta charset="ISO-8859-1" name="viewport" content="width=device-width, initial-scale=1">
<title>Handlebar demo</title>
<script src="lib/jquery-2.1.4.js" type="text/javascript"></script>
<script src="lib/jquery-ui.js" type="text/javascript"></script>
<script src="lib/handlebars-v4.0.4.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/w3.css">
<link rel="stylesheet" href="css/jquery-ui.css">
</head>
<body>
<div class="username-container">
<script id="heading-template" type="x-handlebars-template">
<h1 class="h1">Hello {{username}}</h1>
</script>
<input type="text" id="username">
<button type="submit" id="username-submit">Enter</button>
</div>
<h4 class="w3-row-padding">Shoe List:</h4>
<ul class="shoesNav w3-ul w3-text-indigo"></ul>
<script id="shoe-template" type="x-handlebars-template">
{{#each this}}
<li class="shoes">{{name}}--Price:{{price}} </li>
{{/each}}
</script>
</body>
main.js
$("#username-submit").click(function(){
var uNameVal = $("#username").val();
var uName = {"username":uNameVal};
var theTemplateScript = $("#heading-template").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(".username-container").append(theTemplate(uName));
});
$(function (){
var shoesData=[{name:"Nike", price:199.00}, {name:"Loafers", price:59.00}, {name:"Wing Tip", price:259.00}];
//Get html from tempalte in script tag
var theTemplateScript = $("#shoe-template").html();
//Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
$(".shoesNav").append(theTemplate(shoesData));
//shoesData is passed to compiled handlebars function
//function inserts values from the objects in their respective places in the HTML
//and returned HTML: as a string. Then jQuery is used to append the resulting HTML string to the page
})
Im not sure if I'm using the handlbars syntax etc. correctly, but i based it mostly off of the second function in main.js, which came from a brief handlebars tutorial
When I click the Enter button, nothing happens. There are no console errors, it just does nothing. Am I going about this the wrong way, at least compared to the unordered list example?
EDIT: As per Elli Parks answer, I added an id to the submit button and changed the click handler assignment to the submit button rather than the textbox(a silly mistake on my part). The element still won't appear when the submit button is clicked
In main.js, you're attaching the click handler to #username, which is an input field. You need to give the Enter button an id (ex: #username-submit) and attach the click handler to the button.
So something like this:
handlebardemo.html
<button type="submit" value="Enter" id="username-submit" >Enter</button>
main.js
$("#username-submit").click(function(){
var uNameVal = $("#username").val();
var uName = {"username":uNameVal};
var theTemplateScript = $("#heading-template").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(".username-container").append(theTemplate(uName));
});
You need to change two things:
fix the selector to target the button, like #ElliPark has already said
put the whole thing into the document-ready handler (ie, into the $(function () {...} ); construct. You are trying to attach the event listener before the DOM is ready.
See the demo on JSBin.
I've created a simple page which uses a JavaScript file and the onClick method to display different div tags. I have a much more complex program which signs a user in using ajax, it works fine in a browser but not in the popup
The more I read, and I've read everything on the developers site that I can find the more confused I get. Chrome extensions do not allow inline JavaScript which is fine, but I'm still not sure how I can actually write JavaScript. I know it has something to do with event handlers, but even that is just me guessing.
Can anyone take this program and show me what I need to change to get it to work in a popup using "manifest_version": 2 and no hacks. How do Google expect people to use JavaScript? There really needs to be a hello world program showing how to do this.
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title> Pop Up </title>
<script src = "test.js"></script>
<style type = "text/css">
#signout
{
display:none;
}
</style>
</head>
<body>
<!-- ///////////////////////////////////////////// -->
<!-- //////////////// Log In Screen ////////////// -->
<!-- ///////////////////////////////////////////// -->
<div id = "login">
<form method="post" action="">
Username:
<input type="text" name = "user" id = "user"><br>
Password:
<input type="text" name = "pass" id = "pass"><br>
<input type="button" value="submit" onClick="logInPHP()" />
</form>
</div>
<!-- ///////////////////////////////////////////// -->
<!-- //////////////// Sign Out Screen //////////// -->
<!-- ///////////////////////////////////////////// -->
<div id = "signout">
Your are Currently signed in.<br />
Sign Out
</div>
</body>
</html>
Javascript:
function logInPHP(){
document.getElementById("login").style.display = "none";
document.getElementById("signout").style.display = "inline";
}
function signOutPHP(){
document.getElementById("login").style.display = "inline";
document.getElementById("signout").style.display = "none";
}
You can't use onclick attributes directly in the HTML file. Remove them and wrap your JavaScript code into the document 'DOMContentLoaded' event listener.
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("login").addEventListener('click', function(){
document.getElementById("login").style.display = "none";
document.getElementById("signout").style.display = "inline";
});
document.getElementById("signout").addEventListener('click', function(){
document.getElementById("login").style.display = "inline";
document.getElementById("signout").style.display = "none";
});
});