Replacing texts with emoticons in JavaScript from Json values - javascript

I am trying to replace text with images.For example, abc:) should be converted into abc(and the respective emoticon).And I am using contenteditable element for doing the same.But, nothing seems to work.I tried using the replace() and html() functions but they don't work.
The link to my Codepen is: Link
And I don't want to use regex as I have to do more additions in my json file.Thanks!
HTML Code:
<div contenteditable="true" id='text-box'>
</div>
JS Code:
document.body.onkeyup=function(e){
if(e.keyCode==32){
var contenteditable = document.querySelector('[contenteditable]'),
text = contenteditable.textContent;
var word=getWord(text);
console.log(word);
console.log(data.value);
if(word.includes(data.value)){
//alert("true");
var img=new Image();
img.src=data.image;
img.setAttribute("class","image");
//$("#text-box").append(img);
$("#text-box").html(function (_, html) {
return html.replace(data.value , img );
}
//$("#text-box").html(text.replace(data.value,img));
}
}
function getWord(text){
var word=text.split(" ").pop();
return word;
}
JSON data:
var data={
"value":":)",
"image":"persons-0016_large.png"
};
After the execution of my code,I get the output as abc[object HTMLImageElement] instead of the image itself.

Instead of creating an image object, replace the text by image tag like this.
var data={
"value":":)",
"image":"persons-0016_large.png"
};
document.body.onkeyup=function(e){
if(e.keyCode==32){
var contenteditable = document.querySelector('[contenteditable]');
var text = contenteditable.textContent;
var word=getWord(text);
console.log(word);
console.log(data.value);
if(word.includes(data.value)){
//alert("true");
//var img=new Image();
//img.src=data.image;
//img.setAttribute("class","image");
var img = "<img src='" + img.src +"' class='image' /> ";
//$("#text-box").append(img);
$("#text-box").html(function (_, html) {
return html.replace(data.value , img );
} );
//$("#text-box").html(text.replace(data.value,img));
}
};
};
function getWord(text){
var word=text.split(" ").pop();
return word;
}

Related

HTML Change Within Jquery Textarea Value

I want to extract html codes from a textarea value but failed.
I want to detect and replace images with textarea value.
Below is an example of what I want to do.
TEXTAREA
<textarea class="editor"><img src="x1"><img src="x2"></textarea>
The code below is an example of what I want to do, I know it's wrong.
var editor_images = $('.editor').val().find('img');
editor_images.each(function(key, value) {
$(this).attr('src','example');
});
If you want to replace multiple attributes or tags, then your question may be too broad. However, the example below gives you an idea of how to replace an image attribute within the textarea:
function replaceValueOfTextArea(searchAttr, replaceAttr, value) {
const editor = document.querySelector('.editor');
const imgs = editor.value.match(/<img[a-zA-Z0-9="' ]+>/g);
let textAreaNewValue = '';
for (let img of imgs) {
const regMatch = new RegExp(`(?<!img)${searchAttr}`, "gi");
const match = img.match(regMatch);
if (match) {
const regAttr = new RegExp(`${searchAttr}=["|'][^"|']+["|']`, "gi");
textAreaNewValue += img.replace(regAttr, `${replaceAttr}="${value}"`);
} else {
textAreaNewValue += img;
}
}
editor.value = String(textAreaNewValue);
}
replaceValueOfTextArea('src', 'src', 'https://example.com');
<textarea class="editor"><img src="x1"><img alt="x2"></textarea>
You can use jQuery's $.parseHTML() to parse an HTML string into DOM nodes. Then you can use this method to turn them back into HTML before reinserting them in your <textarea>:
// Get contents of editor as HTML and parse into individual <img> nodes:
let nodes = $.parseHTML( $('.editor').val() )
// Map through <img> nodes and change src attribute, and return as HTML text:
let html = nodes.map(function(node){
$(node).attr('src', 'example')
return $('<div>').append($(node).clone()).html();
})
// Insert HTML text back into editor:
$('.editor').html( html.join('') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="editor"><img src="x1"><img src="x2"></textarea>

Passing image objects as Function & Class Arguments

How do you pass an image as argument in a function/class or is this impossible and if it is how would I fix it? For example:
var tree = new Image();
tree.src = "img/statobj/tree.png"
function additem(dimage){
document.getElementById("myitems").rows[0].insertCell(0).innerHTML ='<div id="invetoryitem" >'+ this.dimage + '</div>'
console.log(dimage) //gets undefined
}
I've tried dimage.src and other methods but nothing I use seems to work :/
Pass it like you would any other, but to display it, use appendChild not innerHTML:
var tree = new Image();
tree.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg/220px-Ash_Tree_-_geograph.org.uk_-_590710.jpg";
function showTree(dimage) {
document.getElementById("div").appendChild(dimage);
console.log(dimage);
}
showTree(tree);
<div id="div"></div>
If you do want to use innerHTML, make an <img> with the src being dimage.src:
var tree = new Image();
tree.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg/220px-Ash_Tree_-_geograph.org.uk_-_590710.jpg";
function showTree(dimage) {
document.getElementById("div").innerHTML = "<img src='" + dimage.src + "'>";
console.log(dimage);
}
showTree(tree);
<div id="div"></div>
You have to name the function and call it by passing the image as an argument. If you are using innerHTML you have to create the image tag and add the source of the image received to the function as argument
var tree = new Image();
tree.src = "img/statobj/tree.png"
function a(dimage){
document.getElementById("myitems").innerHTML ='<div id="invetoryitem" ><img src="'+dimage.src+ '"></div>'
console.log(dimage) //gets undefined
}
a(tree);
<body id="myitems"></body>

Dynamically add <img> tags with via PHP loop, via calling a JavaScript function on each loop

I have a PHP function that loops through image results in a database, formats them with HTML, then returns the variable containing the HTML layout to my page.php. This is all working okay, but in the loop I have some script tags that call a function in my script.js file. It takes two parameters (url and count). I am trying to pass the url of the result from the database to the function, create a new img element, and append the passed url to the src attribute of the newly created img tag.
This appears to be working so far - when I console.log the result, I get a load of <img> tags, all with corresponding src attached to them.
I am having trouble with actually getting these back to the front end, though.
My code below shows the part of the php that gets looped through, followed be the Javascript function it calls on each loop.
public function getResultsHtml($page, $pageSize, $term) {
$fromLimit = ($page - 1) * $pageSize;
$query = $this->con->prepare("SELECT * FROM images
WHERE (title LIKE :term
OR alt LIKE :term) AND broken=0
ORDER BY clicks DESC
LIMIT :fromLimit, :pageSize");
$searchTerm = "%" . $term . "%";
$query->bindParam(":term", $searchTerm);
$query->bindParam(":fromLimit", $fromLimit, PDO::PARAM_INT);
$query->bindParam(":pageSize", $pageSize, PDO::PARAM_INT);
$query->execute();
$resultsHtml = "<div class='image-results'>";
$count = 0;
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$count++;
$id = $row["id"];
$imgUrl = $row["imgUrl"];
$siteUrl = $row["siteUrl"];
$title = $row["title"];
$alt = $row["alt"];
if($title){
$displayText = $title;
} else if ($alt) {
$displayText = $alt;
} else {
$displayText = $imgUrl;
}
$resultsHtml .= "<div class='grid-item image$count'>
<a href='$imgUrl'>
<script>
document.addEventListener('DOMContentLoaded', function() {
loadImage(\"$imgUrl\", \"image$count\");
});
</script>
<span class='details'>$displayText</span>
</a>
</div>";
}
$resultsHtml .= "</div>";
return $resultsHtml;
}
var loadImage = function(src, className){
var image = document.createElement("img");
var aTag = document.querySelectorAll("." + className + " a");
image.onload = function(){
aTag.innerHTML = image;
};
image.onerror = function(){
};
image.setAttribute("src", src);
}
At the moment I'm not geting any results at the front end. In the page source, I can see that inside each anchor tag are script tags, which show the function preloaded with the parameters (loadImage(http://www.com, image22)), but it isn't actually getting a return from the function.
The solution for this with jQuery is below, but I really don't want to use jQuery!
function loadImage(src, className) {
var image = $("<img>");
image.on("load", function() {
$("." + className + " a").append(image);
});
image.on("error", function() {
});
image.attr("src", src);
}
I know that there is some trouble with dynamically writing <script> tags with .innerHTML, but I don't think this is the problem as the script tags are written before the function is called.
I think I have something firing in the wrong order, or I'm missing something that jQuery handles automatically with the .append function.
I have also tried aTag.appendChild(image);, which also gives no results.
I have been using jQuery for a few months, but I am trying to learn Vanilla JS thoroughly - I'm trying to grasp how the jQuery functions actually work, rather than just relying on them blindly.
Any help is massively appreciated!
Beware of that querySelectorAll() returns an array-like NodeList (https://developer.mozilla.org/en-US/docs/Web/API/NodeList), so it should be like this:
(If you only want one element returned user querySelector(), then you don't need the loop)
function loadImage(src, className) {
var image = document.createElement("img");
image.src = src;
image.onload = function() {
var tags = document.querySelectorAll("." + className + " a");
for (var i = 0; i < tags.length; i++) {
tags[i].appendChild(image);
}
}
}
<div class='grid-item image2'>
<a href='https://cdn.pixabay.com/photo/2015/08/21/21/55/star-wars-899693_960_720.jpg'>
<script>
document.addEventListener('DOMContentLoaded', function() { loadImage("https://cdn.pixabay.com/photo/2015/08/21/21/55/star-wars-899693_960_720.jpg", "image2");
});
</script>
<span class='details'>Star Wars 1</span>
</a>
</div>
The problem is that you are using querySelectorAll, which returns a NodeList instead of a single DOM node. This means, you have to iterate over the NodeList and append the image to all the nodes within. For this, you have can either create new copies for each place you want to insert the image, or use cloneNode multiple times.
var each = function (xs, func) {
for (var i = 0; i < xs.length; i += 1) {
func(xs[i]);
}
return xs;
}
var loadImage = function(src, className){
var image = document.createElement("img");
var aTag = document.querySelectorAll("." + className + " a");
image.onload = function(){
each(aTag, function (a) {
a.appendChild(image.cloneNode());
});
};
image.onerror = function(){};
image.alt = '';
image.src = src;
}
loadImage('http://www.fillmurray.com/500/300', 'wrap')
<div class="wrap">
</div>

replace all img tags with alt in div innertHTML

I have this code:
var str = document.getElementById('mesajyazi').innerHTML;
alert('input: '+str);
// first create an element and add the string as its HTML
var container = $('<div>').html(str);
// then use .replaceWith(function()) to modify the HTML structure
container.find('img').replaceWith(function() { return this.alt; })
// finally get the HTML back as string
var strAlt = container.html();
alert('output: '+strAlt);
It doesn't work.
But if I change var str to simple string text.
var str = 'This is a string with <img src="./images/logo.png" alt="logo" /> an image';
It works.
P.S. - inspired by this Replace all <img> tag with img alt text :)

Using Variables in Replace() Method - Javascript

I am trying to replace the contents of the alt="" attribute in the tag.
The replacment text comes from textarea input that is assigned to var alttext
The var oldtext contains tags with placeholders for replacing, like:
<img alt="placeholder" scr="pic.jpg" />
The placeholder needs to be replaced the contents of var alttext.
So far I have tried:
function replacer() {
var alttext = document.myform.alttext.value;
var oldtext = document.myform.oldtext.value;
var replacedtext = oldtext.replace("placeholder", 'alttext' )
document.myform.outputtext.value = replacedtext;
}
But it does not work.
How can the alttext variable contents be used to replace the placeholder?
Thank you very much to everyone!
function replacer() {
var alttext = document.myform.alttext.value;
var oldtext = document.myform.oldtext.value;
var replacedtext = oldtext.replace("placeholder", alttext);
document.myform.outputtext.value = replacedtext;
}
you were trying to replace with quotes around your variable (alttext) making it a string literal

Categories