Converting text to images within a jQuery live preview div - javascript

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.

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/

Related

Adding a picture button in js

I have my code working tho what i would like it's to customize the text link so it should be a picture.
Example the "View" text link will be /pics/icon.png and "Edit", /pics/icon2.png
Here it's my code:
var $container = $( "#daif_results" );
$container.empty();
$.each( items, function() {
var str = '<li>' + this.label + ' - <a href="' + daif_consts.home_url + '?p=' + this.value +
'">View</a> - Edit</li>';
$container.append( str );
});
I couldn't run your code, but I believe you are trying to add images to one of your lists. I think you could use CSS to achieve that, like this example.
I also found a javascript example here.
I think you could create an image element:
img = document.createElement('img');
img.src = "http://sourcetoimage";
And then append it to your list:
li.appendChild(img);
Here's a JFiddle.

Hot to insert a different img into a div depending on the value

I am trying to insert a img into a div, but it should be a different img depending on the div value, which is dynamically populating
So if value is test insert image test.jpg, if the value is blabla insert image blabla.jpg and so on (i got about 25 div values)
I got it working only for the first one now and it is only populating one img everywhere if i use
var divText = $('div').first().text();
My names vars and the img names jpg are exactly the same
Probably need to loop it somehow, some help will be appreciate
My code so far is
HTML
<div>test</div>
<div>blabla</div>
<div>dasdad</div>
<div>khjkhjk</div>
jQuery
var name = 'test';
var name1 = "blabla";
var imgPath = "folder/images/";
var divText = $('div').text();
if (divText === name) {
$('div').prepend('<img src="' + imgPath + 'test' + '.jpg"/>');
}
if (divText === name1) {
$('div').prepend('<img src="' + imgPath + 'blabla' + '.jpg"/>');
}
Here is my fiddle - http://jsfiddle.net/6da9jvr7/
The easiest way to do this is with jquery's each.
$('div').each(function(){
var $div = $(this);
$div.prepend(<img src="' + imgPath + $div.text() + '.jpg"/>');
});
When you call $('div').each(), jquery first selects every div in the document. It then loops over the divs and calls the callback you specify. "this" is bound to the current div in the loop, so when we call $(this) we're "wrapping" that div with jquery, which allows us to use functions like .text and .prepend.
Try to use each loop for this
$.each($('div'), function() {
var img_name = $(this).text();
$(this).prepend('<img src="' + imgPath + img_name + '.jpg"/>');
});
I made a couple assumptions in this demo (added the foo class to the divs, etc)
I believe all you need is this:
var imgPath = "folder/images/";
$('div.foo').each(function(index, element){
var divText = $(element).text();
$('div').prepend('<img src="' + imgPath + divText + '.jpg"/>');
});
You could identify the divs another way by adding a class for example:
<div class="dynamic-image">test</div>
<div class="dynamic-image">blabla</div>
Now you can just search all divs with the dynamic-image class, and fetch the image based on content, like so:
var path = 'path/to/images';
$('.dynamic-image').each(function(i, e) {
var $e = $(e),
img = new Image();
img.src = path + '/' + $e.text() + '.jpg';
$e.prepend(img);
});
For the looping part, you can do something like this. Note that you want to use innerHTML and not text. Also, keeping in mind that $('div') returns an array of divs (which I set to the variable divs).
var divs = $('div');
for (var i = 0; i < divs.length; i++) {
alert(divs[i] + " " + divs[i].innerHTML);
}

Paste event modify content and return it at the same place

I have created this jsfiddle for try to explain what Im trying to do
http://jsfiddle.net/nonyck/tyyCN/
$('.autoresize').bind('paste', function(e) {
e.preventDefault();
var data = e.originalEvent.clipboardData.getData('text');
if(data.match("http://.*?.(jpg|png|gif)")) {
$('.autoresize').val($('.autoresize').val() + "<image src='" + data + "' >");
} else {
$('.autoresize').val( $('.autoresize').val() + data);
}
});
What Im trying is to get the paste event, then modify it and return it back exactly where is the focus, atm this example just returns the content to the end.
So if the user is in the line 2, and pastes some content there, put the modified content there, and not at the end of the document.
Is there a way to return the value at the right place ??
You can get the caret position within the textarea using jQuery to determine where the user wants to paste the text:
Cursor position in a textarea (character index, not x/y coordinates)
Then insert your data into that position. See updated fiddle:
http://jsfiddle.net/tyyCN/1/
if(data.match("http://.*?.(jpg|png|gif)")) {
var caret = $(this).getCursorPosition();
var insert = "<image src='" + data + "' >";
var val = $('.autoresize').val();
$('.autoresize').val(val.substring(0, caret) + insert + val.substring(caret, (val.length)));
}

How to combine tags as long as they have the same class

The Html that I'm getting ideally looks like this:
<span class="RapidLink1-H">See the more detailed areas of what not</span>
Next my aim is to change the span tag into an anchor tag. With the ideal Html, I have done it this way:
// Walk through each link tag on this page and replace the content with an actual link
thisLink.each(function() {
linkRefTarget = '';
// Get only the identifier number of the link
linkId = ($(this).attr('class')).replace(/[A-Za-z$-]/g, '');
// Match this link with the list of link references
if (thisLinkRef) {
for (var key in thisLinkRef) {
if (key == 'link' + linkId) linkRefTarget = thisLinkRef[key];
}
}
output = '';
output+= '<a href="#' + linkRefTarget + '" id="link' + linkId + '" class="rapidLink">';
output+= $(this).html();
output+= '</a>';
}).replaceWith(output);
Now, the problem comes when I'm actually getting this sort of Html (please note, I can't change the Html input):
<span class="RapidLink1-H">See the</span><span class="RapidLink1-H">more detailed areas of</span><span class="RapidLink1-H">what not</span></span>
The question is:
How could I get it to work with such a broken set of spans?
I'm thinking the following:
Find an expected link span
Check whether the immediate next element is also a span with the same class
and then check whether the immediate next element is also...,
and then check...
if none is found, combine the innerHtml of each span into a single anchor tag
How could I achieve such a loop?
Thanks.
There is the + selector which selects consecutive elements: http://jsfiddle.net/NWWYC/1/.
$(".RapidLink1-H + .RapidLink1-H").each(function() {
// move contents to previous span, remove this span afterwards
$(this).prev(".RapidLink1-H").append(
$(this).contents()
).end().remove();
});

