Can I select an nth css column? - javascript

I have a div with 4 css columns and I'd like to select the 3rd and 4th column to make the text slightly darker because I don't have a good contrast between the text and the background-image. Is this possible? I can accept any css or js solution.
Here's the demo.
--EDIT--
It seems that it's not possible to find a selector for pseudo blocks (if I may say) however I still need to figure out a way of creating responsive blocks (like columns) that will split the text equally (in width) whenever the browser is resized.

As far as I know you won't be able to apply styles to the columns.
What you can try however is to use a gradient as a background to make columns 3 and 4 another color.
#columns {
background: -webkit-linear-gradient(left, rgba(0,0,0,0) 50%, blue 50%);
/*... appropriate css for other browser engines*/
}
updated jsFiddle
updated with all browser support gradient
-- EDIT --
Since the intention was actually to change the text color and not the background for the third and fourth column some additional thoughts.
For now it doesn't seem possible to apply styles to single columns inside a container. One possible workaround to change the text color in specific columns is to put every word inside a span. Then to use JavaScript to iterate over the words and determine where a new column starts. Assigning the first element in the third column a new class would make it possible to style this and the following siblings with a different text color.
Because the container is part of a responsive layout and could change in size, the script would have to be re-run on the resize event to account for changing column widths.
The purpose of the code example is to outline how to implement such a solution and should be improved for use in an actual application (e.g. the spans are being re-created every time styleCols is run, lots of console output...).
JavaScript
function styleCols() {
// get #columns
var columns = document.getElementById('columns');
// split the text into words
var words = columns.innerText.split(' ');
// remove the text from #columns
columns.innerText = '';
// readd the text to #columns with one span per word
var spans = []
for (var i=0;i<words.length;i++) {
var span = document.createElement('span');
span.innerText = words[i] + ' ';
spans.push(span);
columns.appendChild(span);
}
// offset of the previous word
var prev = null;
// offset of the column
var colStart = null;
// number of the column
var colCount = 0;
// first element with a specific offset
var firsts = [];
// loop through the spans
for (var i=0;i<spans.length;i++) {
var first = false;
var oL = spans[i].offsetLeft;
console.info(spans[i].innerText, oL);
// test if this is the first span with this offset
if (firsts[oL] === undefined) {
console.info('-- first');
// add span to firsts
firsts[oL] = spans[i];
first = true;
}
// if the offset is smaller or equal to the previous offset this
// is a new line
// if the offset is also greater than the column offset we are in
// (the second row of) a new column
if ((prev === null || oL <= prev) && (colStart === null || oL > colStart)) {
console.info('-- col++', colCount + 1);
// update the column offset
colStart = oL;
// raise the column count
colCount++;
}
// if we have reached the third column
if (colCount == 3) {
// add our new class to the first span with the column offset
// (this is the first span in the current column
firsts[oL].classList.add('first-in-col3');
return;
}
// update prev to reflect the current offset
prev = oL;
}
}
styleCols();
addEventListener('resize', styleCols, false);
CSS
.first-in-col3, .first-in-col3~span {
color: red;
}
jsFiddle

For now i dont think you can do it, here https://bugzilla.mozilla.org/show_bug.cgi?id=371323 is an open bug/request for a feature, you can vote for it. Till then you can consider using tables.
P.S.
Give Up and Use Tables just for the sake of humor :)

The only solution i could think would be a background with your desired color for middle column, customize it for size and position so it goes behind your middle columns and make background-clip:text. Unfortunately it is not supported very well.
You can find more explenations here.

Related

How to get column number based on text

