Inline image in dynamic text - html

I am working on a chat application using AS3. I am new to AS and flash. I want to add smilies in the chat. So when a user types ":p" i want to replace it with an image in his text message. I simply used image tag to do this. However, image does not show inline. It shows in the next line.
Is there an easy way to do this?
Example:
Currently -> this is my chat
image here
Desired results -> this is my "image here" chat
Sample code
var abc:String="This is my :p chat";
abc.replace(":p", "<img src='url of the image' height='10' width='10'>"

Have you tried:
img{
display: inline;
}
I am assuming you already know about loading stylesheets via AS3?
UPDATE:
Something like this should work:
var style:StyleSheet = new StyleSheet();
style.parseCSS("img{ display: inline; }");
// IMPORTANT: tf is whatever TextField instance you are using
tf.styleSheet = style;
var str:String = "<p>This is my :p chat</p>";
tf.htmlText = str.replace(":p", "<img src='url of the image' height='10' width='10'>");

Try this one:
var _message = "Good to see u :) how are you";
chatTxt.htmlText = doReplace(_message);
function doReplace(msg):String
{
var _str = refDocument._baseURL + "/tool/assets/emotion/";
var _search:Array = [":)",";)"];
var _replace:Array = ["<img width='20' height='20' src='smile.png'>","<img width='20' height='20' src='wink.png'>"];
for (var i:int=0; i<_search.length; i++)
{
msg = msg.split(_search[i]).join(_replace[i]);
}
return msg;
}
make sure chatTxt is TLF text

Related

Copied Image from Google Document Paragraph inserted twice

I'm trying to combine several Google Document inside one, but images inside the originals documents are inserted twice. One is at the right location, the other one is at the end of the newly created doc.
From what I saw, these images are detected as Paragraph by the script.
As you might see in my code below, I've been inspired by similar topics found here.
One of them suggested searching for child Element inside the Paragraph Element, but debugging showed that there is none. The concerned part of the doc will always be inserted with appendParagraph method as the script is not able to properly detect the image.
This is why the other relevant topic I found cannot work here : it suggested inserting the image before the paragraph itself but it cannot detects it.
Logging with both default Logger and console.log from Stackdriver will display an object typed as Paragraph.
The execution step by step did not show displayed any loop calling the appendParagraph method twice.
/* chosenParts contains list of Google Documents name */
function concatChosenFiles(chosenParts) {
var folders = DriveApp.getFoldersByName(folderName);
var folder = folders.hasNext() ? folders.next() : false;
var parentFolders = folder.getParents();
var parentFolder = parentFolders.next();
var file = null;
var gdocFile = null;
var fileContent = null;
var offerTitle = "New offer";
var gdocOffer = DocumentApp.create(offerTitle);
var gfileOffer = DriveApp.getFileById(gdocOffer.getId()); // transform Doc into File in order to choose its path with DriveApp
var offerHeader = gdocOffer.addHeader();
var offerContent = gdocOffer.getBody();
var header = null;
var headerSubPart = null;
var partBody= null;
var style = {};
parentFolder.addFile(gfileOffer); // place current offer inside generator folder
DriveApp.getRootFolder().removeFile(gfileOffer); // remove from home folder to avoid copy
for (var i = 0; i < chosenParts.length; i++) {
// First retrieve Document to combine
file = folder.getFilesByName(chosenParts[i]);
file = file.hasNext() ? file.next() : null;
gdocFile = DocumentApp.openById(file.getId());
header = gdocFile.getHeader();
// set Header from first doc
if ((0 === i) && (null !== header)) {
for (var j = 0; j < header.getNumChildren(); j++) {
headerSubPart = header.getChild(j).copy();
offerHeader.appendParagraph(headerSubPart); // Assume header content is always a paragraph
}
}
fileContent = gdocFile.getBody();
// Analyse file content and insert each part inside the offer with the right method
for (var j = 0; j < fileContent.getNumChildren(); j++) {
// There is a limit somewhere between 50-100 unsaved changed where the script
// wont continue until a batch is commited.
if (j % 50 == 0) {
gdocOffer.saveAndClose();
gdocOffer = DocumentApp.openById(gdocOffer.getId());
offerContent = gdocOffer.getBody();
}
partBody = fileContent.getChild(j).copy();
switch (partBody.getType()) {
case DocumentApp.ElementType.HORIZONTAL_RULE:
offerContent.appendHorizontalRule();
break;
case DocumentApp.ElementType.INLINE_IMAGE:
offerContent.appendImage(partBody);
break;
case DocumentApp.ElementType.LIST_ITEM:
offerContent.appendListItem(partBody);
break;
case DocumentApp.ElementType.PAGE_BREAK:
offerContent.appendPageBreak(partBody);
break;
case DocumentApp.ElementType.PARAGRAPH:
// Search for image inside parapraph type
if (partBody.asParagraph().getNumChildren() != 0 && partBody.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE)
{
offerContent.appendImage(partBody.asParagraph().getChild(0).asInlineImage().getBlob());
} else {
offerContent.appendParagraph(partBody.asParagraph());
}
break;
case DocumentApp.ElementType.TABLE:
offerContent.appendTable(partBody);
break;
default:
style[DocumentApp.Attribute.BOLD] = true;
offerContent.appendParagraph("Element type '" + partBody.getType() + "' from '" + file.getName() + "' could not be merged.").setAttributes(style);
console.log("Element type '" + partBody.getType() + "' from '" + file.getName() + "' could not be merged.");
Logger.log("Element type '" + partBody.getType() + "' from '" + file.getName() + "' could not be merged.");
}
}
// page break at the end of each part.
offerContent.appendPageBreak();
}
}
The problem occurs no matter how much files are combined, using one is enough to reproduce.
If there's only one image in the file (no spaces nor line feed around) and if the "appendPageBreak" is not used afterward, it will not occur. When some text resides next to the image, then the image is duplicated.
One last thing : Someone suggested that it is "due to natural inheritance of formatting", but I did not find how to prevent that.
Many thanks to everyone who'll be able to take a look at this :)
Edit : I adapted the paragraph section after #ziganotschka suggestions
It is very similar to this subject except its solution does not work here.
Here is the new piece of code :
case DocumentApp.ElementType.PARAGRAPH:
// Search for image inside parapraph type
if(partBody.asParagraph().getPositionedImages().length) {
// Assume only one image per paragraph (#TODO : to improve)
tmpImage = partBody.asParagraph().getPositionedImages()[0].getBlob().copyBlob();
// remove image from paragraph in order to add only the paragraph
partBody.asParagraph().removePositionedImage(partBody.asParagraph().getPositionedImages()[0].getId());
tmpParagraph = offerContent.appendParagraph(partBody.asParagraph());
// Then add the image afterward, without text
tmpParagraph.addPositionedImage(tmpImage);
} else if (partBody.asParagraph().getNumChildren() != 0 && partBody.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) {
offerContent.appendImage(partBody.asParagraph().getChild(0).asInlineImage().getBlob());
} else {
offerContent.appendParagraph(partBody.asParagraph());
}
break;
Unfortunately, it stills duplicate the image. And if I comment the line inserting the image (tmpParagraph.addPositionedImage(tmpImage);) then no image is inserted at all.
Edit 2 : it is a known bug in Google App Script
https://issuetracker.google.com/issues/36763970
See comments for some workaround.
Your image is embedded as a 'Wrap text', rather than an Inline image
This is why you cannot retrieve it with getBody().getImages();
Instead, you can retrieve it with getBody().getParagraphs();[index].getPositionedImages()
I am not sure why exactly your image is copied twice, but as a workaround you can make a copy of the image and insert it as an inline image with
getBody().insertImage(childIndex, getBody().getParagraphs()[index].getPositionedImages()[index].copy());
And subsequently
getBody().getParagraphs()[index].getPositionedImages()[index].removeFromParent();
Obviously, you will need to loop through all the paragraphs and check for each one either it has embedded positioned images in order to retrieve them with the right index and proceed.
Add your PositionedImages at the end of your script after you add all your other elements. From my experience if other elements get added to the document after the the image positioning paragraph, extra images will be added.
You can accomplish this my storing a reference to the paragraph element that will be used as the image holder, and any information (height, width, etc) along with the blob from the image. And then at the end of your script just iterate over the stored references and add the images.
var imageParagraphs = [];
...
case DocumentApp.ElementType.PARAGRAPH:
var positionedImages = element.getPositionedImages();
if (positionedImages.length > 0){
var imageData = [];
for each(var image in positionedImages){
imageData.push({
height: image.getHeight(),
width: image.getWidth(),
leftOffset: image.getLeftOffset(),
topOffset: image.getTopOffset(),
layout: image.getLayout(),
blob: image.getBlob()
});
element.removePositionedImage(image.getId());
}
var p = merged_doc_body.appendParagraph(element.asParagraph());
imageParagraphs.push({element: p, imageData: imageData});
}
else
merged_doc_body.appendParagraph(element);
break;
...
for each(var p in imageParagraphs){
var imageData = p.imageData
var imageParagraph = p.element
for each(var image in imageData){
imageParagraph.addPositionedImage(image.blob)
.setHeight(image.height)
.setWidth(image.width)
.setLeftOffset(image.leftOffset)
.setTopOffset(image.topOffset)
.setLayout(image.layout);
}
}

How to change an image every 15 seconds in HTML

I have an image in my HTML page, and I would like it to change to a different image every 15 seconds.
<img src="img/img 1.jpg" alt="image">
In my local folder img, I have two images which are img 1.jpg and img 2.jpg. How do I change the img 1.jpg to img 2.jpg after 15 seconds?
Try it:
$(document).ready(function(){
var img = 0;
var slides = new Array();
while (img < 5) {
img++;
// put your image src in sequence
var src = 'assets/images/earth/Sequence' + img + '.jpg';
slides.push(src);
}
var index = 0,timer = 0;
showNextSlide();
timer = setInterval(showNextSlide, 15000);
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('earth').src = slides[index++];
}
});
Try this (pure JS)
var myArray = ['img1', 'img2', 'img3', 'img4', 'img5', 'img6']
var count = 0;
setInterval(function() {
//use this below line if you want random images
//var rand = myArray[Math.floor(Math.random() * myArray.length)];
if (count >= myArray.length) count = 0; // if it is last image then show the first image.
// use this below line if you want images in order.
var rand = myArray[count];
document.getElementById('img').src = rand;
document.getElementById('img').alt = rand; // use 'alt' to display the image name if image is not found
count++;
}, 1000); // 1000 = 1 second
<img src="img/img 1.jpg" alt="image" id='img' />
To do this, you're going to need some Javascript to change the image. Here is a link to a popular website for help with Javascript, HTML, CSS, and a whole lot more. What you'll want to be looking at specifically though, is the setInterval() function on this page: http://www.w3schools.com/js/js_timing.asp
If you don't know Javascript at all, it is also not a bad place to start learning! If that's all you need it for though, you'll need very little Javascript at all.
Firstly include jQuery library in your page.
Then use this script:
$(document).ready(function() {
setInterval(function(){
_path = $('img').attr('src');
_img_id = _path.replace('img/img', '');
_img_id = _img_id.replace('.jpg', '');
_img_id++;
if (_img_id == 3) {
_img_id = 1;
};
$('img').attr('src', 'img/img' + _img_id + '.jpg');
}, 15000);
});

