Blog Home Cartweaver ColdFusion Demos Javascript Music Photos WebDev Whatever

Truncate text on full words only - a simple version of "full left"

Common scenario: you want to show the first part of a long chunk of text, and then have the full text available via a link like " (more...) " , which would either show the text with javascript (more on that later) or take you to another page to see the full article.

For a long time now I have used the "fullLeft()" udf, which works just fine and does exactly what it should.  But the other day, I got a wild hair and, rather than calling in the fullLeft function to my page, decided to script something right in place... just 'because'.

And whaddyaknow, it works... works great, really.
But it is so simple - what am I missing?

Like most things, my 'aha' is haunted by a 'what if', as in 'what if it breaks on certain characters or other stuff in the text'?  What if I don't really know what the heck I am doing? But ...hey... it works!

//// Here is the logic:

take a chunk of text and a number, passed in as variables.

replace all line breaks in the text with <br> tags (easy to remove if not needed)

if the length of the text is more than the given number, cut it off at that
number of characters

find the number of characters at the end of the remaining string that come after the last space ( ' '), and remove them

if the text was trimmed, output the text in a p tag with a (more...) link  - this can all be modified to give the link a url, or in my case to use javascript to show the full text in place of the truncated content.

/// Here is the code:

<cfscript>
/**
 * Another version of "full left"
 *
 * @param trimlength      Length, in characters, to trim text to (Required)
 * @param rawtext           Text to trim (Required)
 * @return Returns a string with an ellipsis (...) 
 * @author Michael Evangelista (mredesign.com)
 * @created June 6, 2008
 
 Usage:
 <cfinclude template="func/trimtext.cfm">
 <cfoutput>#trimtext(recordbody, 160)#</cfoutput>
 */
 
function trimtext(rawtext, trimlength)
{
// this line replaced line returns in the text block with html breaks
   rawtext = replace(rawtext, chr(13), '<br />', 'all');
      if (len(rawtext) gt trimlength)
   {
   cuttext = left(rawtext, trimlength);
   trimlen = len(cuttext) - len(listLast(cutText, ' '));
   texttouse = left(rawtext, trimlen) & '... <em>(<a class="morelink" href="##">more</a>)</em>';
   }
   else
   {
   texttouse = rawtext;
   }
   textoutput = '<p>' & texttouse & '</p>';
   return textoutput;
   }
</cfscript>


Feedback and/or testing appreciated.
thanks

Demo: Dynamic CF Navigation Menu with 'current page' marker

ColdFusion Navigation Menu Demo

Sometimes you just need a simple menu.

If your list is very long, making a link with a class and an id, typing the href value for each, and inserting the link text all by hand can get old. And then - how do you show which link is the current page?

Here we set up a simple list of url/text pairs, and then loop through that list to create our links.

Then - much like the popular javascript-based 'current page' menus - we look at the value of the link url, and the current page url (cgi.SCRIPT_NAME) - if they are the same, we have a winner. One other thing I find myself commonly wanting is a bit of special css on the first or last item in a list, so the code also assigns IDs to those links.

See the demo   See the code

Show a random image with <cfdirectory>

This is a chunk of code I've had around for a while... fairly useful, felt like sharing.

Basically you're looking in a given folder with <cfdirectory> and pulling out a random image by counting between 1 and the number of images found. Just enter the relative location of your images folder and you're all set.


<!--- set the relative path to the folder with your images --->
<cfset imagesFolder = "./">

<!--- code to look in directory, choose one image at random --->
<cfdirectory directory="#expandPath(imagesFolder)#" filter="*.jpg" name="getPics" action="list"/>
<cfset maxrows = getPics.recordCount/>
<cfset startRow = randRange(1, maxrows)/>

<!--- if one or more photos was found --->
<cfif maxrows gt 0>
    <div class="showPic">
    <cfoutput query="getPics" startrow="#startRow#" maxrows="1">
        <img src="#imagesFolder#/#name#" alt="#listFirst(name, ".")#"/>
    </cfoutput>
    <br /><br />
    Hit refresh or reload to get a different image.
    </div>
</cfif>

NOTE: you might want to give the image a different alt tag, like the name of your site, or... whatever. (this code will use the filename of the image). This same code can be adapted for any files in any directory - change the 'filter' attribute to allow whatever file extension you like.

With CF8, you could get also the height and width of the image to create proper height/width attributes for the <img> tag.

[Update 1/22/08] This mini-tutorial is now featured on learncf.com

demo: GeoEncode any address with cf_googleMap.cfc

http://www.mredesign.com/demos/googlemap-connector/

Enter any address and see it on a googlemap.

