write html code in div and see result instantly - javascript

How to setup a div to see the instant result of html by making the div contenteditable. Like
<div id="edit" contenteditable="true"></div>
<button id="trigger">Apply code</button>
Here, div id="edit" assumed to be editor and result viewer as well itself. e.g. write code on div then click on "Apply code" button and the result of html code written in div should be appeared within the same div (i.e. div id="edit").

html
<div id="edit" contenteditable="true"></div>
<button id="trigger" onclick="applyCode()">Apply code</button>
js
function applyCode() {
$('#edit').html($('#edit').html());
}

So here's the basic setup of what you're trying to do...
<div id='editor' contenteditable></div>
<button id='trigger' value='apply'>
And the JS code:
document.getElementById('trigger').addEventListener('click', (function(dv)
{
return function()
{
dv.innerHTML = dv.textContent;
};
}(document.getElementById('editor'))), false);
Here's a fiddle.
But play around with it, and you'll soon find out that there's a problem with it: Try adding markup tags, and edit the input a second time. That's not going to work as well as you'd hope.
Also check out the resulting DOM, after the user puts in some multi-line input: new divs, paragraphs and what have you are added. You'll have to preserve that markup, using something like:
document.querySelector('#editor').addEventListener('click', function()
{
var currentMarkup = this.innerHTML;
}, false);
Then, you'll have to set about sharing that innerHTML with the trigger event handler, and find a way to check if the user changed the actual markup. Have fun with that...
I suggest you use tools that have already been written, tried and tested, instead of setting about building your own.
It'll take you too long, and you'll end up with something that's not even half as capable as the existing editors out there.
Check this related post for details: Replace words of text area

First you need to create an input box where you can type your html code.
<div id="edit"><textarea id='editor'></textarea></div>
Then there is the button, which 'renders' the code.
<button id="trigger">Apply code</button>
Next, you need to create a javascript code which changes the content of '#edit' to '#editor' 's value.
var edit = document.getElementById('edit');
var editor = document.getElementById('editor');
var trigger = document.getElementById('trigger');
trigger.onclick = function() {
edit.innerHTML = editor.value;
};
Fiddle: http://jsfiddle.net/W75Ut/1/

<div id="editable" contenteditable="true">aaaaaaa</div>
<br/>
<button onclick="texttohtml()">Click to apply Html</button>
<script>
function texttohtml()
{
var t=$("#editable").text();
$("#editable").html(t);
}
</script>

Related

Remove any specific html code using javascript

