How to create a console like in IRC in JavaScript - javascript

I am new all around HTML and JavaScript. Now I am trying to build a simple program that get input from the command line by the user and print it on the big console window. Now when I insert a simple text it does not print nothing into the box. Is there a special object should I use?
this is my code:
</head>
<body>
<img src="img/Mellanox_logo.jpg" alt="logo" align="middle">
<h1>Menu</h1>
<div id="container1" >
<div id="console" >
<p>
<script>
function showVal(){
var tmp = document.lineform.command_line.value;
document.getElementsByName('command_line').value = tmp;
}
</script>
</p>
</div>
<div >
<form id="form1" name="lineform" >
<input id="commandline" type="text" name="command_line" placeholder="Command line" onclick="showVal()" >
</form>
</div>
</div>
</body>
</html>
this is the css:
h1{
color: black;
text-align: left;
}
p{
color: black;
text-align: left;
font-size: 20px;
}
#container1{
width:1300px ;
}
#form1{
width:1300px ;
}
#console{
border:5px solid dodgerblue;
background-color: white;
height: 650px ;
padding-left: 5px;
margin-bottom: 5px;
position: relative;
width: inherit;
}
#commandline{
width: inherit;
border: 5px solid dodgerblue;
height: 30px;
padding-left: 5px;
font-size: 18px;
position: absolute;
}
this is how the command line and the window looks like:

