How to link an appended title? - javascript

I currently have an editor that allows users to enter input and save their input under a specific title. I have a button which allows them to do so, as well as adding the name of their title to a box (just a div with white background) using append child.
Was wondering how I could link these titles, such that when they click on one title, the text input assigned to said title shows up inside my editor?
Javascript:
<!-- Function to save the user's input inside editor1 -->
function saveEdits() {
var editElem = document.getElementById("editor1");
var userVersion = editElem.innerHTML;
localStorage.userEdits = userVersion;
//Get the title from the user
var title = prompt("What would you like your title to be?");
localStorage.setItem(title, editElem.innerHTML);
//Asigning the titles input by the user to the key "titles"
titles = localStorage.getItem("titles");
if (titles == null){
titles = [];
}
else {
titles = JSON.parse(titles);
}
var obj;
obj = {"titles": title};
titles.push(obj);
localStorage.setItem("titles",JSON.stringify(titles));
//Save the editor contents to local storage based on title
document.getElementById("update").innerHTML = "Edits saved!";
var theDiv = document.getElementById("Contentable");
var content = document.createTextNode(title);
theDiv.appendChild(content);
var br = document.createElement("br");
theDiv.appendChild(br);
}
<!-- Function to check if the user has any saved input -->
function checkEdits() {
if(localStorage.userEdits != null)
document.getElementById("editor1").innerHTML = localStorage.userEdits;
}
function loadEdits(title) {
//load useredit for title from local storage
var userEdits = localStorage.getItem(title);
var editElem = document.getElementById("editor1");
editElem.innerHTML = userEdits;
}
HTML (Editor):
<!-- Editor 1 -->
<div id="editor1" contenteditable="true" style="margin-left:30em">
</div>
<input id="savechanges" type="button" value="Save Changes" onclick="saveEdits()"/>
<div id="update">Click to save your changes made</div>

You could attach an onclick-event to the markup. Like this.
<div class="container>
<h2 class="title" onclick="edit(this)">
EDITABLE CONTENT BELOW
</h2>
<div class="editable" onclick="edit(this)">
</div>
The js
var activeParent;
function edit( element ){
var title = element.parentNode.children[ 0 ].innerHTML;
var content = element.parentNode.children[ 1 ].innerHTML;
//do stuff with the markup
activeParent = element.parentNode;
}
That is how you can get the content and temporarily store the active parent as a reference. So when you save it is activeParent.children[ 1 ].innerHTML = editedContent.
EDIT: Since all of these are relative references you can use as many as you want. Just be careful when using the activeParent. It assumes you only edit one area at a time.

Related

Covert html in javascript to HTML tags

I'm working on the tooltips and from the backend I'll get data in with html tags. I need to show in the tooltip with its corresponding data in its respective tags. For example, I'll get hello user click here from the backend. I've to show as hello user in h1 format and click here should be a anchor. I tried with both functions and replace its not working.
With function:
<h1 id="data">
</h1>
function convertToPlain(html){
var tempDivElement = document.createElement("div");
tempDivElement.innerHTML = html;
return tempDivElement.textContent || tempDivElement.innerText || "";
}
var htmlString= "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute<a> click here<a></p></div>";
let dataVal = convertToPlain(htmlString)
document.getElementById("demo").innerHTML = dataVal;
With replace:
https://codesandbox.io/s/serene-fast-u8fie?file=/App.svelte
I made below snippet by copy-paste your code and just update return statement inside convertToPlain function, also I added href attribute to <a> in the htmlString content.
function convertToPlain(html) {
var tempDivElement = document.createElement("div");
tempDivElement.innerHTML = html;
return tempDivElement.innerHTML;
}
var htmlString = "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute<a href='#'> click here<a></p></div>";
let dataVal = convertToPlain(htmlString)
document.getElementById("demo").innerHTML = dataVal;
<h1 id="demo"></h1>

How can I add a span to h3 Element with javascript