In the past I used Google Developer Console to delete some specific divs on a page. I could do it manually of course but in some cases where the divs where many I had to use the console. I had a single line code that did the job (I found it while searching the internet) but I lost my note.
So how can I delete using javascript any html code (by copy pasting the code).
Something like:
elements = $('<div ... </div>');
elements.remove();
OR
$('<div ... </div>').remove();
Any ideas? I am not an expert in javascript (obviously) and I've been searching stackoverflow for hours without finding anything that works.
UPDATE: I think some people might get confused with my question. Google developer console accepts javascript command lines. So even though I ask for javascript I will use the code on the google developer console.
UPDATE 2 :
Here is an example of a div I need to delete. Keep in mind I want to copy paste the entire code in the javascript code. Not just identify the div.
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
It's the data-entry-status="declined" that makes that div unique so I can't just identify the div using an id selector or a class selector. I need to put the entrire thing there and remove it.
I tried:
$('<div class="entry-status-overlay" data-entry-status="declined"><div class="entry-status-overlay__inner"><span class="entry-status-overlay__title">Declined</span></div></div>').remove();
It didn't remove the div.
Try to search the dom by its outerHTML.
function deleteDomByHtml(html){
html=html.replace(/\s/g,'');
$("*").each(function(){
if(this.outerHTML.replace(/\s/g,'')===html){
$(this).remove();
}
});
}
And try this line on this page:
deleteDomByHtml(`<span class="-img _glyph">Stack Overflow</span>`);
You cannot do by simply pasting the code. That will remove all the div element.
You may need a specific selector like id,class or child to specific parent to remove the element from the dom.
Consider this case the divs have common class but the data-entry-status is different. So you can get the dom using a selector and then check the dataset property.
For demo I have put it inside setTimeout to show the difference. In application you can avoid it
setTimeout(function() {
document.querySelectorAll('.entry-status-overlay').forEach(function(item) {
let getStatus = item.dataset.entryStatus;
if (getStatus === 'declined') {
item.remove()
}
})
}, 2000)
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
<div class="entry-status-overlay" data-entry-status="accepted">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">accepted</span>
</div>
</div>
Just add any attribute with [] and it will remove the element.
$('[class="entry-status-overlay"]').remove();
/*OR*/
$('[data-entry-status="declined"]').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
function del(){
var h = document.body.outerHTML;
h = h.match('<div>...</div>');
h.length--;
return h;
}
I guess this will work just give it a try... i tried on browser console and it worked, this way you can match the exact you want.
I might as well add my take on this. Try running this in your console and see the question vanish.
// convert the whole page into string
let thePage = document.body.innerHTML,
string = [].map.call( thePage, function(node){
return node.textContent || node.innerText || "";
}).join("");
// I get some string. in this scenario the Question or you can set one yourself
let replacableCode = document.getElementsByClassName('post-layout')[0].innerHTML,
string2 = [].map.call( replacableCode, function(node){
return node.textContent || node.innerText || "";
}).join("");
// replace whole page with the removed innerHTML string with blank
document.body.innerHTML = thePage.replace(replacableCode,'');
If you want to identify divs with that particular data attribute, you can use a data-attribute selector. In the example below, I've used a button and click event to make the demo more visual, but in the console the only line you'd need would be:
$('div[data-entry-status="declined"]').remove();
$(function() {
$("#testbutton").click(function() {
$('div[data-entry-status="declined"]').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
<div id="x">Some other div</div>
<button type="button" id="testbutton">Click me to test removing the div</button>
See https://api.jquery.com/category/selectors/attribute-selectors/ for documentation of attribute selectors.
P.S. Your idea to paste some raw HTML into the jQuery constructor and then execute "remove" on it cannot work - you're telling jQuery to create an object based on a HTML string, which is, as far as it's concerned, a new set of HTML. It does not try to match that to something existing on the page, even if that exact HTML is in the DOM somewhere, it pays it no attention. It treats what you just gave it as being totally independent. So then when you run .remove() on that new HTML...that HTML was never added to the page, so it cannot be removed. Therefore .remove() has no effect in that situation.

Post text to a parent element with option to remove posted elements - Javascript

There are a few things I'd like help with. I have found pieces of the solution on stack overflow, but can't quite put it all together.
I'd want the user to add text to a text area, click a button to post the text to a parent element, and finally have the option to remove the posted text element from the parent. This is as far as I have gotten on the code. Thanks in advance for any suggestions.
<body>
<h4>A News Module.</h4>
<div id="container">
<p>Here is some news.</p>
</div>
<textarea id="alltext" rows="13" cols="53" placeholder="Add your news here."></textarea>
<br>
<input type="button" value="Submit News" onclick="addNews()">
<script>
function addNews(){
var addEl = document.createElement('p');
document.getElementById('container').appendChild(addEl);
}
function deleteNews(){
var deleteEl = document.getElementById('container');
deleteEl.parentNode.removeChild(deleteEl);
}
</script>
</body>
Also on jsfiddle: https://jsfiddle.net/lotus89/nvo1s5re/
Two things.
1) You need to add the text from the textboxt into the newly created element. Add the folowing line right after the creation:
addEl.textContent = document.getElementById('alltext').value;
This grabs the value of the texbox and sets it as the textContent of the newly created element.
2) addNews() needs to be in the global scope for jsfiddle
Add this line:
window.addNews = addNews;
Edit: Update fiddle - https://jsfiddle.net/rtj998gL/1/
Take a look at your addNews code. You're creating a new p and adding it to the container, but you're never putting anything in it.
function addNews(){
//Create blank P element
var addEl = document.createElement('p');
//Set the new element's content to match the textarea value
addEl.innerHTML = document.getElementById("alltext").value;
//Add it to the container
document.getElementById('container').appendChild(addEl);
}
If you put your <script> in the head of your page, your code would work fine. But being that it's in the <body>, your functions are not being found because they are out-of-scope. You can adjust for this by doing window.addNews = addNews within your <script> tags.

Try It Yourself Editor JS

I have created a very simple editor that has been working great. However, I just tried to put JavaScript into it and I can't get it to work.
The code for the editor:
<div id="buttoncontainer">
<input id="button" onclick="update();" type="button" value="Update page">
</div>
<div id="tryitcontainer">
<textarea id="codebox"></textarea>
<iframe id="showpage"></iframe>
</div>
The JavaScript for the editor:
<script>
function update() {
var codeinput = document.getElementById('codebox').value;
window.frames[0].document.body.innerHTML = codeinput;
}
</script>
I just wanted to run some simple JavaScript that changes an image when it is clicked. This code works fine when I run it in a full browser, so I know its the editor thats the problem.
Is there a simple fix for this that I'm missing?
The button is not finding the update() method. You need that function to be globally available:
http://jsfiddle.net/t5swb7w9/1/
UPDATE: I understand now. Internally jQuery basically evals script tags. There's too much going on to be worth replicating yourself... either use a library to append, or eval the code yourself. Just a warning that eval'ing user input is rarely a good thing and is usually a welcome mat for hackers.
window.myScope = {
update: function() {
var div = document.createElement('div'),
codeinput = document.getElementById('codebox').value,
scriptcode = "";
div.innerHTML = codeinput;
Array.prototype.slice.apply(div.querySelectorAll("script")).forEach(function(script) {
scriptcode += ";" + script.innerHTML;
div.removeChild(script);
});
window.frames[0].document.body.appendChild(div);
// hackers love to see user input eval'd like this...
eval(scriptcode);
}
};
And then you would update your button like so:
<input id="button" onclick="myScope.update();" type="button" value="Update page">
Or, even better, use addEventListener and forget the onclick part altogether. I'll let you do that research on your own ;)
JavaScript inserted via innerHTML will not be executed due to security reasons:
HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
from MDN: Element.innerHTML - Security considerations, see also: W3: The applied innerHTML algorithm.
A possible solution using the jQuery method .append() works around that, as it somehow evals the content. But this will still not solve your problem, as the JavaScript code is executed in the current scope.
Here's a test scenario:
function update() {
var codeinput = document.getElementById('codebox').value;
$(window.frames[0].document.body).append(codeinput);
}
Try it here
Try to insert this script:
<script>
alert( document.getElementById('tryitcontainer') );
</script>
and this one:
<p id="test">Test</p>
<script>
window.frames[0].document.getElementById('test').innerHTML = 'updated';
</script>
The first one will return a [object HTMLDivElement] or similar. Here you can see, that you're still in the same scope as the parent frame. The second one will correctly update the content within the iframe. Keep that in mind, when experimenting with those things.
Maybe Executing elements inserted with .innerHTML has some more infos for you.

Create own numpad with inputs

I've been searching the web for some tips regarding how to make your own numpad, created with html code, to act as a numpad would on the computer.
I have this numpad on my website that would give an input to a textfield in the same div. I've given a value to each button and now I guess I would have to create something more so that the numbers will add to my text field.
I'm really a beginner with programming so maybe this is really easy. Thanks for the help!
You could do it, alternatively, with jQuery. jQuery is better IMHO if you need a simple easy solution (jQuery is generally easier and faster).
HTML:
<div id="myDiv"> </div> //the div to which we add text
<div id="buttonContainer"> //this is the div containing the numbers (the numpad)
<button value="one"> one </button>
<button value="two"> two </button>
</div>
jQuery:
$("#buttonContainer button").click(function() {
$("#myDiv").append($(this).val());
});
http://jsfiddle.net/DLzUU/1/
What this does is: when you click any button inside the div with id of 'buttonContainer', it adds its value to the div with the id of "myDiv".
On the Javascript subject, if you want a VERY good guide: http://javascript.info/
what you need is to learn javascript. With javascript you will be able to write code to do this.
<script>
function AddValueToTextField(val)
{
document.getElementByID( <textfiled ID> ).value += val;
}
</script>
<button onClick="AddValueToTextField(this.value)"></button>
this is only very basic but it is a rough idea of what is needed, the button is set to call the function "AddValueToTextField" when it is clicked. When the function is called the value of the button is sent along with it. Inside the function it gets a handle on the textfield and adds the value of the button to whatever was already there, I'd suggest looking at:
http://www.w3schools.com/js/
as a place to start learning javascript.
you can try http://keith-wood.name/keypad.htmlkeypad example, this is an awesome example
$(document).ready(function(){
var selected;
$(".admin_loginid input").focus(function(){
selected = $(this);
});
$(".loginbtn").click(function(){
selected.val(selected.val() + $(this).val());
});
});
Solved it that way and it works really well, thanks for the help! Now my selected input box takes the input from the numpad that i've created.

Making on onClick to change text in javascript

I want to make a format like the following:
Phrase
[Button]
When the button is clicked, the 'phrase' changes and the button remains. I am able to make it so text appears, however I can not make it so the button stays. Does anyone have an idea of how this may be done? Thanks.
Final script
Javascript (replacement)
function displayPhrase()
{
document.getElementById("demo").innerHTML = 'New Phrase';
}
HTML (Old phrase)
<span id="demo">Old Phrase</span>
HTML (The button)
<button type="button" onclick="displayPhrase()"></button>
Credit to above answers ^_^
Take a look at this.
I am able to make it so text appears, however I can not make it so the button stays.
My guess is you are updating the element that also contained the button element, and this update is clearing the button.
HTML
<span id="phrase"></span>
<button id="change-phrase" type="button">Change Phrase</button>
JavaScript
var button = document.getElementById('change-phrase'),
content = document.getElementById('phrase');
button.onclick = function() {
content.innerHTML = 'Your new phrase';
};
jsFiddle.
Use this code:
HTML:
<h1> Welcome to the </h2><span id="future-clicked"></span>
<button onclick="clicked_on()">Click for future</button>
JS:
<script>
function clicked_on(){
document.getElementById('future-clicked').innerHTML = 'Future World';
}
</script>

Categories