Is it possible to Highlight <strong> each word spoken in a sentence with Web Speech API

Looking at the documentation, there seems to be no method of capturing the word about to be spoken, and so being able to BOLD the current word, so its easy to follow for children.
REF: https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html
This is the code I am using:
var u = new SpeechSynthesisUtterance();
u.text = element.innerHTML;
u.lang = 'en-UK';
u.rate = 1;
speechSynthesis.speak(u);
element.innerHTML = "This is a test text sentence.";
While reading the text out, I would like each word to be bold, and then normal. i.e.:
This is a test text sentence
Has anyone been able to achieve this?
UPDATE
I have this code, and it gives me the charIndex of the space of the last word spoken:
u.onboundary = function(event) { console.log(event.charIndex); }
Below is what I have so far, still not right, but close:
HTML:
<div id="speak"></div>
Javascript:
var u = new SpeechSynthesisUtterance();
u.text = 'This is a story about Math!';
u.lang = 'en-UK';
u.rate = 0.7;
u.onboundary = function (event) {
$('#speak').append(u.text.substr(event.charIndex, u.text.indexOf(' ')) + '<br />');
}
speechSynthesis.speak(u);
Demo: jsfiddle
I managed to do this using the following code:
element.innerHTML = "This is a test case"
var u = new SpeechSynthesisUtterance();
var words = element.innerHTML.split(' ');
var a = 0;
u.text = element.innerHTML;
u.lang = 'en-UK';
u.rate = 0.7;
u.onboundary = function(event) {
console.log(words);
element.innerHTML = element.innerHTML.replace(words[a], '<strong>' + words[a] + '</strong>');
a++;
}
speechSynthesis.speak(u);
Took all day, but worth it now its done. Hope it helps others!!

