Question

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();
    }); 
    
  • Was it helpful?

    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();
    });
    

    OTHER TIPS

    To retrieve the outerHeight (including border, padding, and optionally margin) of an html element using jQuery, do $(element).outerHeight()

    To retrieve the innerHeight of an html element using jQuery, do $(element).innerHeight()

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

    The default unit is pixels so you don't have to worry about appending px to the value.

    Licensed under: CC-BY-SA with attribution
    Not affiliated with StackOverflow
    scroll top