I have a div with a fixed width which contains 'tags' like the stackoverflow-tags.
Now, what's disturbing me, is that the Hallo
Tag is in the last line, but it would fit in the first line. Like this:
The order of the elements is irrelevant. So, reordering would be an option.
Question: How can i achieve this? I'm currently using a <ul><li></li></ul>
construct.
The nicest way would be a CSS-Way, but i guess it's up to JS to solve this problem. Any ideas would be appreciated :)
UPDATE JSFiddle: http://jsfiddle.net/CLj2q/
Got it: The jsFiddle is here
$(function() {
$('.as-close').click(function(e) { $(this).parent().remove(); });
DoTagSort();
});
function DoTagSort() {
var TheItems = [], TheHTML = '';
var TheLinks = $('.as-selections').find('li').each(function () {
TheItems.push($(this).text().slice(1));
});
TheItems.sort(function(a, b) { return b.length - a.length; });
var TheTag = '<li class="as-selection-item"><a class="as-close">×</a>';
while(TheItems.length > 1) {
TheHTML = TheHTML + TheTag + TheItems[0] + '</li>';
TheHTML = TheHTML + TheTag + TheItems[TheItems.length - 1] + '</li>';
TheItems.splice(0, 1);
TheItems.splice(TheItems.length - 1, 1);
}
if (TheItems.length) {
TheHTML = TheHTML + TheTag + TheItems[0] + '</li>';
}
$('.as-selections').html(TheHTML);
}
Assuming that the container for the tags is a set-width, and the tags themselves aren't (ie: they inherit their width from their contents, rather than us being able to give them a set-width) there's not a huge amount that you can do from the CSS perspective without breaking and re-ordering the flow of the markup.
If the markup is being generated server-side I'm sure you could calculate widths and re-order prior to pushing the markup into the view. If not, you're a bit stuck without using JavaScript.
Given that the order requirement appears to be purely appearance-based (ie: not functional), there's no harm in enhancing the standard float view that you've displayed in your screenshot with JavaScript. This means that JS-enabled visitors will get an 'enhanced' view (with the elements ordered nicely), whilst non-JS users would still have a fully-functional tag cloud, albeit in a slightly less-organised fashion.
jQuery Masonry or Isotope would probably do would do exactly what you need.
This is off the shelve solution. And a bit of a cheat with Masonry (notice the columnWidth: 1).
$('.as-selections').masonry({
itemSelector: '.as-selection-item'
, columnWidth: 1 });
http://jsfiddle.net/D5ud7/1/
I guess you could find more appropriate library for this or better html form for masonry to crunch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With