1.- For this case i think you should be using getElementById instead of getElementsByName.
2.- I'd recommend not using a form, but instead have the input in the div's "root".
3.- A text input doesnt have a onclick (or at least it doesn't do what you want it to do)
4.- Add a button type input that executes the code through onclick="blabla();"
5.- i'd recommend putting your script at the end of the page since it works with the DOM and you're not using JQuery.
6.- add an id to the <p> element inside of the console <div>
<body>
<h1>Menu</h1>
<div id="container1">
<div id="console">
<p id="console_content">
</p>
</div>
<div>
<input id="commandline" type="text" name="command_line" placeholder="Command line">
<input id="commandButton" type="button" name="command_button" value="confirm" onclick="showVal();">
</div>
</div>
</body>
7.- new script:
<script>
function showVal() {
var tmp = document.getElementById("commandline").value;
document.getElementById('console_content').innerHTML += (tmp + "<br/>");
}
</script>
Here's a JFiddle so you can see it works:
https://jsfiddle.net/bLehLrum/

The function you are using returns an HTMLCollection, you need to the following:
Change,
document.getElementsByName('command_line').value = tmp;
To
document.getElementsByName('command_line')[0].value = tmp;
This gets the first element in the array, notice how there is an s at the end of getElements which suggests plural. This should help you in the future.
Reading Material
getElementsByName

Exdending Script47 answer, The problem is you are taking the value from input field and setting the same value again to it, That's why you are seeing any change/affect.

If by the box you mean the console, you should change your function with this
function showVal(){
// get the value of the input
var tmp = document.getElementById('commandline').value;
// add to the innerHTML of the console the tmp value
document.getElementById('console').innerHTML += "<p>"+tmp+"</p>";
}
document.getElementById
Your code try to reassign the value of command_line with the same value.
document.lineform.command_line.value could be the same as document.getElementsByName('command_line')[0]

Related

JavaScript document.createElement not showing any results [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I am trying to help a friend with making his website school project, but I ran into a problem. It was meant to have 3 text boxes with a button that can add more text boxes, I tried with document.write but it overwrites the whole page so I looked it up and I found out about document.createElement, which doesn't seem to work as well.
I don't know if anything in my code is incorrect.
<!DOCTYPE html>
<html>
<head>
<style>
.input {
margin-top: 50px;
}
.input .submit {
float: left;
}
.add {
margin-left: 100px;
margin-top: 50px;
width: 50px;
height: 50px;
font-size: 30px;
}
.gen {
float: right;
margin-right: 100px;
width: 400px;
height: 50px;
font-size: 25px;
}
.output {
position: fixed;
margin-top: 100px;
float: right;
margin-left: 400px;
}
</style>
<script language="javascript" type="text/javascript">
var input = document.createElement("<p>Hello</p>");
var container = document.getElementsByClassName("buttons");
container.appendChild(input);
</script>
</head>
<body>
<form class="buttons">
<input type="text" class="input">
<input type="submit" class="submit">
<br>
<input type="text" class="input">
<input type="submit" class="submit">
<input type="button" class="gen" value="Click to generate a random word">
<input type="text" class="output">
<br>
<input type="text" class="input">
<input type="submit" class="submit">
<br>
</form>
<input type="button" class="add" value="+" >
</body>
</html>
You're passing incorrect parameters to document.createElement - Documentation for this method can be found here: document.createElement
document.createElement accepts a tag name, but the other properties you have to add on through object manipulation.
var p = document.createElement("p");
p.textContent = "Hello";
document.body.appendChild(p);
Secondly you are using var container = document.getElementsByClassName("buttons") which is incorrect as well. You're trying to get the container element but asking for it to get a list of elements with the class name of "buttons". This returns an array and requires you to select the first option that's returned e.g. container[0].appendChild
In truth you should be using an ID instead of a class name. ID's are meant to be unique so that singular elements can be easily found within a document, class names are meant to be used to alter multiple elements. Given your situation though, you should alter your initial query so that it just returns the singular element using document.querySelector(".buttons")
var container = document.querySelector(".buttons");
All Together:
var p = document.createElement("p");
p.textContent = "Hello";
var container = document.querySelector(".buttons");
container.appendChild(p);
<form class="buttons">
</form>
A word of advice: judging from the code you've presented here you may not know the language well enough to assist in teaching it to others. That's not saying you don't have the aptitude or the ability, but it appears you need to spend more time studying the material before getting to that point.
You have a couple of issues, the first is that when your script runs, there are no elements for it to find, so you need to wait for the document to load using something like window.onload = function() { /* ... */ }. The second is the getElementsByClassName returns a HTMLCollection (essentially an array of nodes). You have to get the one that you want, or else the method appendChild won't exist (since the HTMLCollection has no such method). Also, createElement takes the name of the element, in this case p, and then you can use setInnerHTML to set the contents.
Your code should look something like:
window.onload = function() {
var input = document.createElement("p");
input.innerHTML = 'Hello';
var container = document.getElementsByClassName("buttons");
container[0].appendChild(input);
};

UI problems - How do I trigger an image loading on choice made by dropdown box? Then add text to overlay the image result?

I'm new to coding, I've learned the very basics of html/css/js/java, at least I thought I had, until I went to make a simple game.
I made a simple choose your own adventure game that worked, as each choice just went to a new page.
Then, I thought I'd make it a bit more complex, so I want to have the user enter their name, and store that to show next to the player's stats.
I've got a dropdown box with 4 choices for characters.I want to have Strength/Mana/Lives stats and have the player's choice of character to be able to adjust these stats accordingly before the game starts i.e. Male Warrior would have 2 extra Strength, Female Mage 2 extra mana etc.
Then, I'd like an image based on their character choice displayed next to their stats, so that the game can begin.
So far, I've been pulling my hair out in great clumps and have tried many different methods but so far, I've only got to the stage where I place the page with user input into an iframe. I can get to reflect their choices with text, but I can't get an image to load on submit. Ideally I'd like a permanent box in the top corner of the iframe, and have the statistics variables passed into the stats shown alongside the character's image.
I'd really really appreciate any help here, especially if it can be solved using HTML/CSS/JS as I'm not too familiar with JQuery, and would like to keep it as simple as possible really.
I've gone through as many q's and a's as I can to find relevant help, but I'm mainly finding answers for PHP or other languages.
I must apologise in advance for my waffling above, and sloppy coding. (I seriously thought this would be easy heh).
I'm unsure if my code so far will help, but I'll just paste it below anyway.
HTML for the UI page is:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Character Selection</title>
<link rel="stylesheet" href="css/style2.css">
<style>
img {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<div>
<div id='gamestitle'>
<p>
<img src = "GAMETITLE.jpg"
alt = "Steve's Perilous Capers"/>
</p>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLable' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p></div>
</div>
<div>
</div>
<div>
<form>
Select your Hero please:
<select id="mySelect">
<option>Male Warrior</option>
<option>Male Mage</option>
<option>Female Warrior</option>
<option>Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<script src="js/index.js"></script>
<script>
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
</script>
<p id="demo"></p>
</body>
</html>
The CSS is:
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide { display: none;}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
The JS file: (I've tried using icons and background image but I couldn't get them to show)
// the function which handles the input field logic
function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');
if (nameField.length < 3) {
result.textContent = 'Username must contain at least 3 characters';
//alert('Username must contain at least 3 characters');
} else {
result.textContent = 'Your Hero is: ' + nameField;
//alert(nameField);
}
}
function getOption() {
var obj = document.getElementById("mySelect");
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
}
function swapImage(){
var image = document.getElementById("imageToSwap");
var dropd = document.getElementById("dd");
image.src = dropd.value;
};
// use an eventlistener for the click event
var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false);
var subButtonTwo = document.getElementById('subButtonTwo');
subButtonTwo.addEventListener('click', getOption, false);
$(function () {
$.widget("custom.iconselectmenu", $.ui.selectmenu, {
_renderItem: function (ul, item) {
var li = $("<li>"),
wrapper = $("<div>", {text: item.label});
if (item.disabled) {
li.addClass("ui-state-disabled");
}
$("<span>", {
style: item.element.attr("option-style"),
"class": "ui-icon " + item.element.attr("data-class")
})
.appendTo(wrapper);
return li.append(wrapper).appendTo(ul);
}
});
$("#mySelect")
.iconselectmenu()
.iconselectmenu("menuWidget")
.addClass("ui-menu-icons avatar");
});
/*
function getcurrentChoice() {
var characterSelection = ['MaleWarrior'], ['MaleMage'], ['FemaleWarrior'], ['FemaleMage'];
var currentChoice = document.getElementById('currentChoice').value;
var resultChoice = document.getElementById('resultChoice');
var subButtons = document.getElementById('subButtons');
subButtons.addEventListener('click', getcurrentChoice, false);
}
*/
Sorry for the messy coding, it's not helped that I've tried so many workarounds for each problem I've encountered that I've lost track of what is and isn't working.
I'm pretty sure this is out of control by now, and a waste of your time, but I'm so confused. I'm sure i'm over complicating the matter.
Thanks in advance again,
Steve.
Check this:
https://jsfiddle.net/digitalrevenge/q9z1x6vv/
I've added an img src and made some changes to your JS.
I'm not sure if it does exactly what you want but there's no harm in giving it a try ;)
I am not sure how to do this in Javascript, but I have achieved it with jQuery, maybe you can adapt it to Javascript if you like.
Basically...
Give each option a value
On selection, or change, empty div#change_this, and check for the value
If value = # then add html code to div#change_this
You can change the image/add in the stats, I just used some filler.
You will also need to add css and all that, if you have any specific questions about that, please let me know.
Functionality is there though.
Best,
Levi
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide {
display: none;
}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
<div>
<div id='gamestitle'>
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLabel' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p>
</div>
</div>
<div>
<form>
Select your Hero please:
<select name="hero_type" id="mySelect">
<option value="0">Male Warrior</option>
<option value="1">Male Mage</option>
<option value="2">Female Warrior</option>
<option value="3">Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<div id="change_this">
<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('select[name="hero_type"]').click(function() {
$('#change_this').empty();
if ($('select[name="hero_type"]').val() == "0"){
$('#change_this').append('<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "1"){
$('#change_this').append('<p>Yayyy, Male Mage.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "2"){
$('#change_this').append('<p>Yayyy, Female Warrior</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "3"){
$('#change_this').append('<p>Yayyy, Female Mage</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
})
});
</script>
The src attribute of an image tag points to the location of the image file to use.
You should be somewhat aware of this as your code contains:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
To change the image, simply change the src attribute to point to the location of the new image.
The source of an image tag can be accessed and changed via:
document.getElementById("imageId").src="fileToUse";
This means you need to add an id to your image tag as so:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers" id="imageId"/>
In your case, you want to get the image src from a select field. This means you need to tie the image file locations to your select form as values.
<select id="mySelect">
<option value="location-of-this-image.png">Male Warrior</option>
<option value="location-of-this-image.png">Male Mage</option>
<option value="location-of-this-image.png">Female Warrior</option>
<option value="location-of-this-image.png">Female Mage</option>
</select>
To use these values and assign them to the image src:
document.getElementById("imageId").src=document.getElementById("mySelect").value;
If you correctly id your image and select form, give the select form proper values, and put the above line of code in the function you call when choosing and image, your image should change.
Important Note
JQuery is a JavaScript library and isn't part of the base language. To use JQuery, you must import it in your html code. You seem to be using JQuery functions, but I don't see where you imported JQuery. This may be causing you problems/breaking your code.
If you do have JQuery imported, the above code can be rewritten using JQuery rather than vanilla JavaScript and it'll look a lot cleaner.

Add text to a textarea with JavaScript

Again I got a problem with JavaScript, but this time is something more complex.
I'm trying to make a little JavaScript text editor. Basically it's an experiment, a test and the thing should be easy. I have a <h1> HTML element, and a <p> HTML element, and both of them change, as the user writes on a <input type="text" /> element and a <textarea></textarea>.
Now, everything work fine, but there is a problem. For making a space between lines, the user can't just press Enter, but of course need to use the <br /> HTML tag.
So my idea was to make a little button that allows the user to add this tag by pressing that button.
And JavaScript just makes a variable of the actual text, save it and add at the end of it the <br />. The result should be the text written by the user plus the break HTML tag.
And this works, if the textarea is empty and if you have never written something on it. It works and work even 10 or 20 times, but if you write something on it, it just stop working, even if you delete all the text. What is the problem in the code below?
<html>
<head>
<title>Text editor</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Slab" rel="stylesheet">
<style>
.title {
font-family: roboto;
text-align: center;
}
.text {
font-family: roboto slab;
text-align: justify;
margin-bottom: 40px;
}
.container {
width: 80%;
}
.textarea {
width: 100%;
height: 30em;
text-indent: 0.5em;
}
.title_box {
margin: 10px;
width: 20em;
padding: 10px;
font-size: 1em;
}
</style>
</head>
<body>
<center>
<div class="container">
<h1 class="title" id="title_space">Title of the page</h1>
<p class="text" id="text_space">Content of the page.</p>
</div>
</center>
<hr />
<center><input type="text" class="title_box" placeholder="Title" id="title_box" /></center>
<textarea class="textarea" id="text_box"></textarea>
<input type="submit" value="Save" onclick="saveText()" />
<input type="submit" value="br" onclick="br()" />
<script>
function saveText(){
var title = document.getElementById("title_box").value;
var text = document.getElementById("text_box").value;
document.getElementById("title_space").innerHTML = title;
document.getElementById("text_space").innerHTML = text;
}
function br(){
var actualtext = document.getElementById("text_box").value;
var processedtext = actualtext + "<br />";
document.getElementById("text_box").innerHTML = processedtext;
}
</script>
</body>
</html>
When you're updating the text area, instead of:
document.getElementById("text_box").innerHTML = processedtext;
Use:
document.getElementById("text_box").value = processedtext;
Try to add this to your JavaScript code just before changing the text
text = text.replace(/\r?\n/g, '<br>');
Line breaks are \r\n or \n while HTML line break is <br> and that is the problem.
This in case I understood your question correctly.
Here is the code running

Change href when anchor is clicked

I have a question about how I can dynamically change a href="" in a button.
The jsfiddle below shows a button fixed at the bottom of the viewport starting at the landing page:
http://jsfiddle.net/Hm6mA/3/
The html of the button is like so:
<div class="button">
<a href="#first" class="" style="width: 80px; height: 80px; opacity: 1;">
<img src="img/down.png" alt="down">
</a>
</div>
When it is clicked I want it to scroll to the next section and change the href="" to the following section of the page. So, when it is first clicked, the href will change to #second. It would obviously also need to change when the user manually scrolls past a section.
This is for a single page website. How would I go about such a thing?
Use .prop() to change its value
$(".button").on('click', function(){
$('.button').find('a').prop('href', '#services');
});
Demo
You can use fullPage.js plugin to achieve what you want. Maybe it is faster than coding it from cero :)
Demo fullPaje.js
Page
I am not used to jquery. Here is a pure javascript solution. It surely changes the hash value.
<body>
<div id="sections">
<section id="s100">asdfasd</section>
<section id="s101"></section>
<section id="s102"></section>
<section id="s103"></section>
<section id="s104">asdfasdasdfsdf</section>
<section id="s105"></section>
</div>
<div class="nav-bar">
<a id="next-button" class="button" href="#s100">Next</a>
</div>
<script type="text/javascript">
var sections = document.getElementById("sections");
var nextButton = document.getElementById('next-button');
sections.onscroll = function (evt) {
}
var counter = 100;
var limit = 105;
// closure
nextButton.onmouseup = function (evt) {
var incCounter = function () {
// add your custom conditions here
if(counter <= limit)
return counter++;
return 0;
};
var c = incCounter();
if(c != 0)
this.setAttribute('href', "#s" + c);
}
</script>
</body>
CSS
html, body {
height: 100%;
width: 100%;
overflow: hidden;
}
#sections {
height: 50%;
width: 100%;
overflow: scroll;
}
.nav-bar {
margin: 30px 20px;
}
.button {
text-decoration: none;
border: 1px solid #999;
padding: 10px;
font-size: 120%;
}
I have written a small jQuery plugin for that, just pushed it to GitHub. https://github.com/ferdinandtorggler/scrollstack
What you basically want to do is calling
$('.button').scrollstack({stack: ['#first', '#second', ... ]});
You dont even need the link when you call it on the button. So check it out and let me know if it works for you. ;)
Here you can try it and read more: http://ferdinandtorggler.github.io/scrollstack/

