Adapting @bazmegakapa's Ellipsis Script for Inline Use



I'm working on adapting @bazmegakapa's script (explained here) to work using inline tags:

<script type="javascript">
var p=$('#fos p');
var divh=$('#fos').height();
while ($(p).outerHeight()>divh) {
$(p).text(function (index, text) {
    return text.replace(/\W*\s(\S)*$/, '...');

The code (which I've commented out in this JsFiddle) works great until it's placed inside the tags. Any ideas on what could be causing the breakdown? I think @bazmegakapa's script is brilliant, mainly because it's so much shorter and more manageable than other ellipsis plugins out there, and I'd love to figure out how to get over this hurdle and actually implement it in my project. I'm still very much a javascript novice so help from the guys at SO would be great.


Problem courtesy of: Marcatectura


Unless I'm missing something, I'm almost positive it's because of how you're expecting things done in a fiddle. You currently have the fiddle's Javascript to be run onLoad, which means the DOM will be ready by that point. In your case of inline Javascript, you have it printed in the HTML above the elements that are targeted. HTML is parsed from top to bottom, so the script is run before the elements are even known. When you try to manipulate things that don't "exist" yet, it won't work. So you either need to put your inline script below your main HTML, or use something like:

$(document).ready(function () {
    // Your code here

anywhere on the page.

It might've helped to check your browser's console, but things might not have failed in your situation because jQuery doesn't bomb if elements aren't found - it'll just return correct things, like undefined possibly, so that your other logic would probably fail...just not bomb. Javascript would bomb if you tried document.getElementById("asdf").value if there was no element with an id of "asdf". But it wouldn't bomb if you used $("#asdf").val() - it would just returned undefined or something.

Quick note: you don't need to wrap p like $(p) - it's already a jQuery object, so you can call jQuery methods on plain p.


It seemed like the problem was the fact that the <script> tag needed to have the type "text/javascript", not just "javascript". Here's the fiddle that has your working code:

Solution courtesy of: Ian


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.