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.
Related
I have a report authoring tool that lets me add descriptive text in the report header, prior to a table containing the data. The examples included with the tool show how include Javascript in the description for various special effects. I would like to change certain cells in the table into links to other reports. Here's the HTML produced by the reporting tool.
<div class="element-info">
<div class="description">My Description</div>
<div class="properties">
<table>...</table>
</div>
</div>
I have tried replacing "My Description" with the following, but (perhaps unsurprisingly) it's changing something other than the table.
<div>My Description
<script type="text/javascript">
// currentScript is supported in my version of Firefox.
var me = document.currentScript;
// go up two levels to get the enclosing div
var element_info = me.parentElement.parentElement;
// from there we want the properties div, then the table
var mytable = element_info.lastChild.firstChild;
mytable.style.color = "red";
</script>
</div>
I expect that the problem is that when the script runs, the HTML in the following div has not yet been parsed. Mozilla says that the defer attribute will be ignored in scripts without a src= attribute, and I've verified that it does nothing.
Although my example code is using plain Javascript, the authoring tool is based on jQuery, so it's full repertoire is available if needed.
If the problem involves the fact that the html hasn't yet been parsed, you can immediately gain a reference to the script, but only later utilize it, once the document is loaded. It would look like this:
<div>My Description
<script type="text/javascript">
// Get the reference immediately...
var script_of_interest = document.currentScript;
// And only use it once everything is loaded:
window.onload = function() {
var element_info = script_of_interest.parentElement.parentElement;
var mytable = element_info.lastChild.firstChild;
mytable.style.color = "red";
};
</script>
</div>
Make sure your the node your script operates on is loaded before the execution, otherwise your the node may be undefined or just nothing. You may try wrap your code with
$(document).ready(function(){
//your code
}).
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>
I am sure this is a simple question.
To begin really playing with javascript and understand it I need to have the environment to see what my output is. I have done lessons in javascript but need to actually get the HTML and javascript talking.
What I am looking to do:
Have a user input information into an text box and have it show the result in the html.
is the sky blue? Yes (makes true be displayed on my HTML)
is the sky blue? No (makes false be displayed in my HTML)
currently i have no idea if my javascript is doing anything!
Here is my code:
HTML:
<form action="" onsubmit="return checkscript()">
<input type="text" name="value">
<input type="submit" value="Submit">
Javascript:
function checkscript() {
for (i=0;i<4;i++) {
box = document.example.elements[i];
if (!box.value) {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
return false;
}
}
return true;
}
document.write(box);
I am so confused but need to see the results of what i am doing to see where to fix things, i tried using console in chromes inspect elements function but this has confused me more.
Can someone help and clean the code up to make sense by labelling everything as what they do?
box? check script?
Thanks :)
I updated the jsfiddle I had made for you. It's a working version that might get you started.
HTML
<!-- I avoided all the mess of forms, since that submits to a server, and that's more than you want right now. Note that I added ids to each input. Ids make it very easy to access the elements later. -->
<input type="text" name="value" id="fillIn">
<input type="button" value="Submit" id="button">
JS
// My methodology here is totally different, since I directly get the element I care about
function checkscript() {
// find the element in the DOM
var box = document.getElementById("fillIn");
// check for a value
if (box.value) {
// if there is one, add a new div. That's probably not what you'll want in the long run, but it gives you something to work with (and seems to match your old idea of using document.write. I have never yet used document.write, though others with more experience than I may like the concept better.
// This creates a new element. If you press F12 and look at this in your debugger, you'll see it actually appear in the HTML once it's appended
var newElement = document.createElement("div");
// Set the value to what you want
newElement.innerHTML = box.value;
document.body.appendChild(newElement);
} else {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
// No returns necessary, since we're not dealing with formsubmittal.
}
}
// This hooks up the function we just wrote to the click event of the button.
document.getElementById("button").onclick = checkscript;
This may or may not be what you want, but it's at least a place to get started.
A few things to start out:
1.) Make sure all elements have end tags
<input type="text" name="value" />
Note backslash at end of tag.
2.) You are using a form tag, which submits a form to a server side component.
Suggest you need to use the onclick event. Which is available on all input controls. Suggest you start with buttons so:
<input type="text" name="value" onclick="myFunction()" />
<script type="text/javascript">
function myFunction() {
document.write("Hello");
console.log("Hello");
}
</script>
Writes stuff directly to the html and console. Hope that gets you started.
Regards,
Andy
I'm just started to learn HTML. Doing an alert() on one of my variables gives me this result [object HTMLInputElement].
How to get the data, that were added in text field, where my input type is text?
Say your variable is myNode, you can do myNode.value to retrieve the value of input elements.
Chrome Developer Tools has a Properties tab which shows useful DOM attributes.
Also see MDN for a reference.
If the element is an <input type="text">, you should query the value attribute:
alert(element.value);
See an example in this jsFiddle.
Also, and seeing you're starting to learn HTML, you might consider using console.log() instead of alert() for debugging purposes. It doesn't interrupt the execution flow of the script, and you can have a general view of all logs in almost every browser with developer tools (except that one, obviously).
And of course, you could consider using a web development tool like Firebug, for instance, which is a powerful addon for Firefox that provides a lot of functionalities (debugging javascript code, DOM inspector, real-time DOM/CSS changes, request monitoring ...)
It's not because you are using alert, it will happen when use document.write() too. This problem generally arises when you name your id or class of any tag as same as any variable which you are using in you javascript code. Try by changing either the javascript variable name or by changing your tag's id/class name.
My code example:
bank.html
<!doctype html>
<html>
<head>
<title>Transaction Tracker</title>
<script src="bank.js"></script>
</head>
<body>
<div><button onclick="bitch()">Press me!</button></div>
</body>
</html>
Javascript code:
bank.js
function bitch(){ amt = 0;
var a = Math.random(); ran = Math.floor(a * 100);
return ran; }
function all(){
amt = amt + bitch(); document.write(amt + "
"); } setInterval(all,2000);
you can have a look and understand the concept from my code. Here i have used a variable named 'amt' in JS. You just try to run my code. It will work fine but as you put an [id="amt"](without square brackets) (which is a variable name in JS code )for div tag in body of html you will see the same error that you are talking about.
So simple solution is to change either the variable name or the id or class name.
change:
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
to
$("input:text").change(function() {
var value=$("input[type=text].selector").val();
alert(value);
});
note: selector:id,class..
<input type="text" id="name">
and in javascript
var nameVar = document.getElementById("name").value;
alert(nameVar);
<input type="text" />
<script>
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
</script>
use .val() to get value of the element (jquery method), $("input:text") this selector to select your input, .change() to bind an event handler to the "change" JavaScript event.
When you get a value from client make and that a value for example.
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200 ){
var response = http.responseText;
document.getElementById('server_response').value = response;
console.log(response.value);
}
I want to get text from Nested SPAN element in Following HTML code:
<span id='result_box'>
<span class="hps">text_content</span>
</span>
I want to get "text_content" value using JavaScript.
I have tried this but have a problem:
var resBox=document.getElementById('result_box');
var strTrans=resBox.getElementsByTagName('span')[0].innerHTML;
alert(strTrans);
EDIT: Actually i want to do this from Online Page
your code works fine. i guess your problem is you are executing these code when DOM not loaded completely.if you are testing something, you can try this.
window.onload = function () {
//put your code here,it will alert when page loaded completely.
};
or put the script after your span element. like this.
<span id='result_box'>
<span class="hps">text_content</span>
</span>
<script type='text/javascript'>
var resBox=document.getElementById('result_box');
var strTrans=resBox.getElementsByTagName('span')[0].innerHTML;
alert(strTrans);// it will alert
</script>
you get the element by classname.. document.getElementsByClassName() and then grabbing the first item off the resulting node list
window.onload = function () {
document.getElementsByClassName("hps")[0].innerHTML
};
jsfiddle
var resBox=document.getElementById('result_box');
var strTrans=document.getElementsByTagName('span')[0].innerText;
alert(strTrans);
or better
strTrans = document.querySelector(".hps").innerText ;
got you, i guess you embed a link in your html page,then you wanna manipulate DOM in the page you embed,right? if so, you can check browser same origin policy.
if you wanna implement online translation via google, you can google 'google translate api', google provides a api to others for implementing online translation in their own applications.
it seems like bing also provides a api.i'm not sure.