Convert url to html <a> tag and image url to <img> tag with javascript regular expressions

I am trying to write a function to create tags out of regular links and tags out of image links from the text in a text area.
it works the first time for both, but if i paste an "a href" tag in there, it double links it. it doesn't do the images because of the imageRegex check. any ideas how to get this to work?
keep in mind the textarea could have multiple urls of both types.
$("#message").blur(function() {
var imageRegex = /\.(png|jpg|jpeg|gif)$/;
var s = $(this).val().replace(/(?:^|[^"'])(\b(?:https?|ftp):\/\/[a-z0-9-+&##\/%?=~_|!:,.;]*[a-z0-9-+&##\/%=~_|])/gim, function(str) {
if (str.match(imageRegex)) {
return('<img src="' + str + '" />');
} else {
return('' + str + '');
}
});
$(this).val(s);
});
I'm not great at jQuery, but I made a vanillaJS solution to your problem. Check out this fiddle! http://jsfiddle.net/dv0s5onj/
var yourString=document.getElementById('message').innerHTML;
var count=0;
var urls=yourString.match(/(?:^|[^"'])(\b(?:https?|ftp):\/\/[a-z0-9-+&##\/%?=~_|!:,.;]*[a-z0-9-+&##\/%=~_|])/gim);
// Make an array of urls
urls.forEach(function(v,i,a){
var n = yourString.indexOf(v,count); //get location of string
if(v.match(/\.(png|jpg|jpeg|gif)$/)===null){// Check if image
// If link replace yourString with new anchor tag
yourString = strSplice(yourString,n,v.length,''+v+'');
count += (v.length*2)+16;// Increase count incase there are multiple of the same url.
}else{
// If link replace yourString with img tag
yourString = strSplice(yourString,n,v.length,'<img src="'+v+'" height="120px;" width="120px;"/>');
count += v.length+14;// Increase count incase there are multiple of the same url.
}
});
// A function to splice strings that I found on another StackOverflow Question.
function strSplice(str, index, count, add) {
return str.slice(0, index) + (add || "") + str.slice(index + count);
}
//Replace the value of your element with your string
document.getElementById('message').innerHTML=yourString;

Categories

Resources