This demo was up in another form for quite some time... I was putting a googlemap in a current project and decided to give this a proper place in the demos list.

If you use maps on your pages, you should surely take a look at John Blayter's versatile and well-documented cf_googleMap.cfc

Sitemap XML Generator demo - make a sitemap on the fly with _sitemap.cfc

Make an xml sitemap of any site on the fly!

Being recently and completely impressed with Mike Henke's  Google Sitemap XML Creator , I wanted to see if I could make it work on any site, like a little remote-control spider-bot. Sure enough... this thing is so slick and easy to use, I was able to put the demo together over a coffee break.

The cfc contains another method for submitting the sitemap (removed from demo) and allows deeper spidering - limited here to 2 levels.

This little cfc is a true gem.

The form and resulting code runs out of a single include file, which I will continue to tweak ... if anybody wants a copy just drop me an email.

Playing with CFimage - a CF demo

Since I first heard about CF8 earlier this year, I have been eagerly waiting to get my hands on the new image functions.  Tonight, while watching the Red Sox walk all over the Indians on their way to the World Series, I spent some time with Ben Nadel's excellent cfimage tutorials (part I and II), and built this fun little demo  to show  off some of the functions.

Overall I am extremely impressed with both the speed and quality, especially for resizing. As I understand it, the java image resizing functions have been greatly improved upon, and the fact that quality is so easily controllable - by passing a value between 0.0 and 1.0 - is really nice.

There are a lot more things that CFimage can do... but this demo gives you some of the basics: www.mredesign.com/demos/cfimage-example/index.cfm

Super simple jQuery dynamic AJAX content demo

I just created my first 'ajax' page... and can hardly believe how simply jQuery handles this function.

I created a cfm page with 3 chunks of content wrapped in cfif, with each one shown based on a url variable. Then I set up a few lines of jQuery code to call that page and pass the variable in the url.

The sample page is just for example. In theory, you could run a full query to the database using the url variable to select any type of content you want, and then show it right in the page, without refreshing, or 'blinking' anything.

(Going one step further, jQuery can use (this).text() to pull the text that it inside each link, and pass the string as the url variable. So a linked word 'cicero' becomes a value of 'cicero' in the url.)

See the demo and the code - jquery makes this so simple, I can already think of a dozen ways I can use this action in my cf applications (especially back-end stuff where js-disabled browsers are not an issue).

A few more simple jQuery demos

Just playing around, showing what little I know of this stuff - added a few more demos based on tutorials I found online

Javascript text resizer with jQuery

Show/hide animations using jQuery's onboard effects

FAQ-style show/hide jQuery demo

jQuery makes this stuff so easy!

I just added a simple jQuery FAQ demo to my humble demos list

Had to build something similar for a client's site today - stripping out the relevant code and putting up an example was quick and painless... enjoy!

http://www.mredesign.com/demos/jquery-show-hide/

jQuery - switch styles / container class using simple links

jQuery makes this stuff far too easy.
I just threw together a quick demo of the jQuery '.addClass' function, using regular ol' page links to change the class of a div on the page.

Rather than separate stylesheets, I simply have one set of styles in the page head with 3 versions of each rule. So when the class of the container changes, the browser knows to use the style that fits.

There are more complex tutorials for 'stylesheet switchers' out there ( like this one ) , but I wanted to show how easy it is to change a class on any element with basic links using jQuery. Example code is on the demo page.

Super simple random text display

Playing around with my brand-new demos site (rather than actually adding another demo like I sat down to do), I decided I wanted a random subheader on the main page, like the coldfusionbloggers.org site

And whaddya know - while uber-supremely simple cf-wise, it makes for a cutesy little demo in and of itself.

Here's the rub...

First, I put a bunch of stuff into a list variable
using a pipe '|' for a delimiter (so I can use commas in my slogans)

<!--- goofy slogans --->
<cfset sloganList="
Slogan1|
Slogan2|
Witty saying|
Stupid quote|
Senseless garbage|
Funny, at least at the moment|
Something else|
Got the idea yet?
">

Then, get one of the items in the list, at random,
using listLen to get the length of the list and declaring
my pipe character as the delimiter

<cfset goofySubHead=listGetAt(sloganList, randRange(1, listLen(sloganList, '|')),'|')>

and then, in my page's header,
<h2>#goofySubHead#</h2>

That's it!

