I'm building my own WYSIWYG editor, using an iframe, I'd like to find just a way to simply insert an image! I already got the Bold style, Italic style, H1 and H2, using JS:
function bold(){
editor.document.execCommand("bold", false, null)
}
function italic(){
editor.document.execCommand("italic", false, null)
}
function h1(){
editor.document.execCommand('formatBlock',false,'h1');
}
function h2(){
editor.document.execCommand('formatBlock',false,'h2');
}
That works very well but I'm struggling with "Insert image button" Since I'm really new with coding, I was trying this:
function image(){
var image = prompt ("Paste or type a link", "http://")
editor.document.execCommand("createImage", false, image)
But that doesn't work. My intention is that the users have the possibility to upload images from their computer and/or from internet. Please, if anyone knows how to insert an image... help!
A LOT OF THANKS IN ADVANCE!
Have you tried formatting your image location using a relative link where the @ symbol precedes the image location. Your code and explanation also doesn't explain are they uploading the image from their machine in a location like My Documents or if they are uploading the image strictly from and http link.
To upload from a local machine using Javascript and HTML, you might checkout this code. Your question is one that regularly comes up when writing custom Javascript functions.
<script type='text/javascript'>
function main()
{
var inputFileToLoad = document.createElement("input");
inputFileToLoad.type = "file";
inputFileToLoad.id = "inputFileToLoad";
document.body.appendChild(inputFileToLoad);
var buttonLoadFile = document.createElement("button");
buttonLoadFile.onclick = loadImageFileAsURL;
buttonLoadFile.textContent = "Load Selected File";
document.body.appendChild(buttonLoadFile);
}
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
imageLoaded.src = fileLoadedEvent.target.result;
document.body.appendChild(imageLoaded);
};
fileReader.readAsDataURL(fileToLoad);
}
}
}
main();
</script>
You can check out the full article on this issue of image uploads using Javascript and HTML 5 here: https://thiscouldbebetter.wordpress.com/2012/12/20/uploading-and-displaying-an-image-from-a-file-using-html5-and-javascript/