Appending Button not working - javascript

function story1(){
var t=document.createElement('p');
t.innerHTML = "You wake up from your sleep in a half daze to hear noises of screams outside your bedroom window. You stumble over there to see what is the matter. You decide it's a good idea to grab your"+' <i onclick=addSword()> '+" sword "+' </i> '+"as you take the "+' <i onclick=story2()> '+" stairs. "+'</i>';
document.getElementById("story").appendChild(t);
}
function story2(){
var t = document.createElement('p');
t.innerHTML = "You realize that the door is locked and need to break the code in order to go outside." +' <i id="one" onclick=addOne()> '+ num1 +'</i>'+' <i id="two" onclick=addTwo()> '+ num2+'</i>'+' <i id="three" onclick=addThree()> '+ num3 +'</i>';
document.getElementById("story").appendChild(t);
var b = document.createElement('input');
b.type = 'button';
b.value = 'Check Code';
b.onclick = checkCode();
document.getElementById("story").appendChild(b);
}
In short these two functions are where my issue lies. I'm trying to append a button inside of a div to check to see if the code is broken. The coding for checkCode is working as is.
The issue is, that checkCode() is actually working when stairs in clicked instead of the button. I've tried b.on('click', checkCode()) and b.setAttribute('onclick', checkCode()).
Maybe I'm not coding the button right, but tutorials and reading answers to similar problems can only get me so far! (lol)
Thanks in advance!

Your issue is that you are setting the result of the function checkCode to the handler/attribute in stead of the function reference. You are invoking it.
Try:
b.onclick = checkCode;
or
b.on('click', checkCode);
You need to set the reference of the function to the handler. setting it with () will invoke the function then and there and hence you see the behavior.

Related

javascript query selector and const issue

