Pantalaimon Pantalaimon - 7 months ago 25
Javascript Question

Converting text to images within a jQuery live preview div

I require a way of outputting images into a live preview div, directly as
a user inputs letters. For example, if the user inputs the letter 'k', an
image tied to the 'k' letter is displayed. However, currently only the
letters pre-entered on the page loading display the images, not
characters inputted from a textarea field, as you can see in this [demo]
(http://jsfiddle.net/jLzsrygv/8/).

The method I use of converting characters to images is as follows:

$('#target').each(function() {
var txt = $(this).html();
var img = '<img src="http://i.imgur.com/DWwRx9M.png" alt="' + txt + '" />'
var html = txt.replace(/\*/g, img);
$(this).html(html);
});


What I've tried



I have tried changing the allowed tags of the textarea field to allow img
tags and then controlling this (invisible) textarea with a master
textarea, but to no avail as the k does not convert itself to the img tag
in the original textarea field.

Since directly inserting img tags are the only thing that seem to work for me, the only way I see it possible with my very limited knowledge of the
language is for the second text area in real-time to replace letters
typed into the master text area (e.g 'K' is replaced by ) I have experimented with text replacements but I feel I
may be going wrong with textContent, as opposed to a value or innerHTML. This is as far as I've gotten.

Would appreciate any help.

Answer

The only thing you are not doing is calling the .each() methods when there is a keyup. Thus, the .each() are only called once then the JavaScript is loaded. Put them inside functions and call the functions upon keyup.

$(document).ready(function(){
    change1();
    change2();
    $('#someTextBox').keyup(function(){
        $('#target').html($(this).val());
        change1();
        $('#target2').html($(this).val());
        change2();
    });
});

function change1() {
    $('#target').each(function() {
        var txt = $(this).html();
        var img = '<img src="http://i.imgur.com/DWwRx9M.png" alt="' + txt + '" />'
        var html = txt.replace(/\*/g, img);
        $(this).html(html);
    });
}

function change2() {
    $('#target2').each(function() {
        var txt = $(this).html();
        var img = '<img src="http://i.imgur.com/DWwRx9M.png" alt="' + txt + '" />'
        var html = txt.replace(/\*/g, img);
        //console.log(html);
        $(this).html(html);
    });
}

Fiddle: http://jsfiddle.net/jLzsrygv/21/

Comments