Passing variables through navigateURL to open iFrame as3

By using NavigateURL I can easily pass variables as below through Flash to paypal, this works no problem and can include all the data required.
var req:URLRequest = new URLRequest("https://www.paypal.com/cgi-bin/webscr");
var reqVars:URLVariables = new URLVariables();
reqVars.cmd = "_xclick-subscriptions";
reqVars.business = "BUSINESS CODE";
reqVars.lc = "GR";
reqVars.item_name = "Product Name";
reqVars.item_number = "Product Number 0001";
reqVars.no_note = "1";
reqVars.no_shipping = "2";
reqVars.src = "1";
reqVars.a3 = "15.00";
reqVars.p3 = "1";
reqVars.t3 = "Y";
reqVars.currency_code = "EUR";
//and so on
req.data = reqVars;
req.method = URLRequestMethod.POST;
navigateToURL(req);
By using callIframe as shown below I can easily open an iFrame from Flash.
calliFrame("http://www.webAddress.com/" +"?iframe=true&width=800&height=550", "Page Title", "Page Description");
function calliFrame(url:String, title:String, desc:String):void{
if (ExternalInterface.available) {
trace("calling prettyPhoto");
try {
ExternalInterface.call('$.prettyPhoto.open', url, title, desc);
} catch (event:Error) {
trace("Error occurred!");
}
} else {
trace("External Interface unavailable");
}
}
Is it possible to pass the navigateURL variables through the calliFrame method? I've tried variations but not gotten to either transfer the data or show the page.
I hoped something like the example below would work but only get a blank page or list of the data shown in the iFrame:
calliFrame("https://www.paypal.com/cgi-bin/webscr" +reqVars +"?iframe=true&width=800&height=550", "Page Title", "Page Description");
Any help would be much appreciated, thanks in advance.
The second parameter is the window name, so all you gotta do is pass the name of your iframe.
public function navigateToURL(request:URLRequest, window:String = null):void
docs: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/package.html#navigateToURL()