hope you can clarify an issue I am having that is driving me crazy:
I am trying to get te value of the inpt "#size" in JS, I am using the comand:
submit.addEventListener('click', function(e){
document.querySelector('#output').innerHTML = document.querySelector('#size').value;
document.querySelector('#size').value = '';
})
it works like this, but the thing is that i can not declare the variables to make my code shorter and to handle the data latter, if I use:
const submit = document.querySelector('#submit');//refers to the button to activate the event listener
submit.addEventListener('click', function(e){
document.querySelector('#output').innerHTML = document.querySelector('#size').value;
document.querySelector('#size').value = '';
})
it does not get any value from the size, console says:
Uncaught SyntaxError: Identifier 'submit' has already been declared
it is an error that is happening often and I still not able to solve, hope some of you guys an clarify what am I doing wrong.
EDIT:html code below:
<body>
<input type="text" id="size">
<button id="submit">Sumbit</button>
<ul id="output">
</ul>
<script src="functtions.js"></script>
</body>```
thanks
You certainly have another variable called submit somewhere else. Using function usually prevent such variable collision problem, so what about this kind of code?
function () {
let submit = document.querySelector('#submit');
let size = document.querySelector('#size');
let output = document.querySelector('#output');
submit.addEventListener('click', function(e){
output.innerHTML = size.value;
size.value = '';
});
}();

Why are the images not coming up for document.createElement

I am a very novice coder and I am creating a game that calculates the area of a given rectangle however once the page loads, the image does not show and thus the user cannot answer the question.
An example image has been copied below
The "score" does not display either. Any help would be greatly appreciated :)
var number1;
var number2;
var response;
var calcanswer;
var score = 0;
window.onload = areaquestion1;
myScore.text = "SCORE: " + score;
function areaquestion1() {
var question = document.createElement("question");
question.setAttribute("src", "Images/2*1.png");
question.setAttribute("width", "304");
question.setAttribute("height", "228");
question.setAttribute("alt", "2*1");
document.body.appendChild(question);
var number1 = 2
var number2 = 1
calcanswer = (number1*number2);
var question = document.getElementById("question");
question.innerHTML = "What is the area of this lego brick?";
check();
areaquestion2();
}
function areaquestion2() {
var question = document.createElement("question");
question.setAttribute("src", "Images/3*2.png");
question.setAttribute("width", "304");
question.setAttribute("height", "228");
question.setAttribute("alt", "3*2");
document.body.appendChild(question);
var number1 = 3
var number2 = 2
calcanswer = (number1*number2);
var question = document.getElementById("question");
question.innerHTML = "What is the area of this lego brick?";
check();
areaquestion3();
}
function check()
{
var statusDiv = document.getElementById("status");
response=document.getElementById("answer").value;
if(response != calcanswer)
statusDiv.innerHTML="Incorrect";
else
if (response==calcanswer)
{
statusDiv.innerHTML="Very good!";
score ++;
document.getElementById("score").textContent = score
document.getElementById("answer").value = "";
problem();
}
}
<!DOCTYPE html>
<html>
<title>Lego Area</title>
<head>
<link rel="stylesheet" href="CSS/Play.css">
<script src="JavaScript/Play.js"></script>
</head>
<body onload="areaquestion1();">
<div class="header">
<h1>LEGO AREA</h1>
<p>Calculating <b>area</b> with Emmet.</p>
<div id="score" class="score" value="SCORE:"></div>
</div>
<form>
<div class="row">
<div class="side">
<div id="question"></div>
<div id ="prompt"></div>
<input type="text" id="answer"/>
</div>
<div class="main">
<input id="solve" type="button" value="CHECK!" onclick="check()" />
</div>
</div>
</form>
<div id="status"></div>
<!-- Footer -->
<div class="footer">
<div class="practice"> <img src="Images/legoBlue2.png" id="practicebtn" width="20%"></div>
<div class="play"> <img src="Images/legored2.png" id="playbtn" width="20%"></div>
</div>
</body>
</html>
This is my first question I'm attempting to answer -- so pretty big deal. Anyway...
A few things I noticed:
I got pretty confused reading the code seeing the question variable being used so much for different parts of the code. So I changed the var question to var imageBlock to make it more readable for me.
You were running the areaquestion1() function onload. Since the check() function was run as a part of the areaquestion1() function it was being run as well, in-turn displaying 'Incorrect' even before an answer was entered. I changed this to document.getElementById("solve").check(); to ensure it runs only after the CHECK! button was clicked.
Finally getting to your actual question. It looks like you are trying to use document.createElement to create an image with an id of question, however based on geeks for geeks and W3 Schools you use the document.createElement to create the img element. THEN you can set the id attribute to whatever you like. In this case, I switched it to imageBlock.setAttribute("id", "madeUpImg"); to help with my readability.
So this is what I did, I think there are a lot of improvements you can make, but this works and it will give you a good start:
function areaquestion1() {
var imageBlock = document.createElement("IMG");
imageBlock.setAttribute("id", "madeUpImg");
imageBlock.setAttribute("src", "guWFE.png");
imageBlock.setAttribute("width", "304");
imageBlock.setAttribute("height", "228");
imageBlock.setAttribute("alt", "2*1");
document.body.appendChild(imageBlock); // this appends it to the bottom of the page
number1 = 2
number2 = 1
calcanswer = (number1*number2);
var question = document.getElementById("question");
question.innerHTML = "What is the area of this lego brick?";
document.getElementById("solve").check();
// areaquestion2(); }
All of this is edited to address your further questions:
For appending it in the appropriate spot: I haven't had time to jump back in my code, but this is what I'm thinking. Currently, when you read your code you have document.body.appendChild(question); This JavaScript is telling the computer to find the document, then find the body of that document, then run the appendChild function. So, basically it is saying - "computer, append the question variable to the body of the document". So, what's wrong with this? Well, you want to append it to a specific div! So, you're extremely close, but you're not grabbing the question div! You need to use code to tell the computer to find the question div, then append the image to that div. I'd do something like this: document.getElementById('question').appendChild(imageBlock) this now means the code is grabbing onto the div that you want to append it to then, appending the imageBlock to that div.
I commented out that areaquestion2 because I know you're going to run into more problems. 1. If you call the areaquestion2in the areaquestion1 function it will run immediately when the website loads (you're calling the area question1 on load). I think this is going to make both images appear at the same time. Why? It is just being instructed to append another image to the question div. 2. You probably don't want both images appearing at the same time. So, you're going to need to find a way to replace the first image rather then trying to add another one.
That's about all I can help you with on this for now. I think that if you continue to work through this then refactor it, you're going to learn a ton. I think you should try to bring this to one function by assigning questions to variables, then passing those variables in as arguments to your function. If you haven't already, I'd highly recommend going through FreeCodeCamp's stuff lesson by lesson.
Hope this helped!!

Variable will not increment and register its new value

What I am trying to do: I have a button in html with the id "c1si" and onclick I have it linked to a function in my javascript that is supposed to increment by a factor of 1 a variable called "car1". Then I have an IF statement linked to onclick wired to my submit button that is suposed link to another page, if car1 is equal to 1.
MY CODE:
var car1
car1=0
document.getElementById("c1si").onclick = function() {
this.style.backgroundColor = "Green"
this.disabled = true;
car1++
return car1;
}
if ( car1==1) {
function changehref() {
var link = document.getElementById("link");
link.setAttribute('href', "page1.html");
}
}
HTML:
<a href="#" id="link" onclick="changehref()" ><button type="button" id="resultados" >submit</button></a>
<button type="submit" class="stylebutton" id="c1si" style="background-color:white" > SI </button>
What is the problem: Once I click on "c1si" I can see in the console log that car1 goes from 0 to 1, but my if statement still takes car1 as 0 and not as 1, so the if statement is false and does not redirect me to page1.html. I am really at a loss here. All I want is for my variable to increase each time I click on it so it can redirect me. Please help, Iam new to coding.
As you said in your question, you're seeing the car1 variable increment to 1. But the IF statement isn't resulting in a redirect. In your IF statement, you are defining a function called changehref(). First off, that's poorly formatted code, and I'd encourage you to define that function elsewhere. But more importantly here, that IF statement has no reason to ever be executed aside from when the script is first loaded.
You'll want to pull that IF statement into your onclick function.
var car1 = 0;
document.getElementById("c1si").onclick = function() {
this.style.backgroundColor = "Green";
this.disabled = true;;
car1++;
if (car1 == 1) {
changehref();
}
}
function changehref() {
var link = document.getElementById("link");
link.setAttribute('href', "page1.html");
}
Realistically, since the increment is guaranteed, you could remove the car1 variable and IF statement entirely, and just call the changehref() function in the onclick.

How to use event listener in JS

Im trying to use the same buttons for different function in the program. So I tried using event listeners but for some reason its not working. Could look at the code and tell me what I have done wrong? Thanks. (I omited the HTML tags and so for shortening the posted code)
<script type="text/javascript">
var photo = "photo";
var edgar = "edgar"
var x = document.getElementById("yes");
x.addEventListener("click", choiceyesstory);
x.addEventListener("click", choiceyesfriendly);
var y = document.getElementByID("no");
y.addEventListener("Click", choicenostory);
y.addEventListener("click", choicenofriendly);
function choiceyesstory(x) {
document.getElementById("photo").src = "images/dragon1.jpg";
document.getElementById("stage1").innerHTML = "Once upon a time";
setTimeout("choice2()",5*1000);
}
function choicenostory(y) {
document.getElementById("photo").src = "images/sea.jpg";
document.getElementById("stage1").innerHTML = "Would you like to
listen to some music?";
document.getElementById("edgar").play();
}
function choice2(x){
document.getElementById("photo").src = "images/dragon9.jpg";
document.getElementById("stage1").innerHTML = "Was he a friendly
dragon?";
}
function choiceyesfriendly(x) {
{document.getElementById("photo").src = "images/dragon2.jpg";
document.getElementById("stage1").innerHTML = "He had many friends";
}
function choicenofriendly(y)
{ document.getElementByID ("photo").src = "images/dragon3.jpg";
document.getElementById("stage1").innerHTML = "He did so and so";
}
</script>
<body>
<button id="yes">Yes</button>
<button id="no">No</button>
</body>
Edit / Delete Edit Post Quick reply to this message Reply Reply With Quote Reply With Quote Multi-Quote This Message
Reply to Thread
Quick Navigation DOM and JSON scripting Top
Quick Reply Quick Reply
I took yours js and simplified it. The event listener by itself is working ok. Maybe you have issue somewhere else.
http://jsfiddle.net/jnmav1wk/
var x = document.getElementById("yes");
console.log(x);
x.addEventListener("click", choiceyesstory);
function choiceyesstory(x) {
alert('Clicked');
}
Try to simplify your problem, get rid of the NO and all corresponding code, keep removing code till it's working. Then add feature by feature till it will stop working and you know where it's broken.
I use console.log(); and alert(); to make it more verbose to me.
Sometimes the code needs to be inside this:
$( document ).ready(function() {
yourCode();
});
This needs jQuery, if you want avoid it, here are some alternatives:
$(document).ready equivalent without jQuery
Because if the functions are executed against HTML code which is in middle of loading (and maybe the YES button is not there yet while you try to attach the event listener to it, etc...)

how to make the following code faster?

I am developing a application with phonegap. on my pc everything runs fine but on my mobile device its just too slow.
i think the problem is on the show function, the android browser seems to needs really long to hide and show elements
what can be improved?
function show(id){
$('.view').hide()
//alert('show ' + id)
$('#'+id+'View').show()
scroll(0,0)
}
function getSoundHTML(id, myname, del){
if (del != true){
var imgsrc = 'plus.png'
var f = function(){
addToCostumSounds(id)
alert('added to favorites')
}
}else{
var imgsrc = 'minus.png'
var f = function(){
removeFromCostumSounds(id);
$(this).fadeOut().next('div').fadeOut();
}
}
var div = $('<div></div>').addClass('box').html(myname).css('border-color', '999999').click(function(){
play(id)
})
var img = $('<img></img>').attr('src', imgsrc).addClass('sideimg').click(f)
return $('<div></div>').append(img).append(div)
}
for(var category in categories){
var f = function(category){
$('#'+category+'Btn').click(function(){
show(category)
var categoryView = $('#'+category+'View')
for(var key in categories[category]){
var div = getSoundHTML(key, categories[category][key])
categoryView.prepend(div)
}
var img = '<img src="menu.png" class="menuimg"/>'
categoryView.prepend(img)
categoryView.append(img)
})
}
f(category)
}
the html:
<div class="btn" id="noBtn">no _</div>
<div class="btn" id="thatIsBtn">that is _</div>
<div class="btn" id="thereIsBtn">there is _</div>
<div class="btn" id="thisIsBtn">this is _</div>
...
<div class="view" id="noView"></div>
<div class="view" id="thatIsView"></div>
<div class="view" id="thereIsView"></div>
<div class="view" id="thisIsView"></div>
...
Whilst it may not have an effect on Desktops, your massive lack of semi-colons in the right places may have an effect on mobile devices.
The JavaScript engine has to run through and try to work out where the semi-colons need to go. See this transcript from the ECMAScript specification.
To be honest I think thats only a few milliseconds of time-saved, but its a starting point for now - and good practice for the future.
Here's your problem:
for(var category in categories){
var f = function(category){
...
for(var key in categories[category])
...
}
f(category)
}
You have two BIG issues here:
You're defining a function within a loop. While this is sometimes needed, you should do your very best to avoid defining things within a loop unless you absolutely need to. In this case, you could probably move the f function out of the loop entirely without breaking your code.
Nested loops. You have a for ... in within a for ... in loop. This is largely due to the first problem I pointed out, but in general nested loops are a big no-no from a performance standpoint.
ok, i think i got the only way to improve the peroformance:
if someone clicks on a button (class="btn") he is redirected to a new fresh page that has the entire page in HTML and does not build it with javascript.

Categories