I'm making a chat and I want to add an avatar pics feature so I figured it might work well with span, but the problem is I don't know how to add the span to the element.
let avatar = document.createElement("span");
let userMessage = document.createElement("H3");
avatar.setAttribute(userMessage);
userMessage.innerHTML = username + ": " + message;
//document.getElementById("chat").appendChild(avatar);
document.getElementById("chat").appendChild(userMessage);
userMessage.style.background = color;
userMessage.style.textAlign = "left";
document.getElementById("msg").value = "";
I am assuming that you have div with id="chat" and you want to append an h3 tag in a span and then append the chat div so your code will look like this
var username="zulqarnain jalil";
var message ="welcome back, have a nice day";
var color='lightgrey';
var avatar = document.createElement("span");
var userMessage = document.createElement("h3");
userMessage.innerHTML = username + ": " + message;
userMessage.style.background = color;
userMessage.style.textAlign = "left";
avatar.appendChild(userMessage);
document.getElementById("chat").appendChild(avatar);
//document.getElementById("msg").value = "";
<div id="chat">
</div>
I have created a chatbot snippet for you, here you can test it
var username="zulqarnain jalil";
function sendMessage()
{
var message =document.getElementById('messagebox').value;
if(message)
{
document.getElementById('messagebox').value='';
var color='lightgrey';
var avatar = document.createElement("span");
var userMessage = document.createElement("h3");
userMessage.innerHTML = username + ": " + message;
userMessage.style.background = color;
userMessage.style.textAlign = "left";
avatar.appendChild(userMessage);
document.getElementById("chat").appendChild(avatar);
}
else
{
// message empty
}
}
//document.getElementById("msg").value = "";
<div id="chatBox">
<div id="chat">
</div>
<div>
<input type="text" id="messagebox" />
<input type="button" onclick="sendMessage()" value="Send" />
</div>
</div>
First you need to add the span as a child of the H3 element.
I think the best approach to this problem is creating a class Message. Initializing that class creates h3 and span with unique ids stored in a variable id for future use. The class will also add the h3 as a child of it's parent element ( what ever it is ), and the span as a child of the h3 element.
var counterText = 0;
var counterAvatar = 0;
class UserMessage {
constructor(msgTxt, avatar){
// This block initializes the text message of the user
// It will also add an id to the tag for future use
let msgTxt = document.createTextNode(msgTxt);
this.messageID = 'text' + counterText;
this.message = document.createElement('h3');
this.message.appendChild(msgTxt);
this.message.setAttribute('id', this.messageID);
counterText++;
// This block creates an img element with the attributes src and id
this.avatarID = 'avatar' + counterAvatar;
this.avatar = document.createElement('img');
this.avatar.setAttribute('src', avatar);
this.avatar.setAttribute('id', this.avatarID);
counterAvatar++;
// This block appends the avatar element to the text and the text to the
// chat div.
let chat = document.getElementById('chat');
this.message.appendChild(this.avatar);
chat.appendChild(this.message);
}
}
to initialize a new instance:
var message = new UserMessage("Hello, this is a text message!",'<path/to/avatar>')
this is an object oriented aproach.
you could also just append the avatar to the message and the message to the chat.
But I think aproaching the problem in an object oriented way is much better since it will save time in the future when you're updating your app.
Markdown works fine in here.
Block-level HTML elements have a few restrictions:
They must be separated from surrounding text by blank lines.
The begin and end tags of the outermost block element must not be indented.
Markdown can't be used within HTML blocks.

create the variable link as a hyperlink javascript

