Home » Php » javascript – How to scroll div contents vertically in a loop like news feed in php page

javascript – How to scroll div contents vertically in a loop like news feed in php page

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m making a Php webpage right now and would like to have a little “News” DIV on the right. that has auto scrolling vertical text as soon as the page loads. But, the below code not working in php page.

 <html>
 <head>
    <script src="https://code.jquery.com/jquery-3.0.0.js" 
    integrity="sha256-jrPLZ+8vDxt2FnE1zvZXCkCcebI/C8Dt5xyaQBjxQIo=" 
    crossorigin="anonymous">
    </script>

       <style>
        span 
        { 
          display:block;
          width:350px;
          word-wrap:break-word;
        }

        .display 
        {
          height:200px;
          border:none;
          overflow: hidden;
          padding:5;
        }
       </style>

  </head>

 <body onLoad="scroll()" style="background-color: black;">

 <!---***************** Php Code Start ************************--->
 <?php

   error_reporting(E_ALL ^ E_DEPRECATED);

 //********************* DB Configuration Code *********************
   ob_start();
   define('DB_SERVER', 'localhost');
   define('DB_USERNAME', 'xxxx');
   define('DB_PASSWORD', '');
   define('DB_DATABASE', 'MyDb');

    $connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
    $database = mysql_select_db(DB_DATABASE) or die(mysql_error());

    //************** Selection of Data *********************
    $select=mysql_query("SELECT * FROM newsfeedtest order by created asc");
    $i=1;

   //************* Display Data *********************
     while($userrow=mysql_fetch_array($select))
     {

        $id=$userrow['id'];
        $usernews=$userrow['news'];
        $created=$userrow['created'];

   //******** Div Displays Data *******
     echo  '<div class="display" id="news" style="width:350px; margin-bottom:-20px;">

        <!-------------------- News : --------------------------------->
          <p style="color:#fff;">
          <span style="color: #fff;font-size:17px;">'.$usernews.'</span> </p><br />

        </div>';
      }

       //********************* End of Php Code *********************
     ?> 


      <script language="javascript">
        i = 0
        var speed = 1
        function scroll() 
        {
          i = i + speed
          var div = document.getElementById("news")
          div.scrollTop = i
          if (i > div.scrollHeight - 160) {i = 0}
          t1=setTimeout("scroll()",100)
        }
      </script>

     </body>

    </html>

Also, can it possible that on Mouseover to stop the scroll and on mouse out scrolling starts continue in a loop.
I’ve tried searching for the correct code, but nothing has worked thus far.

” I’m just so frustrated now ! ”

Any help would be immensely appreciated!

How to&Answers:

Here’s the most simple solution I can come up with – it will achieve what you want, and also adjust to the CSS code you define (so if you change your height in CSS, the script won’t have to be altered).

var i = 0;

$(document).ready(function(){
  var interval = setInterval(function () {
    i += 4; // speed
    $('#container').animate({ scrollTop: i }, 1);
    if (i >= $('#container').prop('scrollHeight') - $('#container').height()) {
      i = 0;
    }
  }, 100);
});
#container {
  background-color: #000;
  color: #fff;
  height: 180px;
  overflow: hidden;
  padding: 5px 20px;
  width: 350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
  <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
  <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>

Note that I have set the “speed” to 4 for quicker reviewing of the result – change it to 1 for the outcome you wanted. I also put absolutely everything in it’s correct place, meaning have no inline styles or inline scripts, which will be way easier to maintain in your project the more it grows.

Also, in order to wrap everything into a run-able snippet, I omitted the PHP code, but the generation is essentially the same as you’ve had it in your example, except you’ll need the #container element around it for context.

Answer:

// please add bootstrap.css & jquery.js in the same file folder // 
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="bootstrap.css" rel="stylesheet">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body> 
          <div class="container-fluid">
          <div class="row">
            <div class="col-xs-4"></div>
            <div class="col-xs-4" style="min-height:300px">
                 <ul id="marquee-vertical">
               <li style="list-style-type:none">
                 <a href="">Breaking News 1</a>
                 <div class="row">
                    <div class="col-xs-4"><img  src="logo1.png"/></div>
                    <div class="col-xs-8">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
                 </div>
               </li>

               <li style="list-style-type:none">
                 <a href="">Breaking News 2</a>
                 <div class="row">
                    <div class="col-xs-4"><img src="logo1.png"/></div>
                    <div class="col-xs-8">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
                  </div>
               </li>

               <li style="list-style-type:none">
                 <a href="">Breaking News 3</a>
                 <div class="row">
                    <div class="col-xs-4"><img src="logo1.png"/></div>
                    <div class="col-xs-8">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
                 </div>
               </li>

               <li style="list-style-type:none">
                <a href="" >Breaking News 4</a>
                <div class="row">
                    <div class="col-xs-4"><img src="logo1.png"/></div>
                    <div class="col-xs-8">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
                 </div>
               </li>

             </ul>
            </div>
            <div class="col-xs-4"></div>
          </div>

          </div>