I've divided the Html content (which belongs to an eBook) into multiple columns using the following steps.
1) I've added the HTML inside the content which is inside a container.
<body>
<div id="container">
<div id="content">
BOOK HTML CONTENT
<span id="endMarker"></span>
</div>
</div>
</body>
2) Next, I've added the CSS style of the content and the container as shown below:
#container {
width: 240px;
overflow: hidden;
background-color: yellow;
}
#content {
position: relative;
height: 30em;
-moz-column-width: 240px;
-webkit-column-width: 240px;
column-width: 240px;
-moz-column-gap: 10px;
-webkit-column-gap: 10px;
column-gap: 10px;
}
Now, I want to find the column number of the text (or a line) using javascript?
There are other questions on SO that show how to get the column number based on the id. In my case, there are no id's. The only thing available is the text (or line) and I need to get the column number by searching through the Html content.
Currently, I've two "solutions" to get the column number but they are incomplete.
1) I can find whether the text exists or not by using window.find(text) after that I'm not sure what I've to do.
2) Another option is to add <span> with an id to every line temporarily and remove it. Once added, I can get the total column count up to that line (like shown below).
columnCount = Math.floor($('#marker').position().left/(columnWidth + columnGap));
This will give a wrong number if the line is extended to another column.
The second solution is tricky and book content is huge. I don't think this is the best way to get the column number. I'm looking for a simpler solution.
Try this, made a workable version for your question.
jsfiddle link
Although OP didn't tag question with jQuery, but actually used jQuery inside the question, I use it too for cleaner code. (and fit the question)
What I do in this example:
Make a long content cross several pages to visualize paging (with css: column-width).
Click on previous / next to browse pages.
Input and click 'find' button, make found texts highlighted.
List all columns (pages) found with input text.
Click on the link and jump to column with searched text.
In detail I made temporary DOM elements to calculate column, and remove them right after to keep DOM tree clean.
2017/6/1 Edited: Added highlight color for searched text.
$('#find').click( () => {
var text = $('#findtext').val();
var columns = [];
var doms = [];
while (window.find(text, false)) {
var sel = window.getSelection();
if (sel) {
var range = sel.getRangeAt(0);
var el = document.createElement("span");
var frag = document.createDocumentFragment();
frag.appendChild(el);
range.insertNode(frag);
columns.push(Math.floor(el.offsetLeft/(_columnWidth + _columnGap)));
doms.push(el);
}
}
/// distinct
columns = columns.filter( (value, index, self) => self.indexOf(value) === index );
/// show result
$("#foundlist").empty();
for (var i=0; i<columns.length; i++)
$("#foundlist").append(`<li>Found in Column ${columns[i]+1}</li>`);
/// remove dom. keep dom tree clean
while (doms.length > 0) {
var dom = doms.pop();
dom.parentNode.removeChild(dom);
}
});
Instead of adding a <span> beforehand, you could temporarily insert it at the point where you find your text and remove it again as soon as you have identified the position.
The key is how to find text in a long document. The interface for this task is the TreeWalker, that can iterate through every text node in a DOM subtree.
How to insert an element in the middle of a text node was copied from here.
Your question did not state it, but used jQuery as a dependency. This solution is using only the vanilla DOM interfaces.
var columnWidth = 240,
columnGap = 10;
function getColumn(text) {
// the subtree to search in
var root = document.getElementById('content');
// define an iterator that only searches in text nodes
var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
// filter the text nodes to those containing the search text
acceptNode: function(node) {
if ( node.data.includes(text) ) {
return NodeFilter.FILTER_ACCEPT;
}
}
});
// look if there is a result
if (treeWalker.nextNode()) {
var node = treeWalker.currentNode;
// get start index of found text
var index = node.data.indexOf(text);
// and split into two nodes, referencing the second part
var foundTextNode = node.splitText(index);
// define an empty inline element
var span = document.createElement('span');
// insert it between the two text nodes
var elem = node.parentElement;
elem.insertBefore(span, foundTextNode);
// compute the column from the position of the element
// you might have to account for margins here
var x = span.getBoundingClientRect().left - root.getBoundingClientRect().left;
var column = Math.floor(x / (columnWidth + columnGap));
// restore previous state
elem.removeChild(span);
elem.normalize();
return column;
} else {
// no result
return false;
}
}
The obvious limitation to this solution is that it will not find text that is spanning multiple nodes. So, if you have a text fragment
<p>The quick brown fox <em>jumps</em> over the lazy dog.</p>
a search for 'fox jumps over' will not find this sentence.

change rows depending on the ordernumber in database

