4

Ok I need to be able to position a bunch of random sized absolutely positioned words on a page but I don't want any of the elements to overlap.

The end goal is to have a fluid word cloud that responds to user interaction (remember the Google Balls Doodle?). I would really like to build this from scratch to develop my understanding of this type of development. Any help in this department would also be appreciated :)

wilsonpage
  • 17,341
  • 23
  • 103
  • 147
  • May be useful to set the font size, and get the surrounding element's height / width first, then go about positioning to begin with. http://jsfiddle.net/yYB7t/ – minikomi Jun 03 '11 at 08:20
  • @minikomi any idea how to do the positioning? I am aware how to get an element's hight and width. – wilsonpage Jun 03 '11 at 09:40

2 Answers2

13

I'm not sure if you also want to position the words randomly inside a container, but i've written a fiddle that does just that. You can modify the code to position one word right after the other if you want to though. I think the key part is the method to check if there's a collision.

see http://jsfiddle.net/fZtdt/13/

EDIT: Be aware that this is very simple and unoptimized code. If for example you would add to many words, chances are that the script won't be able to fit all words inside the container, and get into an endless loop.

Jules Colle
  • 11,227
  • 8
  • 60
  • 67
  • That's pretty impressive! My end goal is to create someting that looks like this http://www.lucaongaro.eu/demos/jqcloud/ Can you help/modify your answer? – wilsonpage Jun 03 '11 at 10:41
  • 1
    sure, you can just style all words as you please. check out http://jsfiddle.net/fZtdt/14/ – Jules Colle Jun 03 '11 at 12:31
  • the jqcloud thing seems to use a spiral function to position the tags, starting from the center with the biggest words. I'm not gonna post that code since you can just get the open source code for it here: http://plugins.jquery.com/project/jQCloud – Jules Colle Jun 03 '11 at 12:39
  • The jQCloud link is now broken. :( – macguru2000 Oct 19 '15 at 20:26
9

I have forked Jules' script to add this improvement : the search for a non-overlapping region is bounded (otherwise the original script will loop I believe), and the best region (the one with the smallest overlap) is selected.

see http://jsfiddle.net/Vnyvc/21/

play with the maxSearchIterations variable and/or the size of the whole region, it really makes a difference.

cthiebaud
  • 4,917
  • 2
  • 19
  • 8