Why doesn't this Javascript function work?

i would like to be able to click a link and have a form show up. ideally with smoothly maybe use delay? so far i click on the link and nothing happens.
My Javascript
<script type="text/javascript">
function showForm() {
document.getElementById('showme').style.display = "block";
}
</script>
my HTML
<a class="non_link" href="" alt="start a new post" onmouseclick="showForm();">
Start A New Post
</a>
<form action="#" id="showme" method="post">
my CSS
#showme {
font-size: 0.5em;
color: #000;
font-weight: normal;
margin-top: 20px;
display: none;
}
took out the # sign and still doesn't work
# is not part of the id:
document.getElementById('showme')
Additionally, that should probably be onclick you're using. Plus, try setting the href to something like href="javascript:void(0);" (other expressions that return a falsy value should work too afaik).
Don't use a # sign in getElementById
document.getElementById('showme').style.display = "block";
You want the id, not the selector. See here.
document.getElementById() doesn't need the # .That's a jquery standard kept in line with how you define css ids
See MDN:
https://developer.mozilla.org/en/DOM/document.getElementById
Your code is working in below test HTML file:
<html>
<head>
<style type="text/css">
#showme {
font-size: 0.5em;
color: #000;
font-weight: normal;
margin-top: 20px;
display: none;
}
</style>
<script type="text/javascript">
function showForm() {
document.getElementById('showme').style.display='block';
}
</script>
</head>
<body>
<a class="non_link" href="#" alt="start a new post" onclick="showForm()">
Start A New Post
</a>
<form id="showme" method="">
Content of the Form<br/>
Content of the Form
</form>
</body>
</html>

Categories