7

I have a text which is generated randomly to a div. And this text has different width depending on what is currently generated. And I want this text to marquee only when is too big. html:

<div id="random_word"> <!--here appears something--> </div>

css:

#random_word {
    color: white;
    position: absolute;
    width: 50%;
    left: 0%;
    text-align: center;
    font-size: 8vw;
    margin-top: 22%;
    font-variant: small-caps
    text-shadow: 0 0 20px #000;
    text-align: center;
    z-index: 2;
    overflow: hidden;
    white-space: nowrap;
    line-height: 100%;
}

I found already this css property in internet: overflow-x:-webkit-marquee; but I'm not sure how to use it. Can anyone help?

kupkol
  • 221
  • 1
  • 3
  • 13
  • 3
    Maybe [CSS3 Marquee Effect](http://stackoverflow.com/questions/21233033/css3-marquee-effect) combined with [Check with jquery if div has overflowing elements](http://stackoverflow.com/q/7668636/1456376)? – insertusernamehere Feb 01 '17 at 18:51

2 Answers2

8

The easiest way to determine if an element is overflowing is to compare its scroll height/width to its offset height/width. If any of the scroll values are larger than their offset pairs, your element's contents are overflowing.

function isElementOverflowing(element) {
    var overflowX = element.offsetWidth < element.scrollWidth,
        overflowY = element.offsetHeight < element.scrollHeight;

    return (overflowX || overflowY);
}

From here it's a simple question of checking the return value of this function and adding a marquee effect if true. To achieve this, you can wrap your div's contents in a <marquee>, or achieve the same visual effect using the prefixed marquee CSS rules or simulating it via a CSS animation.

NB: while the <marquee> tag still works as expected in most browsers, it is considered deprecated hence not futureproof.

Good luck!

Community
  • 1
  • 1
ppajer
  • 3,045
  • 1
  • 15
  • 22
  • Oh men, thanks. But I have one more question. How to make this (https://jsfiddle.net/ppajer/zeuzzguk/) marquee's behavior alternate. I mean I want it to bounce from the right to the left and than again to the right and so on. – kupkol Feb 01 '17 at 20:42
  • @kupkol You can control it through the `behavior` attribute. `` will achieve a bouncing effect. – ppajer Feb 01 '17 at 20:49
  • 1
    Ooh sorry, it's injected via JS. That would be `marquee.behavior = "alternate";`, [updated the fiddle](https://jsfiddle.net/ppajer/zeuzzguk/1/) – ppajer Feb 01 '17 at 20:51
  • Hey, I'm having this problem right now, could you please tell me how I can make it vertical though? – DeA May 09 '17 at 14:13
0

I dont think the accepted answer is working when the overflow is hidden.

Better add another div inside and check their widths Check with jquery if div has overflowing elements

alex toader
  • 2,300
  • 1
  • 17
  • 20