The effect _javascript technique of JS to realize the scroll display information of imitation micro Bo

Source: Internet
Author: User
Tags jquery library

I believe that all of us will be free when the micro-blog, push the principal social networking sites, every time I log on Weibo, I will pay attention to what it changes, small some layout changes, large API interface changes.

On the home page to the microblog, we can see a column, "Everyone is saying", it scrolling shows the current each person sent micro-blog; just to see this effect is very interesting, so we will be in the next article to implement scrolling display micro-blog information effect.

We looked at the microblogging "everyone is saying," It is by scrolling down to achieve the continuous display of micro-blog, and every day the new microblog is shown by the fade effect.

Figure 1 Weibo "everyone is saying"

1, the definition of micro-blog Plug-ins
Next, we'll define a plugin to get a tweet on a topic, where we'll use the expansion of jquery to set up a microblog jquery plugin

Because jquery provides a mechanism for adding custom methods and additional functionality to the core modules, jquery allows us to create custom plug-ins that encapsulate commonly used methods to improve our development efficiency.

First, by defining a iife function, and then passing the jquery object as an argument to the executable function, the "$" will not be overwritten by other libraries within its execution scope by establishing a corresponding relationship between "$" and jquery.

Defines a jquery plugin.
; (function ($) {
  $.fn.weibosearch = function () {
    //Your plugin logic
  };
}) (JQuery);

Above, we define a self execution function (Iife) and within it define an extension method Weibosearch ().

As a result, the microblogging API 2.0 provides an interface search/topics to search for tweets under a topic, and returns JSON-formatted data if the request succeeds.

Figure 2 Micro-Blog Search interface parameters

As shown above, we know that the microblogging search interface needs to provide Appkey (OAuth authorization) and topic Keywords (q) for applications.

Next, we define a literal object defaults, which contains the URL of the microblogging interface, the applied appkey, the topic keyword (q), and the number of records (count) returned by a single page, which are defined as follows:

Defines Weibo defaults type.
$.fn.weibosearch.defaults = {
  URL: ' https://api.weibo.com/2/search/topics.json?q= ',
  appkey: ' 5786724301 ',
  numweibo:15,
  term: '
};

