I want to be able to put a way to easily insert GIFs/images into a webpage like the way Discord inserts images by text (i.e. :gifname:
).
I assume it processes some <textarea>
's content and gets the name of the image, and then inserts it. How can I do this?
Can I do some sort of replace()
insert abuse type thing, like:
Text.replace(":example:", "<img src='imagepath.png'>")
CodePudding user response:
Use js.
First, give your textarea an id attr:
<textarea id="text"></textarea>
then,
<script>
let t = document.getElementById('text')
function addShortcut(placeholder, emoji) {
t.addEventListener('change', function(e){
if(t.value.includes(placeholder)) {
t.value = t.value.split(placeholder).join(emoji)
}
})
}
//examples:
addShortcut('hi', 'hello')
addShortcut(':shug:', '¯\\_(ツ)_/¯')
</script>
If you want to add a shortcut, just use addShortcut
again after where I did.
you can delete the examples
Edit: made a typo, fixed it
Edit: If you want to have an image, then do something like this:
addShortcut(":gif:", "<img src='animation.gif' height='14px' width='auto'></gif>")
If you want to use a smaller text size, then just change the height attribute to match your text size.
Edit:
let t = document.getElementById('text')
function addShortcut(placeholder, emoji) {
t.addEventListener('change', function(e) {
if (t.value.includes(placeholder)) {
t.value = t.value.split(placeholder).join(emoji)
}
})
}
//examples:
addShortcut('hi', 'hello')
addShortcut(':shrug:', '¯\\_(ツ)_/¯')
addShortcut(':img:', '')
textarea {
font-size: 14px;
}
<textarea id='text'></textarea>
CodePudding user response:
Using input
or textarea
tag are't possible.
Because these elements can handle only plain text like Ascii, UTF-8, and others. Emoji works in it because is part of the Unicode system.
In that way, u can do this as Hermanboxcar said above, replacing an string with another.
The way Discord works are more complex because it handles events and sub-nodes in DOM (Document Object Model).
You could look for WYSIWYG, it's the name of Discord's text field are using.
I recommend you inspect Discord in the browser and try to type anything else. You will see that it works in another way as you no expect
CodePudding user response:
To change source of image I would recommend selecting your image using query selector and then simply replacing it to other image
<img src="./image.jpg" alt="">
<script>
document.querySelector('.example-image').src = 'image-replace.jpg';
</script>
Have in mind that in shown example I used picture I already had on disc, but you can use url to image, and if you want to use textarea to get image path/url, here is the code to do so, it works on a button click:
<img src="./image.jpg" alt="">
<textarea cols="30" rows="10"></textarea>
<button >Click</button>
<script>
document.querySelector(".example-btn").addEventListener("click", ()=>{
document.querySelector('.example-image').src = document.querySelector('.example-textarea').value;
})
</script>