Bug displaying a div element when a user clicks on a button - javascript

I'm writing a webpage and I need to display a div with some content when a user clicks on a button.
I've written the code below and I don't understand why it doesn't work.
Does someone know why ?
My code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
<script type="text/javascript">
function traverse(){
output.innerHTML+='Test'; // Nothing happens !
}
function check() {
var keywords = document.getElementById('text').value.split(" ");
for (var i=0; i < keywords.length; ++i) {
traverse_tree()
}
}
</script>
</head>
<body onload ="init()">
<input id="text" type="text" size="60" value="Type your keywords here" />
<input type="button" value="Display the text 'Test'" onclick="check();" />
<div id="output">
</div>
</body>
</html>
thanks,
Bruno

Perhaps because the function is called traverse() and you're calling traverse_tree()?

Also, in your method traverse, you should get the element using document.getElementById('output'), instead of using a (undefined) variable output:
i.e:
function traverse(){
document.getElementById('output').innerHTML+='Test';
}
You could also speed this up by caching the node (to avoid calling getElementById each time the button is clicked):
// Create a closure by wrapping the cached node in a self-executing
// function to avoid polluting the global namespace
var traverse = (function (nodeId) {
// Cache the node to be updated here
var node = document.getElementById(nodeId);
// This is the function that "traverse()" will call. Return this function,
// which will assign it to the variable traverse.
return function () {
node.innerHTML += 'test';
};
// Execute the function with the id of the node to cache, i.e. output
}('output'));

Related

Animating a walk cycle using only Javascript and HTML

I'm working on a project for a friend and he wants a pure walk cycle with only HTML/JS (no CSS). So I've tried to work it out but the image only shows up on the webpage.
It doesn't move when I press any buttons or anything at all.
Please show me where I went wrong. I'm used to using HTML and CSS but this is my first JS so I don't know many terms.
How it appears in the website:
My code (HTML + JS):
<!DOCTYPE html>
<html>
<head>
<title>Javascript Animation</title>
<script language="Javascript">
<!--
var walker = new Array(6);
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5) curWalker == 0;
else ++curWalker;
document.animation.src = walker[curWalker].src;
}
-->
</script>
</head>
<body>
<p><img src="walk1.png" name="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval('marathon(),100);">
<input type="button" name="stop" value="stop" onclick="clearsetInterval(startwalking);">
</form>
</body>
</html>
Here it is how I did it get to work (I had to build my simple images with Paint in order to use them in the animation):
<html>
<head>
<title>Javascript Animation</title>
</head>
<body>
<p><img src="walker1.png" id="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval(marathon,100);">
<input type="button" name="stop" value="stop" onclick="clearInterval(startWalking);">
</form>
<script>
var walker = [];
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5)
curWalker = 0;
else
++curWalker;
document.getElementById("animation").src = walker[curWalker].src;
}
</script>
</body>
</html>
I had to correct several typos/mistakes:
Put the JS just before the </body> closing tag
The first paramether of setInterval() must be a function name, so it must be marathon (you had 'marathon(); note that leading single quote)
In order to get the image to be substituted it is better to access the element though Id instead of name attribute. So I changed the image to <img src="walker1.png" id="animation"> (animation is now the Id) and accessed it through document.getElementById("animation")
Now the animation starts... but stops to the last image instead of restarting to the first.
That was because you used to check the curWalker variable instead of performing an assignment: I put curWalker = 0; instead of curWalker == 0;
Almost there. The loop is complete, but the stop button doesn't work. Two typos are preventing this to work:
clearsetInterval doesn't exist. The function to be called is clearInterval
Javascript is a case sensitive language. You use startwalking variable as a parameter, but the correct variable name is startWalking. So you have to correct the onclick event writing clearInterval(startWalking); instead of clearsetInterval(startwalking);
Your animation is now complete.
Note: as correctly noted by #Mike 'Pomax' Kamermans, nowadays you can avoid the use of onclick as you can attach events to the document (such as "click") by using document.addEventListener.

Get current input value in function that is set as variable within another function. (I AM STUMPED) code examples within

I have a difficult question, I am trying to get the input value of an input field, however, I need this to happen within another function.
I already have code that works outside of this other function but I need to refactor it to work inside another function that I am calling.
Examples of working code and non-working code are below.
Here is the HTML where I am getting the input:
<!DOCTYPE HTML>
<HTML>
<head>
<title></title>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="css/styles.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/require.js"></script>
<script type="text/javascript">
(function () {
var config = {
baseUrl: "js",
};
var dependencies = ["otherFile"];
require(config, dependencies);
})();
</script>
</head>
<body>
<div>
<label>Input URL</label>
<input type="url" />
<p id="targetInput"></p>
</div>
</body>
</html>
Here is the non-working JS that I am trying to call within another function:
function someOtherFunction() {
var getCurrentInput = function() { };
var input = document.querySelector("input");
var log = document.getElementById("targetInput");
input.addEventListener("input", getCurrentInput);
var getCurrentInput = function (e) {
log.currentInput = e.target.value;
};
}
});
Lastly here is the working code that works outside of the scope of someOtherFunction
var getCurrentInput = "";
var input = document.querySelector("input");
var log = document.getElementById("targetInput");
input.addEventListener("input", getCurrentInput);
function getCurrentInput(e) {
log.currentInput = e.target.value;
}
Now you may notice that there isn't a form being submitted here, the reason for this is because this code is running on an iframe that is being called into another app. The submit is happening there but requires me to call a function to make it happen and technically isn't a submit, meaning I don't have control over it like a regular submit. This is why I need to call the current input value inside someOtherFunction.
Any help would be greatly appreciated here! Essentially I want to get the value inside the input and update my API with the value as a JSON string. There must be a better way!
Was a bit difficult to follow at first given the nesting, but something like this?
const doThing = (e) => {
let input = document.getElementById("input");
let log = document.getElementById("targetInput");
log.textContent = input.value;
}
<div>
<label>Input URL</label>
<input type="url" id="input"/>
<p id="targetInput"> </p>
</div>
<button onclick="doThing()">Click</button>
Essentially an external submit that takes an internal input value, and injects it into another internal element?

