Replace instead of append based on user input? - javascript

This function currently works for appending an img in a div. But I need a replace method instead of multiple img divs stacking on top of each other.
I'm open to solutions in jQuery as well.
function getImg(){
var url=document.getElementById('txt').value;
var div=document.createElement('div');
var img=document.createElement('img');
img.className="img-responsive";
img.src=url;
div.appendChild(img);
document.getElementById('gif-btn').innerHTML=""; <!-- Correct answer -->
document.getElementById('gif-btn').appendChild(div);
return false;
}
Thanks in advance for any and all help. Much appreciated!

Before you append, you can clear out the div, then append the new one
function getImg(){
var url=document.getElementById('txt').value;
var div=document.createElement('div');
var img=document.createElement('img');
img.className="img-responsive";
img.src=url;
div.appendChild(img);
document.getElementById('gif-btn').innerHTML = ""; // <-- Clears the gif-btn div
document.getElementById('gif-btn').appendChild(div);
return false;
}

Using jQuery
var url = $("#txt").val();
var image = $("<img>").attr("src", url).addClass("img-responsive");
var container = $("<div></div>");
// add the image to the <div> container
container.append(image);
// set the contents of gif-btn
$("#gif-btn").html(container);
... or better yet, you could do a simple fade-out, fade-in...
// replace the last line with this
$("#gif-btn").fadeOut("fast", function() {
$("#gif-btn").html(container); $("#gif-btn").fadeIn();
});

Related

Using class instead of id in JS to do an action

First, sorry I'm not good with javascript.
HTML:
<div id="Comment-ID">
<p class="comment-content">...</p>
</div>
The javascript: (Edit: Added the whole code)
<script type='text/javascript'>
function autoloadmore() {
var loadmoreClass = document.getElementsByClassName("loadmore")[0];
var loadmoreChild = loadmoreClass.querySelector('a')
if (loadmoreClass) {
loadmoreChild.click();
}
}
//<![CDATA[
function InsertarImagenVideo(id) {
var IDelemento = document.getElementById(id),
sustituir = IDelemento.innerHTML;
sustituir = sustituir.replace(/\[img\](.[^\]]*)\[\/img\]/ig, "<img class='img-comentarios' src='$1'\/>");
document.getElementById(id).innerHTML = sustituir;
}
//]]>
window.onload = function() {
autoloadmore();
setTimeout(function(){
InsertarImagenVideo('Comment-ID');
},3000);
};
</script>
"InsertarImagenVideo" replaces some text inside with an image. Instead of using it on "Comment-ID", I want to use it on "Comment-class".
Note: I can't edit the HTML.
I couldn't find anything when I searched, or maybe I didn't know how to look. Can someone help me with this?
You can use document.querySelector to select an element by class:
Update this line:
var IDelemento = document.getElementById(id),
to var IDelemento = document.querySelector(id),
and pass the class selector to your method InsertarImagenVideo
setTimeout(function(){
InsertarImagenVideo('.comment-content');
},3000);
I found a simple way to insert an image into the <p class="comment-content">...</p> element by grabbing the parent <div id="Comment-ID">.
I'm assuming that you need to grab the unique id to then access the inner <p> element to replace the existing text with an image. This code grabs the unique id element, then grabs the first <p> tag using .getElementsByTagName('p')[0]. One thing I did add is a proper image load script to update the <p> tag with the image once it has been loaded (maybe this removes the need for that setTimeout function you have?).
let classElement = document.getElementById("Comment-ID").getElementsByTagName('p')[0];
let imageObject = new Image();
imageObject.src = `https://www.clipartmax.com/png/full/1-14442_smiley-face-png-smiley-png.png`;
imageObject.onload = function() {
classElement.innerHTML = `<img id="myImg" src="${imageObject.src}" />`;
let imageElement = document.getElementById(`myImg`);
imageElement.width = 100;
imageElement.height = 100;
};
Here's a JSFiddle demo of the upper code in action.
Hope this helps :)

Remove innerHTML img completely by jQuery selection

I've dinamically created a div with the code below:
typebox.innerHTML += "<div id='idtypebox' class='typebox'><img id='typeImg' width='30px' height='30px' src="+d[o].src+"></div>";
My intention is to remove completely the innerHTML I created, by changing the innerHTML that had created the img and if change the form A to B, those images will be removed.
function SelectCheck() {
var select_val = $('#Check').val();
// using this to remove typeimg
var toRemove = document.getElementById('typeImg');
toRemove.parentNode.removeChild(toRemove);
if (select_val) {
ajax_json_gallery("Img/"+select_val);
}
return;
}
$(document).ready(function() {
$("#Check").change(SelectCheck).change();
});
I tried this code by on button and it works, but if I put in jQuery selection I get an error
var toRemove = document.getElementById('typeImg');
toRemove.parentNode.removeChild(toRemove);
Why not just :
$("#typeImg").remove();
And the complete code :
function SelectCheck(){
var select_val = $('#Check').val();
// using this to remove typeimg
$("#typeImg").remove();
if(select_val){
ajax_json_gallery("Img/"+select_val);
}
return;
}
jQuery(document).ready(function($) {
myVar=$("#d1 [href]").html();
var href = $(myVar).attr('src');
$("#d1").html('');
$("#d1").html('<img src="'+href+'" class="images_responsive_mode">').removeAttr("href");
});
</script>
this is one of the script which i created for remove the class assigned by wordpress and to assign new class for responsive image , if it useful for you do this !
you can use childNodes to remove the innerHtml
var toRemove = document.getElementById('typeImg');
toRemove.parentNode.removeChild(toRemove.childNodes[0])