2. Send Cross Source request
We can invoke the microblogging search interface by sending an AJAX request, and if the request succeeds the server returns JSON format data to the program, then we need to render the returned data to the page.

 $.getjsonp = function (s) {//Due to cross Origin request, so we-use JSONP format.
  S.datatype = "Jsonp";

  $.ajax (s);
  Figure out what the callback fn was var $script = $ (document.getelementsbytagname (' head ') [0].firstchild); var url = $script. attr (' src ') | |

  ''; Gets callback function var cb = (Url.match (/callback= (\w+)/) | |

  []) [1]; if (!CB) return;

  Bail var t = 0, CBFN = WINDOW[CB];
    $script [0].onerror = function (e) {$script. Remove ();
    HandleError (S, {}, "error", e);
  Cleartimeout (t);

  };

  if (!s.timeout) return;
    WINDOW[CB] = function (JSON) {cleartimeout (t);
    CBFN (JSON);
  CBFN = null;

  };
  Gets Time Out function flag.
    t = settimeout (function () {$script. Remove ();
    HandleError (S, {}, "timeout");
  if (CBFN) WINDOW[CB] = function () {};

  }, S.timeout); /** * Fix Issue: "Jquery.handleerror is not a function"/function HandleError (s, XHR, MSG, e) {s.error && Amp S.error. Call (S.context, XHR, MSG, E);
    S.global && $.event.trigger ("Ajaxerror", [XHR, S, e | | msg]);
  S.complete && S.complete.call (S.context, XHR, E | | msg);

 }
};

Above, we define Method Getjsonp (), which invokes the microblogging API by sending an AJAX request, when we need data across the source, we can get the cross source data through the JSONP format, because it allows the server-side integration script tags back to the client, Cross-domain access is implemented through JavaScript callback.

Next, we define the private method Grabweibos () in Method $.fn.weibosearch (), which is responsible for invoking the GETJSONP () method and getting the returned JSON data to appear on the page.

/**
* Uses Ajax request to grab Weibos.
*
/function Grabweibos () {
  var url = opts.url;
  Grabflag = false;
  grabbing = true;

  $.getjsonp ({
    url:url,
    timeout:30000,
    data: {
      Source:opts.appKey,
      q:opts.term,
      count : Opts.numweibo
    },
    error:function (XHR, status, E) {
    },
    complete:function () {
    }
    , Success:function (JSON) {
      if (json.error) {
        //Can ' t get results displays error.
        return;
      }

      Iterates Weibo results
      $.each (json.data.statuses, function (i) {
        //Adds data to page.
      }}
    }

  ) ;
}

Above, we define Grabweibos (), which calls the Getjsonp () method and displays the data to the page after the request succeeds.

3. JSON data processing
Now, we have basically implemented the Jquery.weibo.search.js plug-in, to search for a topic of the microblogging function, due to the relationship between the time we have to design the interface, the specific HTML code is as follows:

<!--from design-->
<! DOCTYPE html>
 
 

Next, we refer to the jquery library and the custom microblogging topic search plugin jquery.weibo.search.js in the page code as follows:

<!--Adds Javascript reference--> <script type= "Text/javascript" src=
Libs/jquery/1.7.1/jquery.min.js "></script>
<script type=" Text/javascript "src=" js/ Jquery.weibo.search.js "></script>

Above, we directly refer to the jquery library provided by Google, of course, we also download the jquery library to the local, and then introduced into the project, then we add the head element to invoke the microblogging topic search plug-in code, the specific code as follows:

<!--when document ready invokes CharCount function-->
<script type= "Text/javascript" >
  //Invokes Webiosearch function.
  $ (document). Ready (function () {
    $ ("#weibo1"). Weibosearch ({
      term: ' Valentine's Day ',
      direction: ' Down '
    });

    $ ("#weibo2"). Weibosearch ({
      term: ' Lantern Festival ',
      direction: ' Up '});
  });
</script>

Above, we call the default method of Weibosearch () in the page, and search for "Valentine's Day" under the topic of Twitter. Next, we turn on the network option in Chrome to see that the request in Search/topics contains the source, count, Q, and callback (callback function) parameters.

Figure 3 Ajax requests

Because the JSON data in Chrome is not easy to read, we view the data in the JSON format returned in Firefox.

Figure 4 Micro-blog JSON data

The JSON data above is not easy to view, we use the JSON viewer to format the microblog data, and the formatted data is as follows:

Figure 5 Formatted JSON data

From the above figure, we find that the microblog data is contained in the Try/catch statement, and if the request succeeds the catch will be empty, otherwise, the corresponding error message is returned.

Next, we extract the microblogging data and then remove the try/catch we look at the structure of the microblogging data in the JSON viewer.

Figure 6 Micro-blog JSON data

From the figure above, we know that the return data is a JSON array, and its size is determined by the count of our request parameters, and Weibo requires that each request return a maximum of 200 tweets.

Next, we need to show the data to the page, now let's implement the success Method! The specific code is as follows:

Gets response data from Weibo API.
    Success:function (JSON) {if (json.data.error) {//Can ' t get data displays error.
    Faileye (Json.data.error);
  Return
  }//Emptys contain with fade out effect.

    $cont. fadeout (' Fast ', function () {$cont. empty (); Iterates Weibo results $.each (json.data.statuses, function (i) {if (!opts.filter.call, this) | | opts ncated) return;
      Skip this Weibo, some weibos is deleted.

      var $img, $text, W, tweet = Opts.formatter (this, opts), $tweet = $ (tweet);
      Weibo data.
      $tweet. CSS (opts.css[' tweets ');
      $img = $tweet. Find ('. weibosearchprofileimg '). CSS (opts.css[' img '));
      $tweet. Find ('. Weibosearchuser '). CSS (opts.css[' user ');
      $tweet. Find ('. Weibosearchtime '). CSS (opts.css[' time ');
      $tweet. Find (' a '). css (opts.css[' a ']);
      $tweet. Appendto ($cont);

      $text = $tweet. Find ('. Weibosearchtext '). CSS (opts.css[' text '); if (opts. Avatar) {w = $img. Outerwidth () + parseint ($tweet. css (' paddingleft '));
      $text. CSS (' paddingleft ', W);
    }})//loads Weibos with fade in effect.

    $cont. FadeIn (' fast ');
    Invokes Weibo API again. if (Json.data.statuses.length < 2) {if (opts.refreshseconds) settimeout (Gradweibos, Opts.refreshseconds
      * 1000);
    Return
}

  });

 }

In the success () method, we use the Fadein () and fadeout () functions of jquery to fade in and out when the micro-boga load fades.

Next, we use the $.each () method to traverse each of the microblogging information in the JSON array and add them to the page DOM.

Figure 7 Micro-blog Information

We invoke the microblogging Search/topics interface via a cross source request and then display the JSON data returned by the server to the page.

5, micro-bo relative time
Now, the Jquery.weibo.search.js plug-in is basically implemented, but we find that each micro-blog display time seems to be not very normal, and has not implemented scrolling (animate) and Fade (fadeIn) effect.

Because microblogging is using relative time to express the time of the microblogging plug-in, of course, we can also show the time, next, let us change the time of the microblogging creation (CREATED_AT) in the form of relative time, due to the time format of Weibo: "Thu Feb 14 20:33:30 +0800 2013" , so we define the method Relativetime () to convert the Weibo time to relative time.

 function relativetime (datestring) {var values = Datestring.split ("");
  datestring = values[1] + "" + values[2] + "," + values[5] + "" + values[3];
  var parsed_date = Date.parse (datestring); var relative_to = (Arguments.length > 1)?
  ARGUMENTS[1]: New Date ();
  var delta = parseint ((Relative_to.gettime ()-parsed_date)/1000);

  Delta = Delta + (Relative_to.gettimezoneoffset () * 60);
  if (Delta <) {return ' just now ';
  else if (Delta <) {return ' a minute ago ';
  else if (Delta <) {return (parseint (DELTA/60)). ToString () + ' minutes ago ';
  else if (Delta <) {return ' about a hour ago ';
  else if (Delta <) {return ' about ' + (parseint (delta/3600)). ToString () + ' hours ago ';
  else if (Delta <) {return ' 1 day ago ';
  else {return (parseint (delta/86400)). ToString () + ' days ago '; }
}

Above, we define the method Relativetime (), first of all, it can be spliced to convert time format "Feb 14, 2013 20:33:30", and then convert datestring to date, then get the current time minus the Weibo time (created_ at) to calculate the relative time (delta).

Figure 8 Relativetime calculation relative time

5, Micro Bo dynamic effect
Above, we use the method Relativetime () to convert the Weibo time to relative time, and then we need to implement the Micro-blog scrolling (animate) and Fade (fadeIn) effects.

In the Sina Weibo hall, we can see "Everybody is saying" each micro-blog rolls down from the top, in fact, to achieve the scrolling effect we can use the jquery animate () method, specifically implemented as follows:

/** * Weibos rolling from top to bottom/function weiboin () {if (paused | | grabbing)
    {settimeout (Weiboin, 500);
  Return
  }//Gets last element.

  var h, $el = $cont. Children (': Last '), $elFirst = $cont. Children (': a ');
  Gets last Weibo item height.

  h = $el. Outerheight ();
  Animate:increases the Weibo item margin top to ' h '.
  Then decreases the Weibo item margin top to ' 0 '.
    $elFirst. Animate ({margintop:h}, Opts.animinspeed, function () {$elFirst. css ({margintop:0, opacity:1}); /* @cc_on try {el.style.removeAttribute (' filter ');}//IE ClearType fix catch (smother) {} @*///Appen
    d The last Weibo item A.

    $el. css (opts.css[' tweet '). Hide (). Prependto ($cont);
    Fade in display new item.

    $el. FadeIn (Opts.animinspeed);

  Loop settimeout (Grabflag grabweibos:weiboin, opts.timeout);
}); }