How to make a JavaScript result appear on the same page, not in an alert popup window

I was wondering instead of using the alert function to show the function result if there was a way to print it in a text field on the same page as the original variable input. Thanks!
create a div in your body for result like
<div id="result"></div>
update from script like
var resultDiv = document.getElementById("result");
resultDiv.innerHTML = <your value>
Without additional libraries, using only browser functions, you can do this with the document.getElementById() function like this:
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" id="textfield">
</body>
<script>
function someFunction() {
return "Hello world!";
}
document.getElementById('textfield').value = someFunction();
</script>
<html>

html script variable assignment

So I have a script block:
<script>
var totalPopulation = 0;
for(xxxxx){
totalPopulation = totalPopulation + xxx
}
</script>
<tr>
<input type="text" name="censusPop" value=totalPopulation/>
<tr>
I'm still quite green to javascript. But is there a way to assign the value of a variable in a script block to a HTML element like input type? I know that the code is unreachable.
hope it will help you to understand how javascript work
<html>
<head>
<script>
var totalPopulation = 0;
function addAndShowPopulation(population) {
totalPopulation = totalPopulation + population;
var input_tag = getTag('my_input_id');
input_tag.value = totalPopulation;
}
function startAdding() {
addAndShowPopulation(10);
setTimeout( function(){startAdding();},1000);
}
function getTag(id) {
return document.getElementById(id);
}
</script>
</head>
<body onload="startAdding();">
<div>
<input type="text" id="my_input_id" name="censusPop" value="" placeholder="Total Population"/>
</div>
</body>
</html>
Yes, you just have to give an id to the input, for instance "id = my_input_id";
Then, in the javascript, just write :
$("my_input_id").value=totalPopulation;
That's how ajax works: find html elements ids and fill them dinamically using javascript values.
Just be carefull that the html in read before the JS. If not, $("my_input_id") will return Null
More so, you need to do something like this:
<tr>
<td>
<input type="text" id="censusPop" name="censusPop" value=""/>
<td>
<tr>
<!-- Other stuff -->
<script>
var totalPopulation = 10;
// or for loop, or whatever here.
var censusText = document.getElementById('censusPop');
censusText.value = totalPopulation;
</script>
</body>
HTML and JavaScript can interact, but not directly like that. The best thing to do is use <script> tags to setup code that updates the browser DOM. By putting the <script> tags after the HTML, usually at the bottom of the <body> tag, you allow the browser a chance to create the elements before you actually try to use them.
Another note: <tr> tags should contain <td> tags, it's the difference between a row and a column.
If you need to do multiple DOM manipulations, I'd suggest using jQuery is the proper way.
<tr>
<input id="censusPop" type="text" name"censusPop" value=""/>
</tr>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
// make sure, the code is executed when the DOM is ready
$(function () {
// grab the input element by its ID
var $input = $('#censusPop'),
totalPopulation = 0;
// do your population calculations
totalPopulation = ....;
// assign the value to the input element
$input.val(totalPopulation);
});
</script>

How do I assign the result of a function into a global variable?

I can't figure out how to assign this function's result into a global variable. I know this is a really basic thing, but can anyone help?
var pixel_code = null
function captureValue(){
pixel_code = document.getElementById("baseText").value;
return pixel_code;
}
pixel_code = captureValue();
Thanks for sharing the jsfiddle of what you were attempting. I see the concern. The captureValue() function is run asynchronously, so the console.log() shortly after defining it doesn't yet have a value. I've stripped and prodded the jsfiddle and come up with this working sample:
<html>
<head>
</head>
<body>
<h1>Welcome to the AdRoll SandBox</h1>
<textarea id="baseText" style="width:400px;height:200px"></textarea><br />
<input type="button" value="test" id="text_box_button" onclick="captureValue()"/>
<input type="button" value="get" id="text_box_button2" onclick="getValue()"/>
<script>
var pixel_code = null;
function captureValue(){
pixel_code = document.getElementById("baseText").value;
return false;
}
function getValue() {
alert(pixel_code);
return false;
}
</script>
</body>
</html>
I added a second button. Type in the textbox, push "test" (to set the value), then push "get" to get the value of the global variable.
Here's the same sample that uses jQuery and a closure to avoid the global variable:
<html>
<head>
</head>
<body>
<h1>Welcome to the AdRoll SandBox</h1>
<textarea id="baseText" style="width:400px;height:200px"></textarea><br />
<input type="button" value="test" id="text_box_button" />
<input type="button" value="get" id="text_box_button2" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
var pixel_code = null;
$("#text_box_button").click(function (){
pixel_code = document.getElementById("baseText").value;
return false;
});
$("#text_box_button2").click(function () {
alert(pixel_code);
return false;
});
});
</script>
</body>
</html>
If the page reloads, your variable will be reset to it's initial state.
You're reusing pixel_code in and out of the function, which is not a great pattern, but the code you show should work as expected. What error are you seeing? What code surrounds this code that you're not showing? Could all this perhaps be nested inside another function? (Thanks #JosephSilver for the nod.)
Please try this,
var pixel_code='';
function captureValue(){
return document.getElementById("baseText").value;
}
function getValueBack()
{
pixel_code = captureValue();
//alert(pixel_code); /* <----- uncomment to test -----<< */
}

Categories