views:

89

answers:

2

I am looking for a way to limit the amount of characters displayed in a heading using jquery. Essentially the heading is retreived from the database but I only want the results to display on one line of a set width so would like to limit the output or abbreviate it to stop the images below being pushed too far down.

The following Live example should show everything that I mean, scroll down a bit and you will see images titles that are 2 or 3 lines long.

Hope someone can help!!!!

+2  A: 

Dan, I'm a bit confused about what you're looking for, but it sounds like you want some code to truncate the character length of a certain field. I noticed that you tagged this question PHP -- it'd probably be better to handle it server-side. However, if you're set on using Jquery, there's probably an easy way to do it.

The key thing to figure out is, what pattern are you going to use to identify the field tags within the page (ie. what kind of jquery selector will you write to select the tags you want)? Once that's down, javascript's .slice() function will achieve what you want.

So here's an example. Based on the page you linked, I'm going to say we could select your field output by selecting any span tag that is a direct child of an anchor tag that is a direct child of a list item.

$('li > a > span')

Then from there we can grab the contents of the span, check the width, and truncate if we need to.

(untested, but gives the idea)

<script type="text/javascript">

    var MAX_TITLE_LENGTH = 75;

    // on page load...
    $(function() {
     truncateImageTitles();  
    });

    function truncateImageTitles() {
     $('li > a > span').each(
      if (this.text().length > MAX_TITLE_LENGTH)
       this.text(this.text().slice(0,MAX_TITLE_LENGTH));
     );
    }

</script>
T. Stone
+1  A: 

Trim with PHP would work, as T. Stone said, but you'd have to figure out if you want to trim the front end of a title or the back end. Lots of examples. I use trim with titles on my own wordpress site. This trims the first 13 characters from a post title, in place of the_title.

<?php $mytitle = get_the_title(); $mytitle = substr($mytitle,13); echo $mytitle; ?>

songdogtech
is there a way of using this just to limit the number of characters displayed? I tried but failed to find an example anywhere.
DanC
I have ended up going down the route of using php to shorten the text thanks for this
DanC