I am a beginner in JavaScript. Currently I am learning about buttons, alerts and writing documents. For a fun little side project, I want to press a button and then it writes to a document. That works great, but I have other buttons to press but I do not know how to "go back" to the other page and push those other buttons. How can I maybe make a button to "go back" or user a timer? Which would be easier? Once I am on that other page, I don't want to stay there.
Example:
function myTest1() {
document.write("JavaScript")
}
<input type="button" onClick="myTest1()" value="What language is this?">
By keeping the buttons in a container and the displayed "page" in another:
function myTest1() {
// document.getElementBy('content') id to get the content element
// set innerHTML to change the content
document.getElementById('content').innerHTML = "JavaScript";
}
function goBack() {
// document.getElementBy('content') id to get the content element
// set innerHTML to change the content
document.getElementById('content').innerHTML = "Click a button to change this content";
}
<div id="button-container">
<input id="which-language-btn" type="button" onclick="myTest1()" value="What language is this?">
<input id="bo-back-btn" type="button" onclick="goBack()" value="Go back" />
</div>
<div id="content" style="border: 1px solid;">
Click a button to change this content
</div>
Or by changing both buttons and content:
function myTest1() {
// document.getElementBy('content') id to get the container element
// set innerHTML to change the content
document.getElementById('button-container').innerHTML = "JavaScript<input type=\"button\" onclick=\"goBack()\" value=\"Go back\" />";
}
function goBack() {
// document.getElementBy('button-container') id to get the container element
// set innerHTML to change the content
document.getElementById('button-container').innerHTML = "Click a button to change this content<input id=\"which-language-btn\" type=\"button\" onclick=\"myTest1()\" value=\"What language is this?\">";
}
<div id="button-container">
Click a button to change this content<input id="which-language-btn" type="button" onclick="myTest1()" value="What language is this?">
</div>
The idea is using innerHTML instead of document.write too avoid replacing all your document (including your script)
document.write clears the document when it's called:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
You could just keep appending the output to the body, but it's much better in the long run to adjust the content of a separate div, used for output, rather than just keep adjusting the body.
function myTest1() {
document.getElementById('output').textContent += "JavaScript\n"
}
#output {
width: 100%;
min-height: 20px;
background-color: rgb(20, 20, 30);
color: white;
margin-top: 20px;
font-family: "Lucida Console";
padding: 5px;
}
<input type="button" onClick="myTest1()" value="What language is this?">
<div id="output">
</div>
Related
I have three buttons in HTML, orders and products and supplier. I want when the user clicks orders order is being shown, when the user clicks products, the product is shown, and the name of the supplier when it is clicked.
function changedata(parameter){
if(parameter==0){
document.getElementById('myorders').style.fontSize="25px";
}
else if(parameter==1){
document.getElementById('myproducts').style.fontSize="25px";
}
else{
document.getElementById('mysupplier').style.fontSize="25px";
}
}
<button class="button" onclick="changedata(0)">ORDERS</button>
<button class="button" onclick="changedata(1)">PRODUCTS</button>
<button class="button" onclick="changedata(2)">SUPPLIER</button>
<div id="myorders">
<p>Laptop, Earphone</p>
</div>
<div id="myproducts">
<p>Earphone, smart watch</p>
</div>
<div id="mysupplier">
<p>Amazon, E-kart</p>
</div>
But it won't hide data and serve my need, I'm a beginner in web development, looking for kind help to show data only when the corresponding button is pressed.
Try giving each element a default value of display:none in your css, as such -
#myorders,
#mysuppliers,
#myproducts {
font-size: 25px;
display: none;
}
This will select each element and hide them right away.
Then, when a button is pressed, you can use
document.getElementById('___').style.display = 'block';
to then show that element.
Here is the final product:
function changedata(parameter){
if(parameter==0){
document.getElementById('myorders').style.display = 'block';
}
else if(parameter==1){
document.getElementById('myproducts').style.display = 'block';
}
else{
document.getElementById('mysupplier').style.display = 'block';
}
}
#myorders,
#myproducts,
#mysupplier{
font-size: 25px;
display: none;
}
<button class="button" onclick="changedata(0)">ORDERS</button>
<button class="button" onclick="changedata(1)">PRODUCTS</button>
<button class="button" onclick="changedata(2)">SUPPLIER</button>
<div id="myorders">
<p>Laptop, Earphone</p>
</div>
<div id="myproducts">
<p>Earphone, smart watch</p>
</div>
<div id="mysupplier">
<p>Amazon, E-kart</p>
</div>
If you would like to have the element toggle between hidden and shown on each button press, I recommend toggling a class with javascript, as such:
function changedata(parameter){
if(parameter==0){
document.getElementById('myorders').classList.toggle('active');
}
else if(parameter==1){
document.getElementById('myproducts').classList.toggle('active');
}
else{
document.getElementById('mysupplier').classList.toggle('active');
}
}
#myorders,
#myproducts,
#mysupplier{
font-size: 25px;
display: none;
}
#myorders.active,
#myproducts.active,
#mysupplier.active{
display: block;
}
<button class="button" onclick="changedata(0)">ORDERS</button>
<button class="button" onclick="changedata(1)">PRODUCTS</button>
<button class="button" onclick="changedata(2)">SUPPLIER</button>
<div id="myorders">
<p>Laptop, Earphone</p>
</div>
<div id="myproducts">
<p>Earphone, smart watch</p>
</div>
<div id="mysupplier">
<p>Amazon, E-kart</p>
</div>
There are slightly easier ways to connect each div to its corresponding button, and one of them is to use data attributes. We can add a data attribute to each button the text of which matches the id of its corresponding div.
(I'm assuming that when you click on one button all the other divs are hidden, and only its div shows.)
This example uses more modern JS techniques but I'll guide you through them, comment everything, and provide documentation at the end. You don't have to understand everything here but you're probably going to bump up against these things eventually, so you might as well take a look at them now.
Here's a rundown of how this all works:
Remove the inline listeners from the buttons. Modern JS uses addEventListener.
Wrap the buttons in a container. What we're going to use is a technique called event delegation. Instead of attaching listeners to every button we attach one to the container and this captures any events that "bubble up" the DOM from its child elements. We can then call a function when a child element is clicked.
The function does a few things. First it checks to see if the clicked element was actually a button. Then it hides all the "panels" by removing a class called "show" from them ("show" sets the element's display to block - initially all panels have their display set to none). Then based on the id from the button's data attribute it forms a selector with it, and we use that to target its corresponding div and apply the "show" class.
// Cache out buttons container, and all of the panels
const buttons = document.querySelector('.buttons');
const panels = document.querySelectorAll('.panel');
// Add an event listener to the buttons container
buttons.addEventListener('click', handleClick);
// When a child element of `buttons` is clicked
function handleClick(e) {
// Check to see if its a button
if (e.target.matches('button')) {
// For every element in the `panels` node list use `classList`
// to remove the show class
panels.forEach(panel => panel.classList.remove('show'));
// "Destructure" the `id` from the button's data set
const { id } = e.target.dataset;
// Create a selector that will match the corresponding
// panel with that id. We're using a template string to
// help form the selector. Basically it says find me an element
// with a "panel" class which also has an id that matches the id of
// the button's data attribute which we just retrieved.
const selector = `.panel[id="${id}"]`;
// Select the `div` and, using classList, again add the
// show class
document.querySelector(selector).classList.add('show');
}
}
.panel { display: none; }
.show { display: block; }
.button { text-transform: uppercase; }
.button:hover { cursor: pointer; background-color: #fffff0; }
<div class="buttons">
<button data-id="myorders" class="button">Orders</button>
<button data-id="myproducts" class="button">Products</button>
<button data-id="mysupplier" class="button">Supplier</button>
</div>
<div class="panel" id="myorders"><p>Laptop, Earphone</p></div>
<div class="panel" id="myproducts"><p>Earphone, smart watch</p></div>
<div class="panel" id="mysupplier"><p>Amazon, E-kart</p></div>
Additional documentation
addEventListener
classList
Destructuring assignment
forEach
matches
querySelector
querySelectorAll
Template string
I'm trying to write pure javascript function to replace the text "Passed" to "Completed". The HTML inside the div#prompt should remain in tact and is variable. Here is the HTML -
<div id="prompt">
Passed
Take a survey
<button type="button" data-behavior="hide.prompt"></button>
</div>
I tried replacing text but that doesn't seem to be working
var text = document.getElementById('prompt').textContent;
text.replace("Passed", "Completed");
Also tried this -
var text = document.getElementById('prompt').innerHTML;
text.replace("Passed", "Completed");
What am I doing wrong? Appreciate the help!
replace does not mutate the string, it returns a new one. Strings are immutable.
var text = document.getElementById('prompt');
text.textContent = text.textContent.replace("Passed", "Completed");
Actually your element contains a text node that you can override:
document.getElementById('prompt').childNodes[0].textContent = "Completed";
Instead of replacing text, how about toggle a class on the outer div.
With that you can also customize its HTML as well.
Stack snippet
.prompt::before {
content: 'Passed';
}
.prompt.hidden::before {
content: 'Completed';
}
.prompt.hidden button {
display: none;
}
/* demo styles */
.prompt button { padding: 5px 20px; }
hr { margin: 20px 0; }
<div class="prompt">
Take a survey
<button type="button" data-behavior="hide.prompt"></button>
</div>
<hr>
<div class="prompt hidden">
Take a survey
<button type="button" data-behavior="hide.prompt"></button>
</div>
I am trying to make a simple text editing box so that I can eventually post text to another section of a website. I'm attempting to make buttons to make text bold, italicized, add a code box etc, (hence insertAdjacentHTML not insertAdjacentText) but I decided to just start making sure I could get plain text to print to a textarea.
I have achieved this easily but now my question becomes how do I make it so that the button still affects the text area after a user has added text to it? the code below will happily type out "hello"'s up until you click on the textarea, and from that point on it refuses to and I can't figure out why.
window.hello = function(textarea) {
var obj = document.getElementById("text");
obj.insertAdjacentHTML('beforeend', 'hello');
}
<body>
<button onclick="hello()">hello</button>
<form>
<p></p>
<textarea id="text"></textarea>
</form>
</body>
As you can read from MDN a textarea can contain only Character data.
This is the reason because you cannot use insertAdjacentHTML and instead you can use the value.
If you need to add text in bold or ... you can use a contenteditable div element.
The snippet:
window.helloDiv = function() {
var obj = document.getElementById("textDiv");
obj.insertAdjacentHTML('beforeend', 'hello');
};
window.helloTxtArea = function() {
var obj = document.getElementById("textTxtArea");
obj.value += 'hello';
}
div {
width: 300px;
height: 100px;
border: 1px;
border-style: solid;
}
textarea {
width: 300px;
height: 100px;
margin-top: 10px;
}
<button onclick="helloDiv()">helloDiv</button>
<button onclick="helloTxtArea()">helloTextArea</button>
<form>
<p></p>
<div id="textDiv" contenteditable="true"></div>
<textarea id="textTxtArea" contenteditable="true"></textarea>
</form>
I have a form and need to append a field as many times as required. If the button CLICK TO ADD ANOTHER FIELD is clicked the div should be appended. After the first append (onload), the div responses correctly but from the second one on, I am not getting the similar response from the div. Here is my JSFiddle
If I click on the TEST BUTTON , I get alert for the first div but on adding another div (by clicking the CLICK TO ADD ANOTHER FIELD button) , the button (TEST) doesn't work anymore for the second div onwards.
I tried clone() to help this but unable solve this one. May be I am not using it correctly.
To replicate the issue please follow the steps::
Click on the CLICK TO ADD ANOTHER FIELD button to add div
Click on the TEST button on the second div onwards
Please take a look and suggest. Thanks in advance.
You have to use delegation like $(document).on('click','.test',function(){
var count = 1;
$.fn.addclients = function(add){
var mydiv = '';
mydiv = '<div class="dataadd"><fieldset><legend>Test: '+add+'</legend><b>Test Name :</b> <input type="text" id="ct'+add+'" name="cname" value="" style="width:250px" />'+
' <button class="test" id="test" style="float:left;">TEST</button>'+
'<br>'+
'</fieldset></div>';
//$(".dataadd").clone().appendTo('#registerForm');
$('#registerForm').append(mydiv);
}
$.fn.addclients(count);
$(document).on('click','#btn',function(){
++count;
$.fn.addclients(count);
return false;
});
$(document).on('click','.test',function(){
alert("test");
return false;
});
.zend_form{
font-weight:bold;
font-size:10px;
width:358px;
float: left;
}
.dataadd{
font-weight:bold;
font-size:10px;
width:358px;
//border: 1px solid;
margin-top: 15px;
margin-bottom: 15px;
//padding: 5px;
//float:left;
}
.selectbox{
margin-top: 15px;
width:155px;
height:100px;
}
.buttonc{
background-color: #fff;
width:145px;
height:45px;
}
.selection_area{
font-weight:bold;
font-size:10px;
}
input {
width: 200px;
}
dt {
width:50%; /* adjust the width; make sure the total of both is 100% */
}
dd {
width:80%; /* adjust the width; make sure the total of both is 100% */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="registerForm" enctype="application/x-www-form-urlencoded" method="post" action=""><dl class="zend_form">
<dt id="firstname-label"><label for="firstname" class="required">First Name:</label></dt>
<dd id="firstname-element">
<input type="text" name="firstname" id="firstname" value="" style="width:200px; float:left;" /></dd>
<dt id="middlename-label"><label for="middlename" class="optional">Last Name</label></dt>
<dd id="middlename-element">
<input type="text" name="middlename" id="middlename" value="" style="width:200px" /></dd>
</form>
<div style='display:table;background-color:#ccc;width:99%;padding:5px;'>
<button class='buttonc' name='btn_sub' id='btn' style='float:left;'>CLICK TO ADD ANOTHER FIELD</button>
</div>
You write:
$('#btn').click(function(){ ... });
but this will only bind the event handler to elements currently on the page when running this code. So elements added later will not be covered by this code.
But first tip: do not use a HTML ID (#btn) if you want to repeat it. So instead use a class (.btn), to capture all elements.
And then the best way is to write something like:
$(document).on('click', '.btn', function() { ... } )
This will capture any click event on the document (you could use a container div instead --just easier to show now), and only run the callback if it matches the given selector (.btn).
all elements created after body load must use delegation to work
$("body").on("click",".test",function(){
alert("test");
return false;
});
This way, the event is attached to the body, witch always exists, but only triggers when the matched elements appear, no matter when they're created (before or after js is loaded)
Full disclosure, this is an assignment from an advanced JS class I'm taking. I've been trying to figure this out for a couple of weekends and it's driving me crazy! I'm far more familiar with jQuery than I am straight JS (which is one of the reasons I'm taking this class).
The webpage is supposed to take input from the user to create a <UL> list of links with some other strings associated that are related to the link. That part works just fine, what I can't figure out is why as soon as I'm done clicking on the Add Link button, the new link shows very briefly, then disappears! If I click the button very quickly, I can get several of them to show up, but as soon as I stop, all of them disappear.
I tried making a fiddle out of this, but clicking on the Add Link button gave me a POST error (which may be a clue to it's behavior?). If you cut & paste the code into an HTML file & run it, you'll see the behavior I'm describing.
I thought it had something to do with the init() function, so I tried running that at the bottom of the <body>, but that didn't make any difference. I also tried running it without an init, but couldn't figure out how to get the onclick listener initialized, even if it ran at the bottom of the <body>. I notice that even though I'm defining the favesList in global scope, it's still showing up as undefined after it should have been initialized with values (at least from my point of view). However, it looks like it's going out of scope instead which doesn't make sense to me. Console.log isn't providing me the reason why it's disappearing, or I haven't figured out a way to log the event.
I'm reasonably certain I'm missing a fundamental thing (like it's going out of scope for some reason?), so if someone could point out what that thing is I'd be grateful (I also don't need a definitive answer, just a nudge in the right direction, this is basically homework and I know I'm supposed to be figuring this out on my own, but I think a couple of Sundays of my time is giving it the college try).
Here's the code:
<!doctype html>
<html>
<head>
<title>Advanced JavaScript Project: Favorites and Tags</title>
<meta charset="utf-8">
<style>
body {
font-family: Helvetica, Ariel, sans-serif;
}
form {
display: table;
border-spacing: 5px;
width: 40%;
}
form p {
display: table-row;
}
form label {
display: table-cell;
text-align: right;
}
form input {
display: table-cell;
width: 95%;
}
span.comment {
font-size: 80%;
color: #777777;
}
span.tags {
font-size: 80%;
color: rgb(48, 99, 170);
}
#submit {
width: 20%;
}
</style>
<script>
window.onload = init;
var favesList;
console.log(favesList);
function init() {
//get submit button handle
var submit = document.getElementById("submit");
//add click handler to button to call method to add text to the list
submit.onclick = AddFavorite;
console.log("back in init");
}
function favorite(url, title, comment, tags){
console.log(this);
this.url = url;
this.title = title;
this.comment = comment;
this.tags = tags;
console.log(this);
}
function AddFavorite(){
var f = new favorite(
document.getElementById("url").value,
document.getElementById("title").value,
document.getElementById("comment").value,
document.getElementById("tags").value);
console.log(f);
favesList = document.getElementById("list");
console.log(favesList);
var node = document.createElement("LI");
var a = document.createElement('a');
a.appendChild(document.createTextNode(f.title));
a.href = f.url;
console.log(a);
node.appendChild(a);
node.appendChild(document.createTextNode(f.comment));
node.appendChild(document.createTextNode(f.tags));
console.log(node);
favesList.appendChild(node);
console.log(favesList);
}
</script>
</head>
<body>
<h1>Tag and save your favorites</h1>
<form id="form">
<fieldset>
<legend>Add a new favorite:</legend>
<label for="url">URL:</label>
<span><input id="url" type="url" placeholder="http://www.cnn.com" value="http://www.cnn.com"></span><br>
<label for="title">Title:</label>
<input id="title" type="text" value="CNN World News"><br>
<label for="comment">Comment:</label>
<input id="comment" type="textarea" value="Thoughts?"><br>
<label for="tags">Tags:</label>
<input id="tags" type="text" value="Enter keywords separated by commas"><br>
<input id="submit" type="submit" value="Add Link">
</fieldset>
</form>
<br>
<h1>List of favorites</h1>
<ul id="list"></ul>
</body>
</html>
You need to return false; as the last line in your AddFavorite() method, to stop the browser from processing the button and refreshing the page.