Above, we have defined the Weiboin () method, it realizes the micro-blog to scroll down the display effect, we through the animate () method dynamically modifies the div element margintop attribute.

Next, we need to reinsert the scrolling to the last microblog onto the current first microblog, and then implement the microblogging fade through the Fadein () function.

Now that we have basically achieved the downward scrolling and fading effect of the microblogging "everyone is saying", we first modify the margintop attribute of the DIV element with the animate () method, and then show the scrolling micro-blog in the fading mode.

Someone might ask, "What if you want to scroll up and fade out?" In fact, the effect is exactly the opposite of what we've achieved before, and we need to fade out of the hidden microblogging and scroll up.

Now that we have the idea of implementation, then let us achieve up scrolling and fade effect bar! specifically implemented as follows:

/**
* Weibos rolling from bottom to top.
* *
function weiboout () {
  if (paused | | grabbing) {
    settimeout (weiboout,);
    return;
  }

  Gets last element.
  var h, $el = $cont. Children (': A '), el = $el [0];

  Implements fade out effect. 
  $el. Animate (Opts.animout, opts.animoutspeed, function () {

    //Gets the item height.
    h = $el. Outerheight ();

    $el. Animate ({margintop:-h}, Opts.animinspeed, function () {
      $el. css ({margintop:0, opacity:1});
      /* @cc_on
      try {el.style.removeAttribute (' filter ');}//IE ClearType fix
      catch (smother) {}
      @*/

      /A Ppend the last Weibo item.
      $el. CSS (opts.css[' tweets '). Show (). Appendto ($cont);
      SetTimeout (Grabflag grabweibos:weiboout, opts.timeout);});}


