Why is the text getting appended to the wrong html element? - javascript

Overview: I have an editable div section. Below the div, there is a button which creates a span element, inserts the text "tag" in the span element and finally appends the span element in that editable div
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
#sample-div
{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
</style>
<script type="text/javascript">
function addTags()
{
var tag = document.createElement("span");
tag.className = "tag"
tag.innerHTML = "tag";
$('#sample-div').append(tag);
}
</script>
</head>
<body>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
</body>
</html>
Observation: I click on the button, the span element is added to the div as expected
<div id="sample-div" contenteditable="true">
<span class="tag">tag</span>
</div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
However, after I start typing inside the div, I noticed the following:
<div id="sample-div" contenteditable="true">
<span class="tag">tag this is a continuation</span>
</div>
My expectation was:
<div id="sample-div" contenteditable="true">
<span class="tag">tag</span> this is a continuation
</div>
So, my question is why the text "this is a continuation" also getting appended inside the span element? How do I achieve the one stated under my expectation?

The easiest solution would be to set the contentEditable attribute of your span to be false:
function addTags() {
var tag = document.createElement("span");
tag.className = "tag"
tag.innerHTML = "tag";
tag.contentEditable = false;
$('#sample-div').append(tag);
}
Side note: since you are using jQuery you don't need to manually create the tag:
function addTags() {
var tag = '<span class="tag" contenteditable="false">tag</span>'
$('#sample-div').append(tag);
}

Related

How to copy HTML code from the browser using javascript

I want to copy the HTML code by clicking on the button using javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#data {
background: #eee;
width: 300px;
padding: 13px;
text-align: center;
font-family: arial;
}
</style>
</head>
<body>
<button type="button" onclick="copyToClipboard('data')">Copy </button>
<textarea id="data" name="data">
<p>I Want to copy this html code1.</p>
<p>I Want to copy this html code2.</p>
</textarea>
<script src="doc/jquery.min.js"></script>
<script src="doc/clipboard.min.js"></script>
<script>
window.copyToClipboard = function(elementId) {
var aux = document.getElementById(elementId);
aux.select();
document.execCommand("copy");
}
</script>
</body>
</html>
I try this code, but it shows the code only, and I want it to show the preview of the HTML code.like this
So how can I copy HTML code from the browser by clicking on the button?
A textarea is a text only element.
It won't parse the HTML in its value.
What you might want to look into is a WYSIWYG editor that supports html export of its contents.
I have used TinyMCE (self-hosted, there is a paid option as well) in the past tho there are definitely other options. I have no affiliation with TinyMCE.
Edit:
After clarifying, here is a sample of the code:
<button onclick="fun_name();">get outerHTML</button>
<div id="idDiv">
<div id="data">
<p>I Want to copy this html code1.</p>
<p>I Want to copy this html code2.</p>
</div>
</div>
<script>
function copyToClipboard(text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
function fun_name() {
var elem = document.getElementById("idDiv").outerHTML;
copyToClipboard(elem)
}
</script>

How to trigger an event when a particular HTML element is removed automatically?

Overview of the code: This code consists of an editable div section. Below the div, there is a button which creates a span element, inserts the text "tag" in the span element and finally appends the span element in that editable div
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
#sample-div
{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
</style>
<script type="text/javascript">
function addTags()
{
var tag = document.createElement("span");
tag.className = "$(tag)"
tag.innerHTML = "tag";
tag.contentEditable = false;
$('#sample-div').append(tag);
}
$(document).ready(function(){
$('span').keyup(function(){
if(!this.value)
{
alert('this is empty');
}
});
});
</script>
</head>
<body>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
</body>
</html>
General observation: When I type something inside the div and then click on the button, the HTML DOM will change as:
<div id="sample-div" contenteditable="true">
this is a <span class="$(tag)" contenteditable="false">tag</span>
</div>
Please note that the text "this is a", is provided by me when I type inside the div element. "tag" appears when I click on the input button
Expectation / Trying to achieve: When I delete the text in the span, the DOM will change as:
<div id="sample-div" contenteditable="true">
this is a
</div>
So, my aim is to get the information that the element span is removed when I delete the text in span. I am trying to achieve that by doing the following, which is not correct:
$(document).ready(function(){
$('span').keyup(function(){
if(!this.value)
{
alert('this is empty');
}
});
});
So, my question is how do I get the message "this is empty" when the DOM removes the span element?
You could use a variable as a "tag" counter.
When the amount tags present in the div gets lower than the tag counter, that is when one got deleted.
var tagCount = 0;
function addTags(){
var tag = document.createElement("span");
tag.className = "$(tag)"
tag.innerHTML = "tag";
tag.contentEditable = false;
$('#sample-div').append(tag);
// Increment tagCount
tagCount++;
}
$(document).ready(function(){
$('#sample-div').keyup(function(){
if($(this).find("span").length < tagCount){
alert('One tag was removed');
// Decrement tagCount
tagCount--;
}
});
}); // Ready
#sample-div{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
You probably should use MutationObserver
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<style type="text/css">
#sample-div
{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
</style>
</head>
<body>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
<script type="text/javascript">
'use strict';
function addTags()
{
var tag = document.createElement("span");
tag.className = "$(tag)"
tag.innerHTML = "tag";
tag.contentEditable = false;
document.getElementById('sample-div').appendChild(tag);
}
function onTagRemoved(node)
{
alert(`node ${node.tagName}.${node.className} removed`);
}
//
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
//
// select the target node
let target = document.querySelector('#sample-div');
// create an observer instance
let observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// console.log(mutation);
let node = null;
for (var i = 0; i < mutation.removedNodes.length; i++) {
node = mutation.removedNodes[i];
if (/span/i.test(node.tagName)) {
onTagRemoved(node);
}
}
});
});
// configuration of the observer:
let config = { attributes: false, childList: true, characterData: false }
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop obser
// observer.disconnect();
</script>
</body>
</html>
Tested on Firefox 52

