Jump to content

[SOLVED] Limit text in an area, and click button to view all?


Recommended Posts

Hello javascript experts, I have never seen a question here that hasn't been solved since you guys know your stuff :)  I am displaying some text from a database, and would like a link where if the user clicks on it will display all of the text.  It would also be great if the link text changes from "view more" to "close" or whatever text when it is opened.  It would be great if the text is limited to um lets say about 6 lines of text, but it would be great if I can easily adjust this value to display more or less text.  Could anyone provide me with a working example please?  Thanks!

I think this is a two step process.

 

The first step would be to process the text server-side (assuming PHP). Using PHP determine what part of the text should be displayed in partial vs. full mode. Then split the text accordingly. The strait-forward approach would be to use number of characters since determining the number of lines would be difficult, if not impossible. Then echo both pieces of text to the page such that they can be controlled via javascript. Assuming you have mutiple pieces of text that would be displayed I would suggest adding an index number to each piece.

 

Here is an example of how the PHP code could look

$index = 1;
$maxLength = 50; //max characters to show for the preview
while ($record = mysql_fetch_assoc($result))
{
    $text = $record['text'];

    //Determin if preview is needed
    $preview = (strlen($text)>$maxLength);

    if ($preview)
    {
        echo "<a href=\"#\" onclick=\"showHide({$index});\" id=\"display_{$index}\">Show</a><br>\n";
    }

    echo "<div id=\"text_{$index}\">\n";
    if ($preview)
    {
        //Preview needed, break out the text on the space before $maxLength

        //Determine the break point
        $tempString = substr($text, 0, $maxLength+1);
        $breakPoint = strrpos($tempString, ' ');
        //Display the text parts
        echo "<span>" . substr($text, 0, $breakPoint) . "</span>";
        echo "<span id=\"ellipse_{$index}\">...</span>";
        echo "<span id=\"full_{$index}\" style=\"display:none;\">" . substr($text, $breakPoint) . "</span>";
    }
    else
    {
        //No preview needed, display entire text string
        echo $text;
    }
    echo "</div><br><br>\n";
    $index++;
}

 

Then use a javascript function to show/hide the full text or the ellipse (plus chang ethe link text)

function showHide(idx)
{
    var fullTextObj = document.getElementById('full_'+idx);
    var ellipseObj = document.getElementById('ellipse_'+idx);
    var linkObj = document.getElementById('display_'+idx);

    if (fullTextObj.style.display != 'inline')
    {
        fullTextObj.style.display = 'inline';
        ellipseObj.style.display = 'none';
        linkObj.innerHTML = 'Hide';
    }
    else
    {
        fullTextObj.style.display = 'none';
        ellipseObj.style.display = 'inline';
        linkObj.innerHTML = 'Show';
    }
    return;
}

 

Here is a fully working page made from the PHP and JavaScript code above

<html>
<head>
<script type="text/javascript">

function showHide(idx)
{
    var fullTextObj = document.getElementById('full_'+idx);
    var ellipseObj = document.getElementById('ellipse_'+idx);
    var linkObj = document.getElementById('display_'+idx);

    if (fullTextObj.style.display != 'inline')
    {
        fullTextObj.style.display = 'inline';
        ellipseObj.style.display = 'none';
        linkObj.innerHTML = 'Hide';
    }
    else
    {
        fullTextObj.style.display = 'none';
        ellipseObj.style.display = 'inline';
        linkObj.innerHTML = 'Show';
    }
    return;
}
</script>
</head>

<body>

<a href="#" onclick="showHide(1);" id="display_1">Show All</a><br>
<div id="text_1">
<span>FORT MYERS, Fla. – A passenger landed a</span><span id="ellipse_1">...</span><span id="full_1" style="display:none;"> twin-engine plane in Florida after the pilot died in flight with a total of six people on board. Federal Aviation Administration officials say the pilot died after takeoff from an airport in Naples on Sunday. It was on autopilot and climbing toward 10,000 feet when the pilot died.</span></div><br><br>

<a href="#" onclick="showHide(2);" id="display_2">Show All</a><br>
<div id="text_2">
<span>SPRINGDALE, Ark. - Josh and Anna Duggar are</span><span id="ellipse_2">...</span><span id="full_2" style="display:none;"> following in the family tradition. Josh, the eldest of Michelle and Jim Bob Duggar's 18 kids, announced Monday that he and new bride Anna were about to start their own brood. The couple, who's been married since September, said Anna Duggar is due Oct. 18</span></div><br><br>

<a href="#" onclick="showHide(3);" id="display_3">Show All</a><br>
<div id="text_3">
<span>BANGKOK - Thousands of troops fired warning shots</span><span id="ellipse_3">...</span><span id="full_3" style="display:none;"> and tear gas to turn back rampaging anti-government protesters Monday night, forcing retreating demonstrators into one neighborhood where a clash with residents left two people dead</span></div><br><br>

</body>
</html>

Ok an update, it works great, however the problem is that if the list is long and creates a vertical scrollbar on your browser, if you click on show all or hide it will direct to the top of the page due to the # in the url.  I know a way around that is to add the ID to the # so that the browser will scroll do that part, but that will make the browser jumpy so is there a way to make it appear and disappear without moving the browser up and down?  Thanks! :)

 

EDIT

 

Haha well nevermind, as a test I went ahead and tried to add the ID to the # and the browser doesn't move so it works perfectly thanks a lot!

Ok sorry I jumped the gun, the others are right in that if there is html displayed on the page it messes up the output when that span cuts off the text.  How about a simplier way that uses CSS to cut off the text somehow and use javascript to turn off that CSS effect?  If you could provide a full working version that would be great.  I do not need the php code I am good with php but suck with javascript.  Thanks!

