javascriptjqueryscrollnews-ticker

get height of LI using jQuery so news ticker scrolls up the exact amount needed


I am using a script from http://www.yourinspirationweb.com/en/jquery-how-to-create-a-news-ticker-with-just-a-few-javascript-lines/

which is a great newsticker, designed to scroll up just one article at a time, then append it again at the end in a continuous loop. But the limitation of this script is that the news items in each

  • have to be the same height as eachother, which isn't always possible.

    I have been trying to modify the script so that it will automatically get the outerheight of '#ticker li:first'. and scroll it so that marginTop equals the negative of that outerheight. rather than the default '-120px'. But i've realised it's written as CSS style, i don't know how to rewrite it. Help!

    here's the original script:

    $(function()
    {
        var ticker = function()
        {
            setTimeout(function(){
                $('#ticker li:first').animate( {marginTop: '-120px'}, 800, function()
                {
                    $(this).detach().appendTo('ul#ticker').removeAttr('style'); 
                });
                ticker();
            }, 4000);
        };
        ticker();
    }); 
    

  • Solution

  • This should do the trick. Just put the height into a variable, multiply by -1 (to make the negative number you need), and then drop it into the marginTop property:

    $(function() {
        var ticker = function() {
            setTimeout(function() {
                // get the height of the li element, multiply by -1 to be negative
                var h = parseInt($("#ticker li:first").outerHeight()) * -1; 
                $('#ticker li:first').animate( {marginTop: h + 'px'}, 800, function() {
                    $(this).detach().appendTo('ul#ticker').removeAttr('style'); 
                });
                ticker();
            }, 4000);
        };
        ticker();
    });