How to change the style of another element inline using javascript?

I would like to change the style of another inside a html element using javascript.
I have used the below code to change the current html element.
<p onmouseover="this.style.color = 'black;">This text should be changed</p>
<h1>How to change this element when hovered on p element</h1>
I would like to change the other element's style inside the p tag using javascript.
can anyone help?
Using CSS you can achieve the same
<style>
p:hover + h1 {
background-color : red
}
</style>
This should be what you're after (not my work) - check out the fiddle link ...
<html>
<body>
<span id="div1" style="color:black;" onmouseover="stext()" onmouseout="htext()">TEXT1</span><p />
<hr color="black" />
<span id="div2" style="color:red;" onmouseover="htext()" onmouseout="stext()">Text2</span>
</body>
http://jsfiddle.net/FFCFy/16/
for example if you want to change the color:
<script>
document.getElementByTagName("p").style.color = "blue";
</script>
that should probably bound to an event, accordingly to what you want to do
use this :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<p style="color:red;" onmouseover="ch(event)">This text should be changed</p>
<h1>How to change this element when hovered on p element</h1>
<script>
function ch(e) {
e.target.style.color = "black";
alert();
}
</script>
</body>
</html>
use with Javascript
function change(that){
document.getElementsByTagName('h1')[0].style.color="red";
}
<p onmouseover="change()">This text should be changed</p>
<h1>How to change this element when hovered on p element</h1>
use with css
p:hover + h1{
color:red;
}
<p >This text should be changed</p>
<h1>How to change this element when hovered on p element</h1>
jQuery("p").mouseover(function(){
jQuery("h1").css("color", "yellow");
});
You can easily achieve it with jQuery:
$(function() {
$('#a-element').hover(function() {
$('#b-element').css('background-color', 'yellow');
}, function() {
// on mouseout, reset the background colour
$('#b-element').css('background-color', '');
});
});
If #b comes immediately after #a, the simplest solution is in pure css:
#a:hover + #b {
background: #ccc
}
If between #a and #b are other elements, you have to use ~ like this:
#a:hover ~ #b {
background: #ccc
}

Displaying text when link is clicked

