So I'm pretty experienced with programming, but I am just getting new to Javascript. I am making a new element when I click a div, but it won't work. I have tried many methods, and this one seems like the simplest. Can you help me figure out what is wrong?
<!doctype html>
<html>
<head>
<link type="text/css" rel='stylesheet' href='style.css'/>
<meta charset="UTF-8">
</head>
<body>
<div class="head">
<h1>Corkboard</h1>
<div id="addNote" onclick="showNewNoteMenu()">+</div>
</div>
<div id = "newNoteMenu">
<div class="container">
<input id="title" type="text" placeholder="Title" name="Title"/> <br />
<textarea id="details" cols=22.5 rows=5></textarea> <br />
<div onclick="createNewNote()" id='submitNewNote'>Make New Note</div>
</div>
</div>
<div class="content" onclick="hideNewNoteMenu()">
</div>
</body>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="script.js"></script>
</html>
function showNewNoteMenu() {
document.getElementById("newNoteMenu").style.display = "inline-block";
};
function hideNewNoteMenu() {
document.getElementById("newNoteMenu").style.display = "none";
};
function createNewNote() {
document.getElementsByTagName("h1").innerHTML = "This works"
alert("OK");
var title = document.getElementById("title").value;
var text = document.getElementById("details").value;
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var time = hours + ":" + minutes;
var content = document.getElementsByClassName("content");
var note = '<div class="note"><div class="container"><h2>'+ title + '</h2><i>' + time + '</i><p>' + text + '</p></div></div>';
}
hideNewNoteMenu();
It appears all that's missing is to insert the string of markup, note, into the document.
In this case, you can use .insertAdjacentHTML():
var content = document.getElementsByClassName("content");
var note = /* ... */;
content[0].insertAdjacentHTML('beforeend', note);
With beforeend, it will insert the note as the content's last child.
Also, the use of [0] is because getElementsByClassName() returns a collection of Elements (note the plural getElements...).
Since you've included jQuery, this could also be accomplished with jQuery(html) and .appendTo():
$(note).appendTo(content[0]);
Change this:
<div id="addNote" onclick="showNewNoteMenu()">+</div>
to
<div id="addNote">+</div>
and
document.getElementById("addNode").addEventListener("click",showNewNoteMenu);
Be sure the JavaScript executes after the page has been loaded and parsed. You should have a window.onload.
Related
I'm building a random quote machine for Free Code Camp. I need to have one button that produces a random quote and another button that post one of the random quotes to twitter. My random quote button seems to be working fine. I've started work on the twitter button but have run into a road block right away. I'm trying to store that value of the "p" element, i.e. the quote, into a variable so I can use it to build the rest of the button. I tried to log the value of the element just to see if it worked but it returns "undefined" whether there is a quote present or not. I've tried to manipulate the document.getElementById().value method a bunch of different way but can't seem to get it to return a string. Any insight into why its only returning undefined would be helpful. Thank You!
This is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Random Quote Machine</title>
<link rel="stylesheet" style="text/css" href="main.css">
</head>
<body>
<div class="main-header">
<h1>Random Quote Machine</h1>
</div>
<div class="main-content" id="main-content">
<p class="text" id="text"></p>
</div>
<button type="submit" class="quote-button" id="quote-button">New Quote</button>
<button type="submit" class="twitter-button" id="twitter-button">Twitter</button>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
This is my Javascript so far
const btn = document.getElementById('quote-button');
const content = document.getElementById('text');
let strValue = document.getElementById('text').value;
const twitter = document.getElementById('twitter-button');
// New Quote Button Event Listener
btn.addEventListener('click', function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en');
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
const quote = data.quoteText + data.quoteAuthor;
getQuote(quote);
};
xhr.send();
});
function getQuote(newQuote) {
content.textContent = newQuote;
}
// Twitter Button Event Listener
twitter.addEventListener('click', function () {
console.log(strValue);
});
In my code, I updated the Quote Text and The Author name using a function and used those variables when I wanted to share the tweet.
Hope that helps!
HTML:
<div class= "container">
<div class="card bg-dark text-white">
<img class="card-img" src="https://static1.squarespace.com/static/5ab008d6697a9880a9f8c364/t/5abc6961aa4a99a0ab790df2/1522693072256/background-for-quotes-5.jpg" alt="Card image">
<div class="card-img-overlay">
<h5 class="card-title">Quote of the day!</h5>
<blockquote class="blockquote mb-0">
<p id ="quote" class="card-text"></p>
<p id ="author" class="card-text"></p>
<button id = "quote_button" type="button" class="btn btn-secondary" >Click me to get a quote</button>
<a id = "tweet_btn" ><button type="button" class="btn btn-secondary">
Tweet the quote </button>
</a>
</div>
</blockquote>
</div>
</div>
</div>
JS :
var jd;
var currentQuote;
var currentAuthor;
var data = {
method: "getQuote",
lang: "en" ,
format:"jsonp",
dataType: "jsonp"
};
var texttotweet;
$("#quote_button").on("click", function(){
// Only change code below this line.
getthequote();
console.log(currentQuote);
});
function getthequote() {
$.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=?", data, function(jd) {
$('#quote').html('<p>'+ jd.quoteText + '</p>');
$('#author').html('<p>-' + jd.quoteAuthor + '</p>');
quotedata(jd.quoteText , jd.quoteAuthor );
});
}
function quotedata(quote, author )
{
currentQuote = quote;
currentAuthor = author;
}
$('#tweet_btn').on("click", function(){
$(this).attr("href", "https://twitter.com/intent/tweet?text=" + "The Quote:" + currentQuote + ". The Author :" + currentAuthor );
console.log("Testing out the code");
});
A p element doesn't have a value attribute. Try innerHTML...
I'm doing a schoolproject, trying to do an list of things you need to buy.
The problem is, i can't write more than one time and add to the list, and i can't figure out why.
(It's nowhere near done.) (i have to diffrent javascript files)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="main.css" type="text/css" rel="stylesheet">
<title>Inköpslista</title>
</head>
<body>
<div id="kol1" class="kol">
<h1>Inköp</h1>
<input type="image" src="img/button.png" alt="Submit" id="storknapp" onclick="klickaKnapp('skriva')"/>
<input type"text" id="skriva" placeholder="Skriv din vara här!"/>
<input type="image" id="knapp" src="pluss.png" alt="Submit"/>
</div>
<div id="kol2">
<ul id="listaavvara"></ul>
</div>
<script src="menudropdown.js" type="text/javascript"></script>
<script type="text/javascript" src="java.js"></script>
</body>
</html>
function laggtill(cool, namnVara) {
var vara = document.createElement("li");
vara.innerText = namnVara;
cool.appendChild(vara);
}
var button = document.getElementById("knapp");
button.onclick = function() {
var skriva = document.getElementById("skriva")
var namnVara = skriva.value;
if(!namnVara|| namnVara =="" || namnVara == " " ){
return false;
}
laggtill(document.getElementById("listaavvara"), namnVara);
};
javascrpit 2:
function klickaKnapp(x){
var skrivrutan = document.getElementById(x), maxH="100px";
if(skrivrutan.style.height == maxH){
skrivrutan.style.height = "0px";
} else {
skrivrutan.style.height = maxH;
}
}
HOPEFULLY YOU KNOW WHAT I MEAN! (my pictures are not here)
Because
var button = document.getElementById("knapp");
button.onclick = function() { ... }
overrides the inline event handler. You need to attach events with addEventListener
button.addEventListener("click", function(){...}, false);
Your example works for me on fiddle: http://jsfiddle.net/7zjb86ab/
So this looks like there is something wrong with your imported scripts
<script src="menudropdown.js" type="text/javascript"></script>
<script type="text/javascript" src="java.js"></script>
Are those the two files with your javascript snippets inside?
You could also try to replace
var button = document.getElementById("knapp");
button.onclick = function() {
with
function addItem() {
and then add the function as onclick attribute like you do with the klickaKnapp function
<input type="image" id="knapp" src="pluss.png" alt="Submit" onclick="addItem()" />
I have a JavaScript function that uses document.write() to write to the page. My issue is that when I click the button to call the function, document.write() replaces what I already had with what I am writing. Is there a way to write text to a specific div from JavaScript?
Here is my HTML code:
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="javascript.js">
</script>
<script>
// Calling the Google Maps API
</script>
<script>
<!-- JavaScript to load Google Maps -->
</script>
</head>
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>this -->
<div id="bottom_pane_options">
<button onclick="todaydate();">Try It</button>
</div>
</div>
</body>
...and my JavaScript code (something I got from the internet just to test):
function todaydate() {
var today_date = new Date();
var myyear = today_date.getYear();
var mymonth = today_date.getMonth() + 1;
var mytoday = today_date.getDate();
document.write("<h1>" + myyear + "/" + mymonth + "/"+mytoday + "/h1">);
}
I would like the text to be right below the button. Any help would be appreciated.
Thanks,
Josh
You should avoid document.write. You'd better put your results to another div:
<div id="bottom_pane_options">
<button onclick="todaydate();">Try It</button>
<div id="results"></div> <!-- Added div ! -->
</div>
Then
function todaydate() {
var today_date=new Date();
var myyear=today_date.getYear();
var mymonth=today_date.getMonth() + 1;
var mytoday=today_date.getDate();
document.getElementById('results').innerHTML ="<h1>" + myyear + "/" + mymonth + "/" + mytoday + "</h1>";
}
As you can see, we're writing the results to the results div with .innerHTML.
Hope this helps. Cheers
HTML Code:
<div id="someclass"></div>
JS:
document.getElementById("someclass").innerHTML="<h1>some thing you want</h1>";
To write into a div do the following:
Step-1: Give div an id or classname
<div id="txt"></div>
Step-2. Use .innerHTML in the function:
document.getElementById('txt').innerHTML="HELLO";
You can simply try this...
<!doctype html>
<html>
<head>
<script type="text/javascript" >
function load() {
var div = document.getElementById('data');
div.innerHTML = div.innerHTML + "Write your New Data" + "<br>";
}
</script>
<body onload="load()">
<div id= "data">
Hello... I am old
</div>
</body>
</html>
I am calling this on onload() function you can call as per your beed
You need to tell Javascript to perform the action onload... Try with this:
<script type ="text/javascript">
window.onload = function sayHi(){
document.getElementById('hi').innerHTML = 'Hi';
};
</script>
then on your HTML:
<span id="hi"></span>
I have created a html webpage here:
http://diagrams.inse1d.info/wbt.html
Code:
<!DOCTYPE html>
<html>
<head>
<title>WBT Charts</title>
<link rel="stylesheet" type="text/css" href="wbt.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="wbt.js"></script>
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,500,700' rel='stylesheet' type='text/css'>
</head>
<body>
<section>
<article>
<div id="wbtBlock">
<p>Press enter to save amendments</p>
<h1>Title of wbt:<input type="text" id="wbtTitle" /></h1>
<div id="graph">
<p>Graph to go here</p>
</div>
<p><strong>Notes: </strong></p>
<p><span><input type="textarea" id="wbtNote" /></span></p>
</div>
</article>
</section>
<button>Add New WBT Chart</button>
</body>
Here is the jQuery code I wrote:
$(document).ready(function() {
$("h1").keypress(function(e) {
//get
wbtTitle = $('#wbtTitle').val();
// Write text after enter
if (e.which == 13) {
$("h1").text(wbtTitle);
}
});
$("span").keypress(function(e) {
//get
wbtNote = $('#wbtNote').val();
// Write note after enter
if (e.which == 13) {
$("span").text(wbtNote);
}
});
//Insert new WBT on button click
$("button").each(function() {
$(this).click(function() {
var wbtSet = $( "article" ).html();
$(wbtSet).insertAfter('section');
});
});
});
What I want to do is set the title and some note text using input boxes which works using jQuery. I then want to add a copy of the html into another article when the button is pressed without copying the inputs previously made with the possibility of setting new values when the article is cloned. The process should repeat over and over again.
Here is an image to help explain:
I am quite new to jQuery, I think you need to use a loop to fix this, I read that a .each() can be used http://api.jquery.com/jQuery.each/ but not quite sure.
Any help will be appreciated. Thanks.
I think I got your answer.
I changed the html a bit, because you duplicated some id's with your approach, that's not good. id's have to be unique on a page. I simply changed them to classes.
<!DOCTYPE html>
<html>
<head>
<title>WBT Charts</title>
<link rel="stylesheet" type="text/css" href="wbt.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="wbt.js"></script>
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,500,700' rel='stylesheet' type='text/css'>
</head>
<body>
<section>
<article>
<div class="wbtBlock">
<p>Press enter to save amendments</p>
<h1>Title of wbt:<input type="text" class="wbtTitle" /></h1>
<div class="graph">
<p>Graph to go here</p>
</div>
<p><strong>Notes: </strong></p>
<p><span><input type="textarea" class="wbtNote" /></span></p>
</div>
</article>
</section>
<button>Add New WBT Chart</button>
</body>
And of course the jQuery. I got rid of your first two functions because they had no purpose in this context.
$(document).ready(function() {
//Insert new WBT on button click
$("button").on('click', function() {
var title = $(this).prev().find('.wbtTitle').val();
var note = $(this).prev().find('.wbtNote').val();
var wbtSet = $(this).prev("section").html();
$(this).prev().find('.wbtTitle').replaceWith(title);
$(this).prev().find('.wbtNote').replaceWith(note);
$(this).prev("section").after('<section>' + wbtSet + '</section>');
});
});
Here is a working fiddel
Fixing the answer given by hitokun_s
window.onload = function() {
// Save a copy of the element wbtSet element on pageload
var wbtSet = $("article").clone();
$("button").each(function() {
$(this).click(function() {
// Append a new one to the holder of the wbSets
$(wbtSet).appendTo($('section'));
});
});
}
I think this is what you want to do.
window.onload = function() {
$("button").each(function() {
$(this).click(function() {
var wbtSet = $("article:first-child").clone();
wbtSet.find("input").val("");
$(wbtSet).appendTo($('section'));
});
});
}
It always seems to be a problem and I fail to see why, I'm trying to change element p text by using his ID, element p id="para1" is inside PostEditor.html:
The elementID I want to change is para1 in the following html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
The following function is issued by a click on a link inside index.html and displaying the page you are seeing above and is then supposed to change its content:
From index.html I issue the function from link:
<a onclick="postEditing()"> Edit</a>
This line issue the following function:
function postEditing()
{
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.document.getElementById("para1").innerHTML = "11111111111";
result.document.getElementById("para1").innerText = "11111111111";
result.document.getElementById("para1").value = "11111111111";
}
As you can see I tried three methods. I'd never understand what is the difference between them, but I tried all three and none worked!
It's because you're searching the document of the window which shows the index.html, not the document of the newly opened window. try following:
...
var editorWindow = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
editorWindow.document.getElementById("para1").innerHTML = "11111111111";
...
EDIT:
NOW i see the problem: in the function you're trying to access a property of the parameter element, but you don't pass a value for it. So this will end in an error because the accessed object is undefinded!
So you have three options to get it working:
test the parameter (always a good idea): var ID = null; if(element) ID = element.id;
pass a value: <a onclick="postEditing(this)"> Edit</a>
remove the line var ID = element.id;
SOLUTION: (TESTED)
I could not really say why, but the index.html found the para1 and can successfully set the new text. But somehow the new window will reinitialize the old value again.
So you have to do the changing in an handler you run at onLoad:
index.html:
<html>
<head>
<script>
function postEditing() {
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.onload = function() {
result.document.getElementById("para1").innerHTML = "11111111111";
}
}
</script>
</head>
<body>
<a onclick="postEditing()"> Edit</a>
</body>
</html>
PostEditor.html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
I'm fairly sure you will need to query the return result of calling window.open like this:
function postEditing(element)
{
var ID = element.id;
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.getElementById("para1").innerHTML = "11111111111";
result.getElementById("para1").innerText = "11111111111";
result.getElementById("para1").value = "11111111111";
}
[Untested though]
Your button type is submit, which is posting the form. The object is changing in the DOM, only after the script runs, the DOM is reloaded back to it's original state. Try changing your button type to "button", and you should see the P element change appropriately.
Edit: Here's the HTML I used to determine the above. Keeping the button as "submit" caused me to see the text change and then swap back. The HTML below should keep the text in place. HTH!
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<script>
function postEditing(element)
{
document.getElementById('para1').innerHTML = "asdafs";
}
</script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="button" onclick="postEditing('caller')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>