How do i clear text out of a div using javascript

Okay here is what i have:
<script type="text/javascript">
var where = document.getElementById("info")
var texts = false;
function clear() {
where.innerHTML = "";
};
function dostuff(what) {
if(where.style.value === ""){
var comm = document.createTextNode(what);
where.appendChild(comm);
}else {
clear();
}
};
</script>
the id "info" is a div
this is basically a vertical navigation bar that shows tooltips in a div under the buttons when you hover over them.
So I want to first check if the div has no value then if it doesn't then it will append text into it, else it will clear the text but i also want it to append the text after it clears. I'm not sure how to do this and help would be appreciated. thanks
Since you want to clear the item anyways and put your new text in, why even bothering with the conditional? You could just as easily do:
function dostuff(what) {
where.innerHTML = what;
};
Working example

Append Ajax to an element using createDocumentFragment(); instead of create Element

This post was the most helpfull to understand createDocumentFragment() instead of createElement()
Should I use document.createDocumentFragment or document.createElement
I've understood that for performance reason using fragment will help on big dataset so i want to conver my function.
This is what i use right now and it works as desired => Get content from a php file with ajax and then append this content at the top of existing div#wrapperinside a new div.feedBox(r being the XMLHTTP /ACTIVE OBJECT)
r.onreadystatechange=function(){
if(r.readyState==4 && r.status==200){
//Want to convert this to createDocumentFrangment --START
var n = document.createElement("div");
n.className = "feedBox";
n.innerHTML = r.responseText;
document.getElementById("wrapper").insertBefore(n, document.getElementById("wrapper").firstChild);
//Want to convert this to createDocumentFrangment --END
}
}
This is what i tried, but what happens is the content is added but without the div.feedBox
var n = document.createElement("div");
n.className = "feedBox";
n.innerHTML = r.responseText;
var f = document.createDocumentFragment();
while (n.firstChild) { f.appendChild(n.firstChild); }
document.getElementById("wrapper").insertBefore(f, document.getElementById("wrapper").firstChild);
What did i miss? can you explain why and how to make it work?
Is this really a more efficient way of doing this?
PS: NO jquery please. I know it well and i use it widely on other project but i want this to be as small / lite / efficient as possible.
Shouldn't this line
while (n.firstChild) { f.appendChild(n.firstChild);
be
f.appendChild(n);
Also I see that you are not appending the div.feedBox to your DOM anywhere..
What happens if the while condition fails.. You are not appending anything to your DOM..
I am assuming this will work .. Not tested though
f.appendChild(n)
document.getElementById("wrapper").appendChild(f,
document.getElementById("wrapper").firstChild);
ALso better to use
.appendChild(f, instead of .insertBefore(f,
Check Fiddle
This is the full working function, any1 sould feel free to use it:
function ajax_fragment(php_file){
if (window.XMLHttpRequest){
r=new XMLHttpRequest();
} else{
r=new ActiveXObject("Microsoft.XMLHTTP");
}
r.onreadystatechange=function(){
if(r.readyState==4 && r.status==200){
var n = document.createElement("div"); //Create a div to hold the content
n.className = "feedBox"; //Give a class 'feddBox' to the div
n.innerHTML = r.responseText; //Put the response in the div
var f = document.createDocumentFragment(); //Create the fragment
f.appendChild(n); //Add the div to the fragment
//Append the fragment's content to the TOP of wrapper div.
document.getElementById("wrapper").insertBefore(f, document.getElementById("wrapper").firstChild);
}
}
r.open("GET",php_file,true);
r.send();
}

get dynamic text in text area on every click on div

I want to open the CKEDITOR on click-event of div, and want the div contents in that textarea of ckeditor
but somehow this is not working.
Thanks in advance, and sorry for my poor english
function createEditor() {
$('DIV').click(function(event) {
var id1 = event.target.id;
//alert(id1);
document.getElementById("editor1").value = '';
var newtext = document.getElementById(id1).innerHTML;
alert(newtext);
document.getElementById("editor1").value += newtext;
});
document.getElementById("contents").style.display = "block";
}
Remove createEditor() function and try it
$('DIV').click(function(event) {
var id1 = event.target.id;
//alert(id1);
document.getElementById("editor1").value = '';
var newtext = document.getElementById(id1).innerHTML;
alert(newtext);
document.getElementById("editor1").value += newtext;
});
document.getElementById("contents").style.display = "block";
Try this to add data to the textarea.
$("#editor1").val(newtext);
or use
$('#editor1').append(newtext);
This solution will rely more on jQuery. First, if you want this function to be triggered when ever a div is clicked, get rid of your function(), it's not necessary since your event will be triggered every time a div is clicked.
This should solve your problems:
$('div').click(function(e) {
$id1 = $(this).attr("id");
alert($id1);
$("#editor1").val(' '); //Are you sure you want to empty your textarea?
$newtext = $("#"+$id1).html();
alert($newtext);
$("#editor1").val($newtext); //Because when you append the newtext it won't append but replace the text it's already on this.
$("#contents").css("display","block");
});
Here's a fiddle with a similar example of using your function:
If you just want the text of the clicked div and you're using jQuery try
$("div").click( function() {
var newtext = $(this).text();
$("#editor1").text( newtext );
});

Categories