This is inside my CSS:
div.hide {
display:none;
}
div.show {
color: #66CCFF;
}
This is in my HTML:
16:10
<script language="JavaScript">
function showText(show,hide)
{
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<a name="16:10" onclick="showText('text1')" href="javascript:void(0);"></a>
<div id="text1" class="hide">This is your monitors aspect ratio.</div>
I'm trying to make the first link display the "This is your monitors aspect ratio." text lower on the page.
Any help is much appreciated.
Pure CSS Answer
Ok, if you just want to append text after you have moved to a position in a page using an anchor tag, you could do it with nothing but CSS similar to the following:
a:target:after{
content: " Test";
background-color: #ccffcc;
}
What this does is appends the text "Test" after the active anchor and colors. Here is an example page with implementation:
<!DOCTYPE html>
<html>
<head>
<title>Link Printer 2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
a:target:after{
content: " Test";
background-color: #ccffcc;
}
.bigSection{
height: 200px;
}
</style>
</head>
<body>
<div class="bigSection">
<div><a name="first">First</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
<div class="bigSection">
<div><a name="second">Second</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
<div class="bigSection">
<div><a name="third">Third</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
</body>
</html>
Answer using JavaScript
You need to bind an eventListener and prevent it from moving to the next page. Here is a way to do it with JavaScript or CSS. The JavaScript way will actually set the text to whatever you want. The CSS way will hide actually hide the element.
<!DOCTYPE html>
<html>
<head>
<title>Link Printer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
.hide{
display: none;
}
</style>
<script>
function jsShowText(event) {
var divToManip = document.getElementById("text");
if (divToManip.innerHTML === "") {
divToManip.innerHTML = "Hello";
}
else {
divToManip.innerHTML = "";
}
event.preventDefault();
}
function cssShowText(event) {
var divToManip = document.getElementById("text");
if (divToManip.className === "") {
divToManip.className = "hide";
}
else {
divToManip.className = "";
}
event.preventDefault();
}
function setListeners() {
document.getElementById("jsPrinter").addEventListener("click", jsShowText, false);
document.getElementById("cssPrinter").addEventListener("click", cssShowText, false);
}
window.onload = setListeners;
</script>
</head>
<body>
<div><a id="jsPrinter" href="" onclick="showText();">Click With JavaScript</a></div>
<div><a id="cssPrinter" href="" onclick="showText();">Click With CSS</a></div>
<div id="text">I'm text</div>
</body>
</html>
"showText" must receive an id parameter to be used with the call to "document.getElementById"
Try this, just 1 link that will display the text below after click:
<a name="16:10" onclick="showText('text1')" href="javascript:void(0);">16:10</a>
<script language="JavaScript">
function showText(id)
{
document.getElementById(id).style.display = "block";
}
</script>
<div id="text1" style="display:none;">This is your monitors aspect ratio.</div>
I'm just using style display to hide/show the element. Hope it helps.
just change your css like this:
div.show {
display:block;
color: #66CCFF;
}
Here I am going to provide an example with something that I was working, thank you Alberto Montellano for the example, that gave me an idea, however what was required at the end was something a little different, with the option not to show the data and display it only when I click and make it disappear when click again. In this example I am going to give you two options; you can have a button or a link to trigger the JS function to display and hide the body text, you can choose if you want the button or link that is way I put a comment (optional), both behave as the same, it is up to you which one you want to use.
<!DOCTYPE html>
<html>
<head>
<!-- CSS -->
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top:20px;
}
</style>
</head>
<body>
<!-- text before the button or link -->
<p>Click the "PIN" button (or link) to display PIN options:</p>
<!-- The Pin button (optional) -->
<button type="button" onclick="myFunction()">PIN button:</button>
<!-- The Pin link (optional) -->
</br></br></br>
<a onclick="myFunction()" href="javascript:void(0);">PIN link:</a>
<!--Data will display or hide (toggle)-->
<div id="myDIV"style="display:none;">
These are the steps to get your PIN number: Bla bla bla.
</div>
<p><b>Note:</b> The text display when you click the button or link will take space, if you click again will be toggle.</p>
<!-- JS -->
<script>
function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
</body>
</html>

How to clone div wrap on button click?

http://jsfiddle.net/TDmRv/1/
What I want to do: I want the div with the id "theDiv" to be wrapped around the text that gets inputted onto the page. I want this so the text will appear in multiple divs that are created.
Explained more:
Okay, so what I am trying to do is type some input in and have it display with in a div- that works fine, but I want the div to wrap around it when I click input. So every time I click "add" the text gets wrapped into a div and is displayed. BUT I am also trying to make this appear multiple times, so every time I add input the div is wrapped around the text. Finally I am trying to have those two buttons placed into there, I assume those would have to be inserted when "add" is clicked with jQuery. I just need some guidance because I am struggling to comprehend how this will work.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#edit").click(function(){
$("#theDiv").css("background-color","red");
});
});
$(document).ready(function(){
$("#delete").click(function(){
$("#theDiv").remove();
});
});
$(document).ready(function(){
$("#add").click(function(){
$('#edit').wrap('<div class="theDiv" />');
});
});
</script>
<style>
#theDiv {
border: 1px solid rgb(204, 204, 204);
margin: 5px 0pt;
padding: 5px;
background-color: blue;
height:50px;
}
button {
float:right;
}
</style>
</head>
<body>
<div id="hold">
<button id="edit">Edit</button><button id="delete">Delete</button>
</div>
<form>
<div><textarea class="textI" id="textI2" style="width: 400px; height: 50px;"></textarea></div>
<div><input type="button" id="add"value="add" onclick="theDiv_append()" /></div>
</form>
<script language="javascript">
$('.textI').each(function() {
var default_value = this.value;
$(this).focus(function() {
if(this.value == default_value) {
this.value = '';
}
});
});
function theDiv_append() {
$('#theDiv').append($('#textI2').val());
}
</script>
</body>
</html>
try this , change #add click to this , it works in jsfiddle, just add the text, I didn't do that , but you will see how to add new blue div
$("#add").click(function(){
var newRow = $('#theDiv').clone();
$('#hold').append(newRow);
$('#edit').wrap('<div class="theDiv" />');
});
});

Categories

Resources