Adding an Image to DOM Dynamically Using Range.insertNode() - javascript

How can I dynamically insert an IMG element into the DOM using Range.insertNode() ?
My HTML:
<div class="css_class_for_div" style="height: 250px;" contenteditable="true">
<img src="/path/to/my/image/myimage.png" alt="/myimage.png" title="/myimage.png" class="css_class_for_image" e_resid="/myimage.png" />
<br />
<br />
<span class="css_class_for_span"></span>
</div>
<input id="myButton" type="button" value="insert image" />
MY JS:
var button = document.getElementById("myButton");
button.addEventListener("click", function(e){
var src = "/path/to/my/other/image/image2.png";
var title = "/image2.png";
var cssClassname = "css_class_for_image";
var list = document.getElementsByClassName("css_class_for_div");
var el = list[0];
var selRanges = el.getSelection();
if (selRanges.rangeCount > 0) {
var curRange = selRanges.getRangeAt(0); // Range object
if (curRange.toString().length == 0) {
var imageNode = document.createElement('img');
imageNode.src = src;
imageNode.alt = title;
imageNode.title = title;
imageNode.className = cssClassname;
curRange.insertNode(imageNode);
}
}
},false);
[Link to fiddle]
The above code doesn't work. Any help is appreciated.

If you simply want to insert Image2 into the first occurrence of a div with classname = css_class_for_div using Range.InsertNode(), you can use the following code.
I had to use
var range = document.createRange();
range.selectNode(your div);
range.insertNode(your image);
Updated Fiddle
var button = document.getElementById("myButton");
button.addEventListener("click", function (e) {
debugger;
var range = document.createRange();
var list = document.getElementsByClassName("css_class_for_div");
if (list.length > 0) {
var el = list[0];
range.selectNode(el);
var imageNode = getImageNode();
range.insertNode(imageNode);
}
}, false);
function getImageNode() {
var src = "/path/to/my/other/image/image2.png";
var title = "/image2.png";
var cssClassname = "css_class_for_image";
var imageNode = document.createElement('img');
imageNode.src = src;
imageNode.alt = title;
imageNode.title = title;
imageNode.className = cssClassname;
return imageNode;
}

Related

How to add onclick function with javascript append?

The onclick handler function closeTab() doesn't work on appended elements.
HTML:
<li id="listid" class="first-tab">
<img class="cmd-icon" id="cmdicon" src="resources/img/cmd.png">
<a id="atext">Mozilla Firefox</a>
<img onclick="closeTab()" id="deleteTab" class="deleteicon" src="resources/img/delete-icon.svg">
<img onclick="addTab()" id="addTab" class="addplus" src="resources/img/add.svg">
</li>
JavaScript:
function closeTab() {
var whereTab = document.getElementById('listid');
if (whereTab.style.display == 'block') {
whereTab.style.display = 'none';
} else {
whereTab.style.display = "none";
}
}
function addTab() {
var img = document.createElement("img");
img.src = "resources/img/delete-icon.svg";
var img2 = document.createElement("img");
img2.src = "resources/img/cmd.png";
img.className = 'deleteicon';
img.id = "deletetab";
img.onclick = closeTab();
var ulLocation = document.getElementsByClassName('abc')[0];
var whereTab = document.getElementById('listid');
var addTab = document.createElement('li');
addTab.className = 'first-tab';
addTab.id = "listid";
addTab.className = 'active';
addTab.innerHTML = "mozilla-firefox/newtab";
addTab.appendChild(img2);
ulLocation.appendChild(addTab);
addTab.appendChild(img);
}
Why doesn't the closeTab() function work on appended items via addTab()?
Instead of img.onclick = closeTab();, you need img.onclick = closeTab;- you need to assign the function not execution.

Element not being created and inserted with values

