Useful Javascript Snippets

Get the current URL

var my_url = document.URL;

Get the root URL

var my_root_url = location.protocol + '//' + location.host;

Get a Hash Parameter from a URL

var my_parameter = document.URL.split('#')[1];

Redirect a page to another page

window.location.href = 'http://www.yourpageofchoice.com';

text-overflow: How to truncate long texts using CSS

Using a back-end language to cut long strings is not always the best solution. Consider that a variable amount of space (on desktop the space would be bigger; on mobile devices it would be smaller) needs to be filled with some text. PHP, Ruby etc. will be ignorant of the actual size of the space that will be filled with text, so we need something on the front-end. Of course, JavaScript comes to mind, but there is an (even) easier way.

Using a CSS property text-overflow it is possible to cut the text exactly where you need it, when you need it. Example:

<div class="cut-the-text">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
.cut-the-text {
    width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

text-overflow is well supported by all recent web browsers, but even on ancient ones like Internet Explorer 6 the text that goes beyond the limit is at least hidden. Anyway, the result is this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Just remember that beside text-overflow you have to specify the size of the box, no wrap for the text, and to hide whatever goes beyond the limit of the container.