2

I have a span with some text inside it.

document.getElementById('span1').scrollWidth;

on firefox return '100' as the scrollWidth but Chrome returns only '0'. Does Chrome not support this 'scrollWidth' property? Any other browser which doesnt support the same?

Also what would be work around for this if I need to get the length of a sentence in pixels?(I keep populating 'span1' with sentences using 'innerHTML' property)

Bhumi Singhal
  • 8,063
  • 10
  • 50
  • 76
  • Bhumika this when accessed using document.getElementById('span1').scrollWidth; gives the complete width of the page. This is different than the behaviour at firefox which provides the width of "bhumika" as the span's scrollWidth. – Bhumi Singhal Nov 05 '12 at 06:03
  • Setting the display=block;visibility=hidden wont work if done manually ..in the least it didn't for me. – Bhumi Singhal Nov 05 '12 at 07:46

1 Answers1

2

There is a lot of difference in how Firefox and Chrome respond to css and js. [ff=Firefox, c=Chrome, sw= scrollWidth ]

Key points:

  1. sw works only when the element's display is not inline and none.
    ff sets the display to block by default while c sets it to inline. So you would not get sw in c. If you need the element to be hidden anyways just use:
    visibility:hidden without setting the display for both ff and c.
  2. If u have set the visibility in c, use style.width of the element instead of sc. This works.

If you still want to use sc on chrome also for a hidden span, you could use @AnthonyWJones answer on

Knowing how wide a text line will be in HTML for word wrap and other applications

Worked for IE7,8,9 , FF, Chrome.

Community
  • 1
  • 1
Bhumi Singhal
  • 8,063
  • 10
  • 50
  • 76
  • Ohk ...there is something on with the css defined in the AnthonyWJones answer that is making it work on Chrome as without it and simply noting the visibility as hidden wont work on chrome as display remains as inline. However with the css, display becomes block. No idea how it happens. Someone explain – Bhumi Singhal Nov 05 '12 at 07:42
  • Alright in the css provided: position:absolute is doing the trick. – Bhumi Singhal Nov 05 '12 at 07:48