In the Weiboout () method, we implement the fade effect by modifying the Opacity property of the $el, but we can also use the fadeout () method to fade out, and we use the method animate () to modify the MarginTop property, different from-H to start the change.

Now that we have the fade out, fade in and scroll effect, we need to add CSS styles to the interface to make the program more beautiful.

Weibo CSS style in jquery plugin. css:{//default styling a:{textdecoration: ' None ', Color: ' #3B5998 '}, eye:{width: ' 40px ', Height: ' 40px ', Position: ' Absolute ', left: ' -30px ', Top: ' -20px ', border: ' None '}, container:{overflow: ' Hidden ', backgroundcolor: ' #eee ', Height: ' 100% '}, fail:{background: ' #6cc5c3 url (./images/error_page_small.png) no-repeat 50% ' 50% ', Height: ' 100% ', padding: ' 10px '}, frame:{border: ' 10px solid #C2CFF1 ', Borderradius: ' 10px ', '-moz-border-radius ': ' 10px ', '-webkit-border-radius ': ' 10px '}, tweet:{padding: ' 5px 10px ', clear: ' Left '}, img:{' float ': ' Left ', margin: ' 5px ', Width: ' 48px ', Height: ' 48px '}
  , loading:{padding: ' 20px ', textAlign: ' Center ', Color: ' #888 '}, text:{}, time:{fontsize: ' Smaller ', color: ' #888 '}, title:{backgroundcolor: ' #C2CFF1 ', margin:0, padding: ' 0 0 5px 0 ', textAlign: ' Center ', fontweight: ' Bold ', FontSize: ' Larg E ', Position: ' relative '}, titlelink:{textdecoration: ' None ', Color: ' #3B5998 '}, user:{fontweight: ' Bold '}After that, we add the following style to the Weibo.serach.style.css file, which is defined as follows: Div.weibo {margin:auto; width:300px} #weibo1 {height:300px;} #weibo2 { height:300px;  Body {background-color:white} body, div {font-family: ' Microsoft Ya-black ', Helvetica, Verdana, Arial, sans-serif} body {margin: 20px 0; padding:0; Font-size:small;
  Color: #333} div {Display:block}/* Image rounded corner*/. weibosearchprofileimg{border-radius:10px;
  -moz-border-radius:10px;
-webkit-border-radius:10px;
  } table {Margin:auto;
  Border-collapse:separate;
border-spacing:25px;

 } table {border-collapse:collapse;}


Figure 9 Program Interface

Now, we have implemented the microblogging search plug-in, search for "Valentine's Day" and "Lantern Festival" under the topic of the microblogging, through the plugin we obtained micro-blog information and display to the page.

The above is the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.