Insert a Link Using CSS

I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate:
<table><tr><td class="case">123456</td></tr></table>
I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz).
So I'd like that "123456" to be changed to a link of this form:
123456
Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number.
Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript..
function makeCasesClickable(){
var cells = document.getElementsByTagName('td')
for (var i = 0, cell; cell = cells[i]; i++){
if (cell.className != 'case') continue
var caseId = cell.innerHTML
cell.innerHTML = ''
var link = document.createElement('a')
link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId
link.appendChild(document.createTextNode(caseId))
cell.appendChild(link)
}
}
You can apply it with something like onload = makeCasesClickable, or simply include it right at the end of the page.
here is a jQuery solution specific to your HTML posted:
$('.case').each(function() {
var link = $(this).html();
$(this).contents().wrap('');
});
in essence, over each .case element, will grab the contents of the element, and throw them into a link wrapped around it.
Not possible with CSS, plus that's not what CSS is for any way. Client-side Javascript or Server-side (insert language of choice) is the way to go.
I don't think it's possible with CSS. CSS is only supposed to affect the looks and layout of your content.
This seems like a job for a PHP script (or some other language). You didn't give enough information for me to know the best way to do it, but maybe something like this:
function case_link($id) {
return '' . $id . '';
}
Then later in your document:
<table><tr><td class="case"><?php echo case_link('123456'); ?></td></tr></table>
And if you want an .html file, just run the script from the command line and redirect the output to an .html file.
You could have something like this (using Javascript). Inside <head>, have
<script type="text/javascript" language="javascript">
function getElementsByClass (className) {
var all = document.all ? document.all :
document.getElementsByTagName('*');
var elements = new Array();
for (var i = 0; i < all.length; i++)
if (all[i].className == className)
elements[elements.length] = all[i];
return elements;
}
function makeLinks(className, url) {
nodes = getElementsByClass(className);
for(var i = 0; i < nodes.length; i++) {
node = nodes[i];
text = node.innerHTML
node.innerHTML = '' + text + '';
}
}
</script>
And then at the end of <body>
<script type="text/javascript" language="javascript">
makeLinks("case", "http://bugs.example.com/fogbugz/default.php?");
</script>
I've tested it, and it works fine.
I know this is an old question, but I stumbled upon this post looking for a solution for creating hyperlinks using CSS and ended up making my own, could be of interest for someone stumbling across this question like I did:
Here's a php function called 'linker();'that enables a fake CSS attribute
connect: 'url.com';
for an #id defined item.
just let the php call this on every item of HTML you deem link worthy.
the inputs are the .css file as a string, using:
$style_cont = file_get_contents($style_path);
and the #id of the corresponding item. Heres the whole thing:
function linker($style_cont, $id_html){
if (strpos($style_cont,'connect:') !== false) {
$url;
$id_final;
$id_outer = '#'.$id_html;
$id_loc = strpos($style_cont,$id_outer);
$connect_loc = strpos($style_cont,'connect:', $id_loc);
$next_single_quote = stripos($style_cont,"'", $connect_loc);
$next_double_quote = stripos($style_cont,'"', $connect_loc);
if($connect_loc < $next_single_quote)
{
$link_start = $next_single_quote +1;
$last_single_quote = stripos($style_cont, "'", $link_start);
$link_end = $last_single_quote;
$link_size = $link_end - $link_start;
$url = substr($style_cont, $link_start, $link_size);
}
else
{
$link_start = $next_double_quote +1;
$last_double_quote = stripos($style_cont, '"', $link_start);
$link_end = $last_double_quote;
$link_size = $link_end - $link_start;
$url = substr($style_cont, $link_start, $link_size); //link!
}
$connect_loc_rev = (strlen($style_cont) - $connect_loc) * -1;
$id_start = strrpos($style_cont, '#', $connect_loc_rev);
$id_end = strpos($style_cont,'{', $id_start);
$id_size = $id_end - $id_start;
$id_raw = substr($style_cont, $id_start, $id_size);
$id_clean = rtrim($id_raw); //id!
if (strpos($url,'http://') !== false)
{
$url_clean = $url;
}
else
{
$url_clean = 'http://'.$url;
};
if($id_clean[0] == '#')
{
$id_final = $id_clean;
if($id_outer == $id_final)
{
echo '<a href="';
echo $url_clean;
echo '" target="_blank">';
};
};
};
};
this could probably be improved/shortened using commands like .wrap() or getelementbyID()
because it only generates the <a href='blah'> portion, but seeing as </a> disappears anyway without a opening clause it still works if you just add them everywhere :D