var input = document.getElementById("input").value;
var split1 = input.split(";");
var split2 = input.split(":");
var canvas = document.getElementById("canvas");
if (split2[0] === "draw") {
var thing = document.createElement("div");
thing.style.backgroundColor = split2[1];
thing.style.height = split2[2];
thing.style.width = split2[3];
thing.appendChild(canvas);
}
So I am trying to have an element created with custom values in an input box, why is it that everything is defined, but it does not work? this is what I type in (the input box value): "word(colon)lol(colon)red(colon)sans-serif"
I made some changes with your code and added a test for it, you can run :
"draw:red:100:200" - and check what you need .
You can see I changed the line :
canvas.appendChild(thing);
because you want to append to "canvas" , you tried to add the canvas to the new element you created right before.
<input type="text" id="input">
<script>
function testClick() {
const input = document.getElementById("input").value;
const split2 = input.split(":");
const canvas = document.getElementById("canvas");
if (split2[0] === "draw") {
var thing = document.createElement("div");
thing.style.backgroundColor = split2[1];
thing.style.height = `${split2[2]}px`;
thing.style.width = `${split2[3]}px`;
canvas.appendChild(thing);
}
}
</script>
<button onclick="testClick()">test</button>
<div id="canvas"></div>
stackblitz : https://js-lwpolg.stackblitz.io
Working example:
var input = document.getElementById("input").value;
var split2 = input.split(":");
var canvas = document.getElementById("canvas");
if (split2[0] === "draw") {
var thing = document.createElement("div");
//var textnode = document.createTextNode("xxx");
//thing.appendChild(textnode);
thing.style.backgroundColor = split2[1];
thing.style.height = split2[2];
thing.style.width = split2[3];
canvas.append(thing); //canvas.appendChild(thing)
}
<input id='input' value='draw:red:15px:30px'>
<div id='canvas'></div>

Using local storage to save image in javascript

Check my JS Fiddle: https://jsfiddle.net/oxfre6kj/1/
I have a button that creates as many images as you want, but when I refresh the page those images are gone, I want them to be still there after I click the save button.
Here is what I tried it works with variable but it doesn't work with "img"
<button onclick="createImage()">Create Image</button>
<button onclick="saveImages()">Save Images</button>
<div id="image"></div>
<script>
function createImage() {
var img = document.createElement('img');
img.src = 'http://via.placeholder.com/350x150';
document.getElementById('image').appendChild(img);
}
var image = localStorage.getItem('image');
alert(image);
function saveImage() {
localStorage.setItem("images", image);
}
</script>
is this how you want the page to work ?
HTML :
<button id="create_image">Create Image</button>
<button onclick="saveImages()">Save Images</button>
<label for="image_url">Image url :</label>
<input type="text" id="image_url" value="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded" placeholder="img url">
<div id="images"></div>
JAVASCRIPT :
document.getElementById("create_image").addEventListener("click", function() {
const url = document.getElementById("image_url").value;
createImage(url);
});
var images = localStorage.getItem('image');
loadImagesFromLocal();
function createImage(src) {
var img = document.createElement('img');
img.src = src;
img.onload = function() {
document.getElementById('images').appendChild(img);
}
}
function saveImages(img) {
const images = document.querySelectorAll(`div#images img`);
var savedImagesSrc = JSON.parse(localStorage.getItem("images")) || [];
savedImagesSrc = Array.from(savedImagesSrc);
for (var i = savedImagesSrc.length; i < images.length; i++) {
savedImagesSrc.push(images[i].src);
}
localStorage.setItem("images", JSON.stringify(savedImagesSrc));
}
function loadImagesFromLocal() {
const savedImagesSrc = JSON.parse(localStorage.getItem("images")) || [];
for (var i = 0; i < savedImagesSrc.length; i++) {
createImage(savedImagesSrc[i]);
}
}

Creating dynamic div using javascript