<script type="text/javascript">


(function($, window, document, undefined){
    var pluginName = "marquee",

    defaults = {
       enable : true, 
       direction: 'vertical',   
       itemSelecter : 'li',  
       delay: 1000, 
       speed: 1,  
       timing: 1,
       mouse: true 

    };


    function Widget(element, options) {
        this.element = element;
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;

        this.$element = $(this.element);
        this.$wrapper = this.$element.parent();
        this.$items = this.$element.children(this.settings.itemSelecter);


        this.next = 0;
        this.timeoutHandle;
        this.intervalHandle

        if(!this.settings.enable)return;
        this.init();
    }


    Widget.prototype = {

       init:function(){

            var that = this;

            var totalSize = 0;

            $.each(this.$items, function(index, element){

                totalSize += that.isHorizontal() 
                            ? parseInt($(element).outerWidth())
                            : parseInt($(element).outerHeight());

            }); 

            var elmentTotalSize = this.isHorizontal()
               ? this.$element.outerWidth
               : this.$element.outerHeight;

            if(totalSize < elmentTotalSize)return;

            this.$wrapper.css({

                position : 'relative',
                overflow : 'hidden'

            });

            this.$element.css({

                 position : 'absolute',
                 top : 0,
                 left: 0

            });

            this.$element.css(this.isHorizontal() ? 'width' : 'height', '1000%');

            this.cloneAllItems();

            if(this.settings.mouse)
                     this.addHoverEvent(this);

            this.timer(this);


       },


        timer : function(that){

            this.timeoutHandle = setTimeout(function(){that.play(that)}, this.settings.delay);

        },


        play : function(that){


           this.clearTimeout();

            var target = 0;

            for(var i = 0; i <= this.next; i++){

                 target -= this.isHorizontal()
                    ? parseInt($(this.$items.get(this.next)).outerWidth())
                    : parseInt($(this.$items.get(this.next)).outerHeight());


            }

            this.intervalHandle = setInterval(function(){that.animate(target)},this.settings.timing);
        },


        animate : function(target){

            var mark = this.isHorizontal() ? 'left' : 'top';

            var present =  parseInt(this.$element.css(mark));


            if(present > target)
            {
                if(present - this.settings.speed <= target)
                {
                     this.$element.css(mark, target);

                }else

                     this.$element.css(mark, present - this.settings.speed);

            }else{


                this.clearInterval();

                if(this.next + 1 < this.$items.length){

                     this.next++;

                }else{

                    this.next = 0;
                    this.$element.css(mark,0);

                }
                this.timer(this);
            }

        },


        isHorizontal : function(){

            return this.settings.direction == 'horizontal';
        },

        cloneAllItems: function(){

            this.$element.append(this.$items.clone());
        },


        clearTimeout : function(){

            clearTimeout(this.timeoutHandle);
        },

        clearInterval : function(){

            clearInterval(this.intervalHandle);
        },



        addHoverEvent : function(that){

            this.$wrapper
              .mouseenter(function(){

                   that.clearInterval()
                   that.clearTimeout();

              })
              .mouseleave(function(){

                   that.play(that);

              });
        }



    }


    $.fn[pluginName] = function(options) {

        return this.each(function() {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Widget(this, options));
            }
        });

    };

})(jQuery, window, document);



  $(function(){


  $('#marquee-vertical').marquee();  

});
</script>
</body>
</html>

Answer:

I use marquee with some its properties and the problem is solved !

  <marquee behavior="scroll" height="50px" scrollamount="1"  direction="up" onmouseover="this.stop();" onmouseout="this.start();">

  <!---*********************** Php Code Start ***************************--->
       <?php

         //********** Php code goes here ***********

       ?>
  <!---******************** Php Code End ********************************--->

   </marquee>