create a hyperlink with the variable link
<html>
<body>
<center><h1> retrive data</h1></center>
<h1 id="head1"> </h1>
<input type="text" placeholder="enter your unique id" id="pass"/>
<input type = "button" value = "submit" id="but" onclick="myfunction();"/>
<script>
var pass;
function myfunction()
{
pass = document.getElementById("pass").value;
document.writeln(pass);
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
var passwordToLookFor = pass;
var ref = firebase.database().ref("users");
var query = ref.orderByChild("password").equalTo(passwordToLookFor);
query.once("value").then(function(snapshot) {
snapshot.forEach(function(child) { // loop over the results
console.log(child.key);
console.log(child.val().user_name);
var link = child.val().user_name;
document.writeln(link);
});
});
}
</script>
</body></html>
i want to create the value of link as a hyperlink
i want the hyperlink to be created once when the function is called
Are you just looking for how to make it an anchor tag?
<script>
var pass;
function myfunction()
{
...
var link = child.val().user_name;
document.writeln("<a href='"+link+"' target='_blank'>"+link+"</a>");
});
});
}
</script>
</body></html>
You can create an a dom element like this:
let link_el = document.createElement('a')
link_el.href = link // assuming link holds the value of the href you want
Then insert it into the dom wherever you want.
If I understand correctly and the link variable contains the actual address you want to navigate to, then this will work. First simply set an ID on the div you want to populate with links:
<div id="target-div"></div>
Then populate it like so (I just created an array for demo purposes, but this would be your snapshot.forEach:
var links = ['link1', 'link2', 'link3']
var targetDiv = document.getElementById("target-div");
links.forEach(function(link) {
var anchor = document.createElement('a');
anchor.href = link;
anchor.innerText = link;
targetDiv.appendChild(anchor);
var br = document.createElement('br');
targetDiv.appendChild(br);
});
Demo: https://jsfiddle.net/csnuh7rd/2/

Using multiple editable elements in HTML5 / Javascript

I want to use the to be able to type data into a page, press a button to save the data, then be able to close and re-open the page with the saved data.
I have been able to do this with the code below with 1 text area, but if I use multiples, it only displays the last entered data.
Here's my code:
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
function saveEdits() {
//get the editable element
var editElem = document.getElementById("CPU")
var editElem = document.getElementById("RAM")
var editElem = document.getElementById("HDD")
//get the edited element content
var userVersion = editElem.innerHTML;
//save the content to local storage
localStorage.userEdits = userVersion;
//write a confirmation to the user
document.getElementById("update").innerHTML="Edits saved!";
}
function checkEdits() {
//find out if the user has previously saved edits
if(localStorage.userEdits!=null)
document.getElementById("CPU").innerHTML = localStorage.userEdits
document.getElementById("RAM").innerHTML = localStorage.userEdits
document.getElementById("HDD").innerHTML = localStorage.userEdits
}
</script>
</head>
<body onload="checkEdits()">
<label>Processor : </label>
<div id="CPU" contenteditable="true"></div><br><br><br>
<label>RAM : </label>
<div id="RAM" contenteditable="true"></div><br><br><br>
<label>Hard Drive : </label>
<div id="HDD" contenteditable="true"></div><br><br><br>
<input type="button" value="SAVE" onclick="saveEdits()"/>
<div id="update"></div>
</body>
</html>
You need to have 3 different variables for each of the 3 inputs, see fiddle: https://jsfiddle.net/xtat0oa6/5/
javascript
function saveEdits() {
//get the editable element
var editElem1 = document.getElementById("CPU")
var editElem2 = document.getElementById("RAM")
var editElem3 = document.getElementById("HDD")
//get the edited element content
var userVersion1 = editElem1.innerHTML;
var userVersion2 = editElem2.innerHTML;
var userVersion3 = editElem3.innerHTML;
//save the content to local storage
localStorage.userEdits1 = userVersion1;
localStorage.userEdits2 = userVersion2;
localStorage.userEdits3 = userVersion3;
//write a confirmation to the user
document.getElementById("update").innerHTML = "Edits saved!";
}
function checkEdits() {
//find out if the user has previously saved edits
if (localStorage.userEdits1 != null || localStorage.userEdits2 != null || localStorage.userEdits3 != null){
document.getElementById("CPU").innerHTML = localStorage.userEdits1
document.getElementById("RAM").innerHTML = localStorage.userEdits2
document.getElementById("HDD").innerHTML = localStorage.userEdits3}
}

Replacing DIV content based on variable sent from another HTML file

I'm trying to get this JavaScript working:
I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.
<!-- ORIGINAL DIV -->
<div id="Email">
</div>
<!-- DIV replacement function -->
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';
ReplaceContentInContainer('Email1',content);
}
</script>
<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';
ReplaceContentInContainer('Email2',content);
}
</script>
Any ideas what I've done wrong that is causing it not to work?
Rather than inserting the element as text into innerHTML create a DOM element, and append it manually like so:
var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"
document.getElementById("email").appendChild(obj);
See this working here: http://jsfiddle.net/BE8Xa/1/
EDIT
Interesting reading to help you decide if you want to use innerHTML or appendChild:
"innerHTML += ..." vs "appendChild(txtNode)"
The ReplaceContentInContainer calls specify ID's which are not present, the only ID is Email and also, how are the two scripts called, if they are in the same apge like in the example the second (with a corrected ID) would always overwrite the first and also you declare the content variable twice which is not permitted, multiple script blocks in a page share the same global namespace so any global variables has to be named uniquely.
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.
As for grabbing the content parameter from the query string:
var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}".
With the closing "}", you are closing a block of code you never opened.
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:
<script type="text/javascript">
function ParseQueryString() {
var result = new Array();
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
</script>
Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:
<div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...
Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var contentId = QS["content"];
if (contentId) {
var source = document.getElementById(contentId);
if (source) {
var target = document.getElementById("Email");
target.innerHTML = source.innerHTML;
}
}
}
How about this? Hacky but works...
<!-- ORIGINAL DIV -->
<div id="Email"></div>
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}
window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>

Categories