<script>
function selecteditems()
{
var i=1;
var val="";
while(i<=53)
{
if(document.getElementById('timedrpact'+i)!="")
{
val+=document.getElementById('timedrpact'+i).value;
document.getElementById('showselecteditems').innerHTML=val;
}
i++;
}
}
</script>
How to create a new div and add contents to it?In the above case i lost previous content due to innerHTML.I want new div each time for dynamically attach an image and the above variable val to it.
Thanks in advance.
Check this Demo
<div id="output" class="out">
</div>
window.onload=function(){
var output = document.getElementById('output');
var i=1;
var val="";
while(i<=3)
{
if(!document.getElementById('timedrpact'+i))
{
var ele = document.createElement("div");
ele.setAttribute("id","timedrpact"+i);
ele.setAttribute("class","inner");
ele.innerHTML="hi "+i;
output.appendChild(ele);
}
i++;
}
};
Look at document.createElement() and element.appendChild().
var newdiv = document.createElement("div");
newdiv.innerHTML = val;
document.getElementById("showselecteditems").appendChild(newdiv);
Because you will likely encounter this in the near future: You can remove any element with this code:
element.parentNode.removeChild(element);
Using createElement:
function selecteditems() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=53;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(fld.value));
container.appendChild(div);
}
}
}
Full version using cloneNode (faster) and eventBubbling
Live Demo
var div = document.createElement("div");
var lnk = document.createElement("a");
var img = document.createElement("img")
img.className="remove";
img.src = "https://uperform.sc.gov/ucontent/e14c3ba6e4e34d5e95953e6d16c30352_en-US/wi/xhtml/static/noteicon_7.png";
lnk.appendChild(img);
div.appendChild(lnk);
function getInputs() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=5;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var newDiv = div.cloneNode(true);
newDiv.getElementsByTagName("a")[0].appendChild(document.createTextNode(fld.value));
container.appendChild(newDiv);
}
}
}
window.onload=function() {
document.getElementById('showselecteditems').onclick = function(e) {
e=e||event;
var target = e.target||e.srcElement;
// target is the element that has been clicked
if (target && target.className=='remove') {
parentDiv = target.parentNode.parentNode;
parentDiv.parentNode.removeChild(parentDiv);
return false; // stop event from bubbling elsewhere
}
}
getInputs();
}
Syntax for dynamic create div:
DivId = document.createElement('div');
DivId.innerHtml ="text"

Change textarea into <li> element when done editing

I have the following code:
var counter=0;
function appendText(){
var text = $("#text").val();
if ( $("#text").val() ){
var textArea = "<div class='divex'> <textarea id='t"+counter+"'>"+text+"</textarea><button id='b"+
counter+"'name='t"+counter+"' >edit</button> <button onClick='moveUp()' id='updiv'>Up:></button></div>";
$("#text").val();
$("#addedText").after(textArea);
$("#t"+counter).clear;
$("#t"+counter).attr('readonly','readonly');
$("#b"+counter).bind('click',makeAreaEditable);
$("#text").val('');
counter++;
}
else{
}
};
var makeAreaEditable = function()
{
var target = event.target || event.srcElement || event.originalTarget;
var button = $("#"+target.id);
button.text("OK");
button.unbind('click');
button.bind('click',saveEdit);
var targetArea = $("#"+target.name);
targetArea.removeAttr('readonly');
};
var saveEdit = function()
{
var target = event.target || event.srcElement || event.originalTarget;
var button = $("#"+target.id);
button.text("edit");
button.unbind('click');
button.bind('click',makeAreaEditable);
var targetArea = $("#"+target.name);
targetArea.attr('readonly','readonly');
};
The html looks like this:
Add text
<div id="addedText" style="float:left">
</div>
I want to change this script so that : when i click the add text button - the text will be added as an li element when i click ok it will bring the textarea and at save back to li. Thanks!
I've done it! here is the final code:
var makeAreaEditable = function()
{
var liid = $(this).parent().find('li').attr('id');
var text = $("#"+liid).html();
var target = event.target || event.srcElement || event.originalTarget;
var button = $("#"+target.id);
button.text("OK");
button.unbind('click');
button.bind('click',saveEdit);
var targetArea = $("#"+target.name);
targetArea.replaceWith('<textarea>'+text+'</textarea>');
};
var saveEdit = function()
{
var target = event.target || event.srcElement || event.originalTarget;
var button = $("#"+target.id);
var textarea = $(this).parent().find('textarea');
var text = textarea.val();
button.text("edit");
button.unbind('click');
var targetArea = button.parent().find('textarea');
var textid = target.name;
targetArea.replaceWith("<li id='"+textid+"' style='list-style-type:none;'>"+text+"</li>");
};

Categories

Resources