I'm creating for my education-project a pizza-ordering website. With the help of the stackoverflow-community I've achieved already a lot - so thank you! But now I'm stuck and can't find any working solution to my problem.
Question
How can I change the row color alternating (white / grey / white / grey ...) depending on the ordernumber in the database(mysqli)? The ordernumber can be in more than one row, so I can not simple change the color row by row.
I've tried with jquery, but this works only if the ordering numbers remain always in the list (even/odd) ... if an order is cancelled, then it doesn't works anymore (see image with missing ordernumber 7)
Here is the code in jquery:
$(document).ready(function() {
var check = 0;
for(var i =0; i<= $("tr").length;i++){
$("tr").each(function(){
if(parseInt($(this).find("#bestnr").text())==check){
if(check%2 == 0){
$(this).css("background-color","white");
}else{
$(this).css("background-color","#DCDCDC");
}
}
});
check +=1;
}
});
Any ideas? Thanks for your help!
Since you're working with JQuery, something like this ought to do the trick - explanations in code comments.
$(document).ready(function() {
// define the initial "previous order id" as 0 assuming
// there will never be an order with id 0
var previousOrderId = 0;
var previousBgColour = '#dcdcdc';
var thisBgColour;
// loop the table rows
$("tr").each(function() {
// determine "this" row id (assuming bestnr is short for bestelnummer)
// and that the text in that table cell *is* the order number
// I've changed this to a class as an id HAS to be unique
// you'll need to update your code to accommodate
var thisOrderId = parseInt($(this).find(".bestnr").text());
// define the background colour based on whether the order id has changed
// if it has change it
if(thisOrderId != previousOrderId) {
thisBgColour = previousBgColour == '#dcdcdc' ? '#ffffff' : '#dcdcdc';
previousBgColour = thisBgColour;
}
else {
thisBgColour = previousBgColour;
}
$(this).css({'background-color' : thisBgColour});
//update the previousOrderId to this id
previousOrderId = thisOrderId;
});
});
You're basically storing the previous order id and comparing it to the current order id - if the order id hasn't changed it'll use the previous background colour, if it has it'll flipflop it to the alternate colour.
If it is just alternating colors, you can use CSS directly and not worry about anything else:
tr:nth-child(odd) {
background-color:white;
}
tr:nth-child(even) {
background-color:#DCDCDC;
}
If this is somehow dependent on logic from the backend, we can look at adding a class in jQuery and adding colors to this class via CSS

Prevent overlapping while positioning element at height of another