Um, that is a CSS effect. CSS is not programatical; you can't use it to logically display a certain number of characters/words. You could use javascript to change the "height" of the container div so it only takes up so much room. But, the problem there is that you can't control exactly how each browser will display the page. So, you might only have 2 lines of text show in one browser, whereas in a different browser you woudl get two lines and the top half of the third line.

 

That would be the simplest approach though. To keep the HTML formatting and use the method I provided can be done, but would involve more code to handle the conversion.

Ok thanks anyway, your example works but for the complex coding I am using it doesn't really integrate well even though I know it is possible.  Actually I meant that I knew a CSS designer and when he mistakenly made a width for a row that  cutoff the text, I asked him to make it so the text wraps instead of getting cutoff.  I was thinking of perhaps using that method purposely(whatever it is) which is what I meant when I suggested a CSS attribute.  It was a set width and any text or data that went beyond that width of the CSS field was stripped off, not sure how it was done but it was very simple since I remember looking at the code when I was trying to fix it.

That was what I was referring to, but as I said it won't look consistent on every browser.

 

<HTML>
<head>
<script>
function showHide(idx)
{
    var textDiv = document.getElementById('text_'+idx);
    var linkObj = document.getElementById('display_'+idx);

    textDiv.style.overflow = (textDiv.style.overflow != 'visible') ? 'visible' : 'hidden';
    linkObj.innerHTML = (textDiv.style.overflow != 'visible') ? 'Show' : 'Hide';
    return;
}
</script>
</head>

<body>

<a href="#" onclick="showHide(1);" id="display_1">Show</a><br>
<div id="text_1" style="width:250px;height:50px;overflow:hidden;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Vestibulum suscipit congue diam. Vivamus nisi. Curabitur 
augue libero, hendrerit vel, porttitor id, bibendum ut, 
massa. Maecenas porta lectus vitae erat. Praesent quam. 
Nunc lacus augue, sollicitudin ac, mattis ut, consectetur 
eget, urna. Mauris tortor dolor, hendrerit id, sollicitudin 
ut, egestas vitae, lacus. Nulla sed sem. Pellentesque 
scelerisque erat id nisl. Morbi sed purus in velit volutpat 
tempor. Mauris a metus. Suspendisse eleifend malesuada enim.</div>

</body>
</html>

Ah crap!  Ok I love this new version, however I have the div inside an html table row, and when I click show all the text overlaps the whole table instead of stretching the table.  Any way around that?  If not then perhaps at least be able to give that background a solid color so it isn't transparent against the background?

Or if those two ideas do not work, I notice that you have javascript assigned to the div only, if it can be assigned to a <td> table, perhaps that would work?  Your first javascript function allowed me to assign the id to the table row instead of a div.

Or if those two ideas do not work, I notice that you have javascript assigned to the div only, if it can be assigned to a <td> table, perhaps that would work?

 

Why don't you just try it?

 

Edit: this is a browser compatability issue. Works fine in IE, but not in FF. You'll need to experiment with the format to make it work in both.

Ok an update, it works great, however the problem is that if the list is long and creates a vertical scrollbar on your browser, if you click on show all or hide it will direct to the top of the page due to the # in the url.  I know a way around that is to add the ID to the # so that the browser will scroll do that part, but that will make the browser jumpy so is there a way to make it appear and disappear without moving the browser up and down?  Thanks! :)

 

Just to add...

 

You don't need to add a # to your URL to escape this. There's several ways...

 

You can call the JavaScript from the 'href':

 

<a href="javascript:showHide(1);" id="display_1">

 

But that displays the JavaScript in the status bar and some people don't like that.

 

You could have the 'onclick' event return false, which would stop the browser loading whatever is in the 'href':

 

<a href="#" onclick="showHide(1); return:false;" id="display_1">

 

Or you could use void(0); instead of #...

 

<a href="javascript:void(0);" onclick="showHide(1);" id="display_1">

 

Adam!

Or if those two ideas do not work, I notice that you have javascript assigned to the div only, if it can be assigned to a <td> table, perhaps that would work?

 

Why don't you just try it?

 

Edit: this is a browser compatability issue. Works fine in IE, but not in FF. You'll need to experiment with the format to make it work in both.

 

Yes I know the problem I am asking for the solution.  Yes I did try it and it didn't work which is why I asked.  I tried everything but I just do not understand javascript enough to make it work. 

Sorry, if I was a bit harsh, but when someone asks "will this work" it appears they only want someone to provide a solution to them and are unwilling to be part of the solution by participating in the process. I am only here to help people that want to help themselves. Not saying that is your attitude, but that is how I perceive that type of statement.

 

In any event, this is no longer a javascript issue. The JavaScript is fine. This is a CSS issue. You need to find a way to construct the page such that you can change the CSS properties to display/hide the partial content that is cross-browser compliant.

Sorry I do not know how to do it.  When I say "Perhaps that would work" I mean that I do not know how to do it and only suggesting alternative work arounds on how to acheive the same task.  If I were to reword my question, I would ask "Could you please provide me with the javascript code to resize the height of the table row when the Show link is clicked please?"

Nevermind a friend of mine was able to get it to work by using:

 

function showHide(idx)

{

var textDiv = document.getElementById('text_'+idx);

var linkObj = document.getElementById('display_'+idx);

 

textDiv.style.height = (textDiv.style.height != 'auto') ? 'auto' : '50px';

linkObj.innerHTML = (textDiv.style.height != 'auto') ? 'Show All' : 'Hide Again';

 

return;

}

 

Thanks again for all of your help :)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.