If you want to see it at work, just click here
and then refresh the page to see the slogan change
( or don't... see if I care... fine, be that way!)

More jQuery demos

Following a link from one of the jQuery google groups, I found a big list of jQuery demos by Glen at commadot.com... and for the record I am jealous of the obvious time he's had just to play and explore. So much you can do with jQuery, I have been endlessly amazed for weeks now, and still feel I'm only scratching the surface.

Anyway, check out the demos - they're good examples of the fun funky things jQuery makes so easy.

jQuery - super simple link effect examples

ok , last one for now
this simple example page shows how easy it is to make links that 'do stuff' using jQuery.

Things I've learned, and was actually able to use (only had to check my syntax 7 times in 7 lines... )

The built in behavior called 'click' lets you assign any function when the named element is clicked
The behaviors of fadeIn and fadeOut do just that, with speeds of slow, normal or fast
The behavior called 'toggle' lets you assign two functions, and toggle between them by clicking the same element twice

Here is the extent of the code for the sample page (with comments) ...

<script>
$(document).ready(function(){
// link with id of 'showit' shows the div with id of 'somestuff'
$("a#showit").click( function() {
$("div#somestuff").fadeIn("slow")
} );
// link with id of 'hideit' hides the div with id of 'somestuff'
$("a#hideit").click( function() {
$("div#somestuff").fadeOut("slow")
} );
// link with id of 'toggleit' toggles the two functions
$("a#toggleit").toggle(
  function () {
    $("div#somestuff").fadeIn("slow");
  },
  function () {
    $("div#somestuff").fadeOut("slow");
  }
);
});
</script>

I don't know how many lines of straight javascript this would have been, but it ain't much at all using jQuery (of course, there's something like 3000 lines in the jquery file itself... but that's all done ahead of time!).

I also have a bit of css in the file, to give the stuffbox div a height, and an inline style so the stuff itself loads as hidden.

On the scale of jquery examples, this has got to be about 3 degrees below 'super-beginner-nooby', but for me, I suddenly feel like I can actually write - and understand - my own simple js functions... and that's the whole point of a library like jQuery.

CF Instant Gallery demo :: upload a zip file, get a gallery!

This is just a simple demo, no database or xml (yet) so no captions or other data, but the function is fun, and easy...
http://www.mredesign.com/demos/zipGallery/index.cfm

Upload a zip file containing some jpg images, give your gallery a unique name (folder with same name will be created on server) and then wait... while the server uploads and unzips the file (with zip.cfc), resizes all of the photos (using Massimo's tmt_img.cfc) and then displays a gallery ready-to-go.

Current skins include Project Seven's Slide Show Magic and Image Gallery Magic, plus the interesting (and easy) FrogJS Gallery and a quick HoverBox CSS Gallery

Go ahead... try it!
If you have any problems / errors, please let me know by leaving a comment on this post.
(or if you don't want to wait, there are some sample galleries on the right side of the upload form)

This was just a quick workbench experiment, to show the upload/unzip/resize routine in action.
Future plans for the 'real' gallery include either an xml or mySQL back end, with captions, titles, categories, etc for a full-blown instant gallery maker.

All comments appreciated.



Updated: CF Image Uploader / Resizer with tmt_img.cfc

Decided to get serious (ok... serious'er') about the look and feel of these demo-things I keep playing with. I grabbed a quick css template courtesy of styleshout.com and set up some workspace.

First up - the same ColdFusion Image Resizer demo I posted back in December, with a new skin...
http://www.mredesign.com/demos/tmtImg-Uploader/

Automagic links for http: and mailto: from plain text content

A while back, I built a simple cms system for an article-based site where some of the articles have links and email addresses built in. My client wanted to be able to simply copy and paste the articles into the textarea, and not have to fuss with making each of the links. (that, and I really didn't want to turn her loose with fckeditor in this case... 'just the facts, ma'am")

So, I jumped over to experts-exchange, and within minutes of posting my question, one of the legions of experts in the ColdFusion arena gave me this nice bit of regular expressionism, wrapped up in a nice little function (ok, two functions)

It will find anything starting with http://, www., or http://www, and turn it into a link.   Anything in email format ( something@something.something) gets made into a mailto: link.


========================

<!--- This function creates hyper links from url strings,
and email mailTo links from email addresses --->

<cffunction name="LinkURLs" output="true" returntype="string">

<cfargument name="text" type="string" required="yes">
<!--- Define local variables --->
<cfset var pos=1>
<cfset var subex="">
<cfset var done=false>
<cfset results = arguments.text>

<cfloop condition="not done">

<!--- Perform search --->
<cfset subex=reFind("(http://|http://www|www)(.*?)([[:space:]]|$)", arguments.text, pos, true)>
<!--- Anything matched? --->
<cfif subex.len[1] is 0>
<cfset done=true>
<cfelse>
<cfsavecontent variable="theLink"><a href="http://#replace(mid(text,subex.pos[1],subex.len[1]),'http://','')#">#mid(text,subex.pos[1],subex.len[1])#</a></cfsavecontent>
<cfset results = replace(results,mid(text,subex.pos[1],subex.len[1]),theLink)>
<!--- Reposition start point --->
<cfset pos=subex.pos[1]+subex.len[1]>
</cfif>
</cfloop>

<!--- and return results --->
<cfreturn results>
</cffunction>

<cffunction name="LinkEmails" output="true" returntype="string">

<cfargument name="text" type="string" required="yes">
<!--- Define local variables --->
<cfset var pos=1>
<cfset var subex="">
<cfset var done=false>
<cfset results = arguments.text>

<cfloop condition="not done">

<!--- Perform search --->
<cfset subex=reFind("([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})", arguments.text, pos, true)>
<!--- Anything matched? --->
<cfif subex.len[1] is 0>
<cfset done=true>
<cfelse>
<cfsavecontent variable="theLink"><a href="mailto:#mid(text,subex.pos[1],subex.len[1])#">#mid(text,subex.pos[1],subex.len[1])#</a></cfsavecontent>
<cfset results = replace(results,mid(text,subex.pos[1],subex.len[1]),theLink)>
<!--- Reposition start point --->
<cfset pos=subex.pos[1]+subex.len[1]>
</cfif>
</cfloop>

<!--- and return results --->
<cfreturn results>
</cffunction>

===================

To call the function, I simply used
#linkEmails(linkUrls(recordDescrip))#
where #recordDescrip# is my article text

easy, eh?

Cartweaver Mod: multiple product images, auto photo resizing, mouseover js display

A very nice CartWeaver user contacted me for some help with her product images - basically, she wanted to add more images per product (easier than ever in CW3) and, most importantly, she wanted a way to let her clients upload a single image, and have the thumbnails and other sizes made automatically.

I set up a demo version of the add-on, saving a copy of the modified CW code so I can use it again for my own clients. ( That link shows a default product page with a very basic multiple image javascript display... in theory, the finished product would be much nicer. A demo of the admin is here ( use admin/admin to log in)

I added an automatic uploader / image resizer, and set up her images table in the CartWeaver database to handle 5 images for each product, with 4 sizes for tiny preview, details thumbnail, large image, and zoom.

In the CartWeaver admin, she simply uploads a single image file for each photo slot, and the thumbnails are made on the server (instead of a separate upload slot for each image size). Otherwise, it works and looks exactly like the regular CartWeaver admin.

On the display side, the single results page composes the mouseover image swap display for 1 to 5 mages, whatever is available.

The way this code works, any number of images and any number of sizes for each can be used - and any type of gallery, lightbox, list or display of the images can be populated from the image query.

Updated spring 2008: Now using CFimage for super fast, high quality resizing on the fly with more accurate height/width scaling.

The resizer works with both tall and wide images, with a maximum width and height set in the database for each size of image.

Each image upload slot can have its own set of sizes and max w/h dimensions, so the possibilities are almost endless.

The CW site I was working on was on a CF7 server, so instead of using the onboard CFimage functions in CF8, I went with Massimo Foti's tmt_img.cfc  - so in theory it should work on any server, running any recent version of ColdFusion.

Contact me directly to log in and test the admin on that demo site, or if you are interested in using this code on your own CartWeaver (or other) sites.

Coldfusion Image Resizer w/ tmt_img.cfc

More late night code obsession....

I have had Massimo's tmt_img.cfc at the root of my CF cms, dynamic cfGallery and other apps for quite a while.... but I hadn't ever set it up as a standalone process... until now.

http://mredesign.com/cfdev/UploaderMREdemo/index.cfm


This simple demo lets the user input the thumb and full size widths of their choice, and uploads the original file for safekeeping. Also, any spaces in the filename are replaced with hyphens to avoid troubles later on.

Another thing I have been wanting is dynamic paths... this whole thing runs on CGI variables that get and show the server path and the http url based on the location of the upload page (and a few set folder names, in relative locations). This means you can place it anywhere and it will 'know' where it is with no entry of server or http info.

tmt_img can also crop, get dimensions, and more... but this shows the basic function and it was fairly easy to set up, once I got the syntax right.

EDIT: Files are attached to this post. See the 'download' link below.
You will need a copy of tmt_img... get it here... then unzip my attachment and put the tmt_img file into the 'tags' directory, then upload the works to anwhere on your CF server. It *should* work.  (Then again, it is *almost* 5 am, so anything is possible... )

Powered by BlogCFC version 5.5.005 by Raymond Camden.   Reinit  Admin