Inside a long text document there are some "special words" to which I want to display notes/annotations on the left. Each note should be as close as possible to the level of the word it is refering to.
The HTML for this is organised in a table. Each paragraph is one table row, consisting on annotations in the left and main text in the right table column. the notes/annotations go to the left. However, unfortunately, there are also some other elements/text nodes in there.
<table>
<tr>
<td class"comments">
<span id="dog" class="note">Note for dog</span>
<span id="cat" class="note">Note for cat</span>
<span id="horse" class="note">Note for horse</span>
Somethin else than a note.
</td>
<td>[Text...]
<span id="dog_anchor" class="reference">Dog</span>
<span id="cat_anchor" class="reference">Cat</span>
<span id="horse_anchor" class="reference">Horse</span>
[Text...]
</td>
</tr>
</table>
It's easy to change the "note"-spans to absolute and positioned them on the level of their reference:
$('span[class*="note"]').each(function (index, value) {
var my_id = $(this).attr('id');
var element_ref = document.getElementById(my_id + "_anchor"); // get reference element
var pos_of_ref = element_ref.offsetTop; // get position of reference element
$(this).css('top', pos_of_ref); // set own position to position of reference element
});
However, life is not so simple here. Since there could be a lot of reference words in one line (while on other there are none of them) I need a rather sophisticated way to distribute the notes so that they are as close as possible to their references without destroying anything in the layout (e.g. being placed outside of the table cell or overlapping with other elements).
Furthermore, the height of the table cells could not be changed. Elements which are not notes must not be moved. (Note elements are always in the order they appear in the main text. That's not the problem.)
So, I need an algorithm like this:
Take all notes in a table cell.
Analyse blank space in that table cell: Which areas are blank, which are blocked?
Distribute the notes in the table cell so that each note is as close as possible to its reference word without any element colliding with any other item in the table cell.
Is there any fast and elegant way to do this without having to write hundreds of lines of code?
Here is a JSfiddle: https://jsfiddle.net/5vLsrLa7/7/
[Update on suggested solutions]
Simply setting the position of the side notes to relative or just moving notes down won't work, because in this case, the side notes will just go downwards relative to their desired position which results in side notes way to far from their reference words. After all, for a neat solution I need to side notes spread in both directions: up and down.
[Update]
The expected result would be something like this:
As you see, it's never possible to place all the notes at the height of their reference. However, the free space is used to position them as close as possible, moving them up and down.
I changed move() function as follows:
function move(){
var prev_offset = 0;
$('span.note').each(function (index, value){
var my_id = $(this).attr('id');
var element_ref = document.getElementById(my_id + "_anchor"); // get reference element
var pos_of_ref = element_ref.offsetTop; // get position of reference element
if (prev_offset >= pos_of_ref){
pos_of_ref = prev_offset + 30;
}
$(this).css('top', pos_of_ref); // set own position to position of reference element
prev_offset = pos_of_ref;
});
}
I'm assuming that your element's notes will be in the correct order always
I made some changes to your javascript:
function move()
{
var arrayTops = [];
$('span[class*="note"]').each(function (index, value)
{
var my_id = $(this).attr('id');
var element_ref = document.getElementById(my_id + "_anchor"); // get reference element
var pos_of_ref = element_ref.offsetTop; // get position of reference element
pos_of_ref = getCorrectTopPosition(arrayTops,pos_of_ref);
$(this).css('top', pos_of_ref); // set own position to position of reference element
arrayTops.push(pos_of_ref);
});
}
function getCorrectTopPosition(arrayTops, newOffsetTop)
{
var notesHeight = 18;
var marginBetweenNotes = 3;
var noteheightWithMargin = notesHeight + marginBetweenNotes;
var lastTop = arrayTops[arrayTops.length-1];
if((lastTop + noteheightWithMargin) >= newOffsetTop)
return lastTop + noteheightWithMargin;
return newOffsetTop;
}
Thanks for all the answers and comments. I was finally able to figure out at least a partical solution which works for me.
First of all, I was able to restructure my HTML, so that now the "non note" elements in the left td are all wrapped in one div which is now the very first element in the td. So, now there is nothing between notes, maybe something before them.
The idea of my solution is not to give the notes a new position but to set a new margin-top to each of them. The maximum amount of margin-top values to be added within a table cell is calculated before (called "roaming space"), being the space below the last note in a table cell. Thus, the table layout is not destroyed.
function move_notes() {
$('tr').each(function (index, value) {
var current_tr = $(this);
var last_app_element_in_tr = $(this).find('span[class*="note"]').last();
if ($(last_app_element_in_tr).length) /* Only preceed if there is at least one note in the table row */ {
var tr_height = $(this).height();
var tr_offset = $(this).offset().top;
var bottom_of_tr = tr_offset + tr_height;
var bottom_of_last_app_el = $(last_app_element_in_tr).offset().top + $(last_app_element_in_tr).height();
var roaming_space = bottom_of_tr - bottom_of_last_app_el; // Calculate the amount of pixels which are "free": The space below the very last note element
$(this).find('span[class*="note"]').each(function (index, value) {
var my_id = $(this).attr('id');
var element_ref = $(current_tr).find("#" + my_id + "_anchor");
var pos_of_ref = $(element_ref).offset().top;
var new_margin_top;
/* Calculate the new margin top: The note should be at the same level as the reference element.
When loading, in most cases the notes are placed too high. So, the margin top of the note should equal
the amount of pixels which the note is "too high". So we subtract the height and the offset of the element
before the current note from the offset of the reference. */
var previous_note = $(this).prev();
// not just notes, but every element in the td in general
if (! $(previous_note).length) // If there is no previous_note, than take the table cell
{
closest_td = $(this).closest("td");
new_margin_top = pos_of_ref - $(closest_td).offset().top;
} else {
new_margin_top = pos_of_ref - $(previous_note).offset().top - $(previous_note).height();
}
var difference_to_previous = $(this).css('marginTop').replace(/[^-\d\.]/g, '') - new_margin_top; // Calculate the difference between the old and the new margin top
if (new_margin_top > 0 && Math.abs(difference_to_previous) > 2) // Only move, if the new margin is greater than zero (no negative margins!) if the difference is greater than 2px (thus preventing ugly "micro moving".
{
var new_roaming_space = roaming_space - difference_to_previous;
if (new_roaming_space > 0) /* if there is still room to move */ {
var margin_top_ready = new_margin_top + "px";
$(this).css('margin-top', margin_top_ready);
roaming_space = new_roaming_space;
} else /* If there is no more space to move: */ {
var margin_top_ready = roaming_space + "px"; // take the rest of the "roaming space" left as margin top
$(this).css('margin-top', margin_top_ready);
return false; // Stop the execution because there is nothing left to do.
}
}
});
}
});
}
window.onload = function () {
move_notes();
};
$(window).resize(function () {
move_notes();
});
As you will notice, one of my main concerns is still not addressed: Notes are only moved down, never up. Because of various problems with my real world webpage I didn't implement that yet. However, an algorith could be something like: If the new margin top is greater than the height of the current note and the difference between the offet of the current note anchor and the following note anchor is less than the height of the current note, than subtract the height of the current note from the new margin.
Still, two problems remain:
If the window is maximized or quickly resized from a rather thin width to a greater width, the adjustment of the note positions won't work. I don't know why.
The performance could be better. As a user, you can see the notes jump down. (Because of strange and unpredictable behaviour in Firefox, I had to move the event handler from document.ready to window.onload)

Fullcalendar.io: how to display one event per line in agendaWeek then mix all in one?

I use Fullcalendar.io v2
In my agendaWeek mod I have events and all of them are displayed on one line in day square. So, more events I have, then thiner event blocks.
How can I show one event per line? Like in month mod. And more events I have, then higher day block will me (height). Perhaps, it is hard to use functions like eventRender, because if you inspect .fs-event element (web developer tool), you will see event block uses position:absolute;top:300px;left:33%... so I don't know what to do.
I want something like this:
I was stuck with that problem too, it is very difficult because the plugin compose the calendar in an odd way, using some tables and locating the events with dynamically with a position absolute and varying the css top property.
However i found a generic solution that works very good. First i will show you the code, and them i will explain what exactly the code does.
I use the option eventAfterAllRender of the fullCalendar. This is an example working.
I use moment for manage time and i assume the id of the fullCalendar html element is 'Calendar'.
eventAfterAllRender: function() {
// define static values, use this values to vary the event item height
var defaultItemHeight = 25;
var defaultEventItemHeight = 18;
// ...
// find all rows and define a function to select one row with an specific time
var rows = [];
$('div.fc-slats > table > tbody > tr[data-time]').each(function() {
rows.push($(this));
});
var rowIndex = 0;
var getRowElement = function(time) {
while (rowIndex < rows.length && moment(rows[rowIndex].attr('data-time'), ['HH:mm:ss']) <= time) {
rowIndex++;
}
var selectedIndex = rowIndex - 1;
return selectedIndex >= 0 ? rows[selectedIndex] : null;
};
// reorder events items position and increment row height when is necessary
$('div.fc-content-col > div.fc-event-container').each(function() { // for-each week column
var accumulator = 0;
var previousRowElement = null;
$(this).find('> a.fc-time-grid-event.fc-v-event.fc-event.fc-start.fc-end').each(function() { // for-each event on week column
// select the current event time and its row
var currentEventTime = moment($(this).find('> div.fc-content > div.fc-time').attr('data-full'), ['h:mm A']);
var currentEventRowElement = getRowElement(currentEventTime);
// the current row has to more than one item
if (currentEventRowElement === previousRowElement) {
accumulator++;
// move down the event (with margin-top prop. IT HAS TO BE THAT PROPERTY TO AVOID CONFLICTS WITH FullCalendar BEHAVIOR)
$(this).css('margin-top', '+=' + (accumulator * defaultItemHeight).toString() + 'px');
// increse the heigth of current row if it overcome its current max-items
var maxItemsOnRow = currentEventRowElement.attr('data-max-items') || 1;
if (accumulator >= maxItemsOnRow) {
currentEventRowElement.attr('data-max-items', accumulator + 1);
currentEventRowElement.css('height', '+=' + defaultItemHeight.toString() + 'px');
}
} else {
// reset count
rowIndex = 0;
accumulator = 0;
}
// set default styles for event item and update previosRow
$(this).css('left', '0');
$(this).css('right', '7px');
$(this).css('height', defaultEventItemHeight.toString() + 'px');
$(this).css('margin-right', '0');
previousRowElement = currentEventRowElement;
});
});
// this is used for re-paint the calendar
$('#calendar').fullCalendar('option', 'aspectRatio', $('#calendar').fullCalendar('option', 'aspectRatio'));
}
How the code works:
First i found all tr elements that are the rows of my calendar (note that they contains an attribute with its owns time).
Later I iterate for each column and get, for each one, its events items. Each event item is an anchor element with some inner child with the date as an attribute data-full.
From the event i peek what should be its row, and in that row if there are more than one item, then increase the position where the event item should be located. I use for that the margin-top property because this property is not used or readjust by the plugin (don't use top property).
In the row i set a data attribute to take the max amount of events that has any column of that row. With that, i can calculate if the row must be increase its height or not.
Well, this is basically what the codes does. If you have some question please do-it.
You can add a class to your events and try to customize this events with CSS
As an example you can use style
.test {
width: 100%;
height: auto;
position: relative !important;
left: 0% !important;
margin-right: 0% !important;
}
and event like this:
{
title: 'Lunch',
start: '2014-06-09T10:30:00',
className: 'test'
},
Look on this Fiddle if this is what you want to achieve
Also with a little bit workaround you can use eventAfterRender callback to adjust height of specific row. But this is not very safe solution and it requires some tuning:
eventAfterRender: function( event, element, view ) {
var row = $(".fc-slats tr:contains('"+ moment(event.start).format('ha') + "')");
if (moment(event.start).format('mm') != '00')
{
row = row.next();
}
row.height(element.height()+row.height());
}
https://jsfiddle.net/m5uupf9x/3/
I also faced the same issue and while Alexander's answer is great, i had performance issues with it as it does lot of DOM manipulation. I have about 2000-3000 events per week and became unusable in browsers like Firefox, IE etc. Therefore adapting Alexander's answer and minimizing DOM manipulation came up with following solution.
variables
var itemsOnSlot = {}; // counter to save number of events in same time slot
var maxItemsOnRow = {}; // counter to save max number of events in row
utilize eventRender and eventAfterAllRender callbacks
eventRender: function(event, element, view){
// for each event, margin top and other css attributes are changed to stack events on top of each other
if(!(event.start in itemsOnSlot)){ // if itemsOnSlot has no index with current event's start time
itemsOnSlot[event.start] = 1; // create index and set count to 1
$(element).addClass('slot-attributes'); // add css to change the event style
}else{ // if itemsOnSlot already has a index with current event's start time
itemsOnSlot[event.start] += 1; // increase counter by 1
// change margin top to stack events on top of each other and add css to change the event style
$(element).css('cssText','margin-top:'+(itemsOnSlot[event.start]*18)+'px !important;').addClass('slot-attributes');
}
},
eventAfterAllRender: function(view) {
// this loop is run to get the max number of events per row
for(var start in itemsOnSlot){ // for all the timeslots with events in them
var time = start.substr(16,8); // extract required time format from index - eg. 14:00:00
if(!(time in maxItemsOnRow)){ // if maxItemsOnRow has no index with current time
maxItemsOnRow[time] = itemsOnSlot[start]; // create index and set count to current day's number of events in this time slot
}else{ // if maxItemsOnRow already has a index with current time
if(itemsOnSlot[start] > maxItemsOnRow[time]){ // if current day's number of events in this time slot are greater than existing number
maxItemsOnRow[time] = itemsOnSlot[start]; // replace current time's number of slots
}
}
}
// change height of each row using values from maxItemsOnRow
$('div.fc-slats > table> tbody > tr[data-time]').each(function() { // for all rows in calendar
var time = $(this).attr('data-time'); // get time of each row
if(time in maxItemsOnRow){ // if current row's time is in maxItemsOnRow
$(this).css('cssText','height:'+(maxItemsOnRow[time]*18)+'px !important;'); // change the height of the row to contain max items in row
}else{ // if current row's time is not in maxItemsOnRow (no events in current time slot)
$(this).css('cssText','display: none !important;'); // hide timeslot
}
});
// repaint the calendar with new dimensions
$('#calendar').fullCalendar('option', 'aspectRatio', $('#calendar').fullCalendar('option', 'aspectRatio'));
itemsOnSlot = {}; // reset variables
maxItemsOnRow = {}; // reset variables
},
CSS
.slot-attributes {
left: 4px !important;
right: 3px !important;
height: 15px !important;
margin-right: 0 !important;
}

JavaScript - Visible Text of a DIV

----------------------------------------------------
| This is my text inside a div and I want the overf|low of the text to be cut
----------------------------------------------------
Please note that I want the overflow to be removed, so the CSS ellipsis property would not work for me. So basically, I want that the text above to appear like this:
----------------------------------------------------
| This is my text inside a div and I want the overf|
----------------------------------------------------
How is this possible with pure JavaScript?
EDIT
I need a JavaScript function to crop the text because I need to count the characters of the visible text.
Okay, I didn't see the addendum to the question. Although I had previously said it wasn't possible to do this using JavaScript and a font that isn't fixed-width... it actually is possible!
You can wrap each individual character in a <span>, and find the first <span> that is outside the bounds of the parent. Something like:
function countVisibleCharacters(element) {
var text = element.firstChild.nodeValue;
var r = 0;
element.removeChild(element.firstChild);
for(var i = 0; i < text.length; i++) {
var newNode = document.createElement('span');
newNode.appendChild(document.createTextNode(text.charAt(i)));
element.appendChild(newNode);
if(newNode.offsetLeft < element.offsetWidth) {
r++;
}
}
return r;
}
Here's a demo.
You can do this with Javascript. Here is a function that counts the number of visible characters in an element, regardless of external css sheets and inline styles applied to the element. I've only tested it in Chrome, but I think it is cross browser friendly:
function count_visible(el){
var padding, em, numc;
var text = el.firstChild.data;
var max = el.clientWidth;
var tmp = document.createElement('span');
var node = document.createTextNode();
tmp.appendChild(node);
document.body.appendChild(tmp);
if(getComputedStyle)
tmp.style.cssText = getComputedStyle(el, null).cssText;
else if(el.currentStyle)
tmp.style.cssText = el.currentStyle.cssText;
tmp.style.position = 'absolute';
tmp.style.overflow = 'visible';
tmp.style.width = 'auto';
// Estimate number of characters that can fit.
padding = tmp.style.padding;
tmp.style.padding = '0';
tmp.innerHTML = 'M';
el.parentNode.appendChild(tmp);
em = tmp.clientWidth;
tmp.style.padding = padding;
numc = Math.floor(max/em);
var width = tmp.clientWidth;
// Only one of the following loops will iterate more than one time
// Depending on if we overestimated or underestimated.
// Add characters until we reach overflow width
while(width < max && numc <= text.length){
node.nodeValue = text.substring(0, ++numc);
width = tmp.clientWidth;
}
// Remove characters until we no longer have overflow
while(width > max && numc){
node.nodeValue = text.substring(0, --numc);
width = tmp.clientWidth;
}
// Remove temporary div
document.body.removeChild(tmp);
return numc;
}
JSFiddle Example
You're trying to force a CSS problem into JavaScript. Put the hammer away and get out a screwdriver. http://en.wiktionary.org/wiki/if_all_you_have_is_a_hammer,_everything_looks_like_a_nail
Solving the answer of character count is probably irrelevant if you take a step back. The last character could be only partially visible, and character count is drastically different given font size changes, the difference of width between W an i, etc. Probably the div's width is more important than the character count in the true problem.
If you're still stuck on figuring out the characters visible, put a span inside the div around the text, use the css provided in other answers to this question, and then in JavaScript trim one character at a time off the string until the span's width is less than the div's width. And then watch as your browser freezes for a few seconds every time you do that to a big paragraph.
try this, it requires a fixed width if that is ok with you: http://jsfiddle.net/timrpeterson/qvZKw/20/
HTML:
<div class="col">This is my text inside a div and I want the overf|low of the text to be cut</div>
CSS:
.col {
width:120px;
overflow: hidden;
white-space:nowrap;
}​
.col { width:40px; overflow: hidden; white-space:nowrap; }
White-space: nowrap; is needed when the content has spaces.
Either way, long words in single lines do not appear. http://jsfiddle.net/h6Bhb/

Categories

Resources