search to json pull from API to html all nice and pretty? - javascript

I'm working on a project for a client where the site visitors can search Campusbooks.com and get the results displayed.
Contacted Campusbooks and was told that I can use their API and have fun... and that's it.
I've found how to create a search form that pulls the results as posts the raw JSON. There's no formatting in the JSON so what I am getting is
"response":{
"#attributes":{
"status":"ok",
"version":"10"
},
"label":{
"#attributes":{
"plid":"3948",
"name":"Textbooks 4 You"
}
},
"page":{
"#attributes":{
"name":"search"
},
"count":"1000",
"pages":"100",
"current_page":"1",
"results":{
"book":[{
"isbn10":"1463590776",
"isbn13":"9781463590772",
"title":"Life on the Mississippi",
"author":"Mark Twain",
"binding":"Paperback",
"msrp":"13.99",
"pages":"316",
"publisher":"CreateSpace",
"published_date":"2011-06-19",
"edition":"Paperback",
"rank":"99999999",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/51sXKpUcB0L.SL75.jpg"
},
{
"isbn10":"1406571253",
"isbn13":"9781406571257",
"title":"How to Tell a Story and Other Essays (Dodo Press)",
"author":"Mark Twain",
"binding":"Paperback",
"msrp":"12.99",
"pages":"48",
"publisher":"Dodo Press",
"published_date":"2008-02-29",
"edition":"Paperback",
"rank":"214431",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/41S5poITLpL.SL75.jpg"
},
{
"isbn10":"0520267192",
"isbn13":"9780520267190",
"title":"Autobiography of Mark Twain, Vol. 1",
"author":"Mark Twain",
"binding":"Hardcover",
"msrp":"34.95",
"pages":"743",
"publisher":"University of California Press",
"published_date":"2010-11-15",
"edition":"1",
"rank":"344",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/41LndGG6ArL.SL75.jpg"
},
{
"isbn10":"1936594595",
"isbn13":"9781936594597",
"title":"The Adventures of Huckleberry Finn",
"author":"Mark Twain",
"binding":"Paperback",
"msrp":"8.88",
"pages":"270",
"publisher":"Tribeca Books",
"published_date":"2011-04-07",
"edition":"Paperback",
"rank":"1285",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/51J4kzmKcpL.SL75.jpg"
}
]
}
}
}
}
I need to take that output and make it all nice and pretty in HTML.
The script I am using to do this with at this point is:
// Vanilla JS Example: CampusBooksJS
(function () {
var CampusBooks = require('campusbooks'),
// This key is a special dummy key from CampusBooks for public testing purposes
// Note that it only works with Half.com, not the other 20 textbook sites, so it's not very useful,
// but good enough for this demo
cb = CampusBooks.create("T4y4JKewp48J2C72mbJQ"),
cbform = document.getElementById("vanilla-campusbooksjs-form");
// Note: This is for demonstration purposes only (with modern browsers)
// Use MooTools or jQuery for a real-world solution that works cross-browser
// (and please don't write you own, it's not worth it)
function cbSearch(e) {
var cbform = this,
search = cbform.querySelector("select").value,
data = cbform.querySelector("input").value;
e.preventDefault();
if (!data) {
alert("Try Typing in a Keyword or Two First");
return;
}
alert("Your Search: " + search + ": " + JSON.stringify(data, null, ' '));
var params = {};
params[search] = data;
cb.search(params).when(function (err, nativeHttpClient, data) {
if (err || !data) {
alert("Error: " + JSON.stringify(err) || "No Data Returned");
return;
}
document.querySelectorAll("#vanilla-campusbooksjs-display")[0].innerHTML = JSON.stringify(data, null, ' ');
});
}
// This will work on modern browsers only
cbform.addEventListener("submit", cbSearch, false);
}());
The search form is:
<form id="vanilla-campusbooksjs-form">
<select name="cb_search">
<option>keywords</option>
<option>author</option>
<option>isbn</option>
</select>
: <input name="cb_value" type="text"/>
<input type="submit" value="Search"/>
</form>
<div>
<pre>
<code id="vanilla-campusbooksjs-display">
</code>
</pre>
</div>
I hope this isn't too long of a post. If additional information is needed, please let me know.

I would suggest using Mustache Templates. Its easy to apply mustache templates to JSON and get some markup. It can be done on the server or client side.

Related

JSON select data at specific ID

In PHP, I've created a function to create a JSON file:
function writeJSONData(PDO $conn): void
{
$contentJSON = "SELECT * FROM tb_content";
$contentResultsJSON = $conn->query($contentJSON);
$contentJSONExt = array();
while ($JSON = $contentResultsJSON->fetchAll(PDO::FETCH_ASSOC)) {
$contentJSONExt = $JSON;
}
$infoJSON[] = json_encode(array('movies' => $contentJSONExt));
$target_dir = $_SERVER['DOCUMENT_ROOT'] . "/CineFlex/private/api/api.json";
file_put_contents($target_dir, $infoJSON);
}
In my HTML file I've created a button which sends the ID of the selected movie:
<!-- Edit Button -->
<button onclick="toggleDialog(editMovie, this.id)" id="<?php echo($info['content_id']) ?>Edit Movie</button>
My JavaScript file contains the function:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("./private/api/api.json", function (data) {
console.log(data)
})
}
When I click on the edit button, it prints the entire JSON file in the console. Which is understandable.
Current output:
{
"movies": [
{
"content_id": 15,
"title": "Scream (2022)",
"description": "25 years after a streak of brutal murders shocked the quiet town of Woodsboro, Calif., a new killer dons the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town's deadly past."
},
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
},
{
"content_id": 17,
"title": "Archive 81",
"description": "An archivist hired to restore a collection of tapes finds himself reconstructing the work of a filmmaker and her investigation into a dangerous cult."
}
]
}
Now my issue is, I want the "dialogID" to be selected from the JSON file where it matches with "content_id". For example: When I click on a movie with 16 as "dialogID", I want the console to just print everything from that array.
Expected output:
{
"movies": [
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
}
]
}
To get it, you need to create dynamic API instead of static file content. In alternative case, you can get it only from JS loop (check all and check suitable ID). If you want to do it with API, you must change html and php script like this:
function getDataById(PDO $conn):string
{
$id = (int) $_GET['id'];
$contentJSON = "SELECT * FROM tb_content where id = :id";
$contentResultsJSON = $conn->prepare($contentJSON);
$contentResultsJSON->execute([':name' => 'David', ':id' => $_SESSION['id']]);
$rows = $contentResultsJSON->fetchAll(PDO::FETCH_ASSOC);
$contentJSONExt = array();
while ($JSON =$rows) {
$contentJSONExt = $JSON;
}
return json_encode(array('movies' => $contentJSONExt));
}
And, JS codes to change like this:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("https://my-site.com/getDataById/?id="+dialogID, function (data) {
console.log(data)
})
}
I don't know if you want to select in your php the right ID, and send back only the right one or if you want the whole json back and select in javascript.
First answer here gives the answer to dynamic php: only the right ID back from server.
I will try to answer the second possibility: all json movies back, selection in javascript.
html (3 buttons for example):
<button onclick="toggleDialog(this.id)" id="15">Edit Movie 15</button>
<button onclick="toggleDialog(this.id)" id="16">Edit Movie 16</button>
<button onclick="toggleDialog(this.id)" id="17">Edit Movie 17</button>
javascript, let say we have back the whole json movies, I put a variable here (it's supposed to be the whole json back from php):
let json = {
"movies": [
{
"content_id": 15,
"title": "Scream (2022)",
"description": "25 years after a streak of brutal murders shocked the quiet town of Woodsboro, Calif., a new killer dons the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town's deadly past."
},
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
},
{
"content_id": 17,
"title": "Archive 81",
"description": "An archivist hired to restore a collection of tapes finds himself reconstructing the work of a filmmaker and her investigation into a dangerous cult."
}
]
}
javascript function:
function toggleDialog(dialogID) {
dialogID = parseInt(dialogID);
json.movies.every(e => {
if (e.content_id === parseInt(dialogID)) {
console.log(e.content_id);
console.log(e.title);
console.log(e.description);
return false;
}
return true;
})
}
You iterate through the json.movies (it's an object) with "every" instead of forEach. With every, you can break the loop when condition is met dialogID === content_id with return false. You have to put return true at the end of the loop otherwise it breaks immediately.
Your content_id are numbers, so parseInt on the dialogID. If coming from php json, it'll normally be string so no need for that.
A friend of mine helped me out:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("./private/api/api.json", function (data) {
for (let i = 0; i < data['movies'].length; i++) {
if (data['movies'][i]['content_id'] == dialogID) {
$('#editMovieTitle').val(data['movies'][i]['title'])
}
}
})
}

jQuery search in an object using a string

UPDATE
23 November 2016:
I was very close to the solution. Rory McCrossan has solved it for me, so I accepted his answer. BUT I changed the code for faster developing. I want to share this so you can use it to.
JSON langfile-v1.0.json
{
"nl": {
"text1":"Hallo Wereld!",
"text2":"voorbeeld.com",
"text3":"Ik hou van Stack Overflow"
},
"en":{
"text1":"Hello World!",
"text2":"example.com",
"text3":"I love Stack Overflow"
}
}
Javascript / jQuery script.js
//Creating an GLOBAL object
var languageObject;
//Get the language json file
$.get("langfile-v1.0.json", function(response){
languageObject = response; //Assign the response to the GLOBAL object
setLanguage(); //Calling the setLanguage() function
});
//Call this function to set the language
function setLanguage() {
$("lang").html(function() {
var userLang = navigator.language || navigator.userLanguage;
var langSupported = false; //Check if the user language is supported
$.each(languageObject, function(key) {
if (userLang == key) {
langSupported = true;
}
});
if (langSupported) {
//Users language is supported, use that language
return languageObject[userLang][$(this).html()];
} else {
//User language is NOT supported, use default language
return languageObject.en[$(this).html()];
}
});
}
HTML page.html
<lang>text1</lang> <br>
<lang>text2</lang> <br>
<lang>text3</lang>
Demo
You can check how this works on JSFiddle (with a slightly different code because I dont know how to inculde the langfile-v1.0.json file)
Click here for demo
OLD QUESTION POST:
I want to search in a object using a string.
Example:
JSON
{
"nl": {
"lang":"Nederlands",
"header-WelcomeText":"Welkom op de website",
"header-Sub1":"Hoofdpaneel"
},
"en": {
"lang":"English",
"header-WelcomeText":"Welcome on the website",
"header-Sub1":"Dashboard"
}
}
Javascript/jQuery
var output;
$.get("file.json", function(response){
output = response; //This is now a object in javascript
});
This all works, here what i want:
//The jQuery code
$('span .lang').text(output.nl.$(this).attr("data-lang"));
//The HTML code
<span class="lang" data-lang="header-Sub1"></span>
I know this will not work, but I know there will be a way to achief this.
To make this work there's a few changes you need to make.
when accessing the key of an object through a variable you need to use bracket notation.
to reference the element through the this keyword you need to run your code within it's scope. To do that you can pass a function to the text() method which returns the value you need from the object.
the .lang class is directly on the span, so you shouldn't have the space in your selector.
With all that in mind, this should work for you:
var output = {
"nl": {
"lang": "Nederlands",
"header-WelcomeText": "Welkom op de website",
"header-Sub1": "Hoofdpaneel"
},
"en": {
"lang": "English",
"header-WelcomeText": "Welcome on the website",
"header-Sub1": "Dashboard"
}
}
$('span.lang').text(function() {
return output.nl[$(this).data("lang")];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="lang" data-lang="header-Sub1"></span>

freegeoip doesn't work anymore

A few months ago I created a code that detect a visitor country and display the legal drinking age.
For country in EU is 18 and for other countries is 21.
I'm using the freegeoip.
The code was working great, but now I noticed that doesn't work anymore.
$.get("http://freegeoip.net/json/", function (response) {
$("#ip").html("IP: " + response.ip);
$("#country_code").html(response.country_code);
if(response.country_code=='AL','AD','AT','BY','BE','BA','BG','HR','CY','CZ','DK','EE','FO','FI','FR','DE','GI','GR','HU','IS','IE','IT','LV','LI','LT','LU','MK','MT','MD','MC','NL','NO','PL','PT','RO','RU','SM','RS','SK','SI','ES','SE','CH','UA','VA','RS','IM','RS','ME') {
$(".age").html("18");
} else {
$(".age").html("21");
}
}, "jsonp");
Here I dispay the age:
<span>ARE YOU</span> OVER <span class="age"></span>?
I assume that the problem is in freegeoip but I can't fix it.
You can also use ip-api.com like freegeoip :
function getDataOfIp($ip) {
try {
$pageContent = file_get_contents('http://ip-api.com/json/' . $ip);
$parsedJson = json_decode($pageContent);
return [
"country_name" => $parsedJson->country,
"country_code" => $parsedJson->countryCode,
"time_zone" => $parsedJson->timezone
];
}
catch (Exception $e) {
return null;
}
}
I just found an answer for the problem.
I noticed that the freegeoip.net website doesn't work so I changed the service.
I replaced the http://freegeoip.net/json/ with http://getcitydetails.geobytes.com/GetCityDetails?callback=?
and added <script language="Javascript" src="http://gd.geobytes.com/gd?after=-1&variables=GeobytesLocationCode,GeobytesCode,GeobytesInternet,GeobytesFqcn"></script>
Now the code works again.

Having issues tying together basic javascript chat page

I have the skeleton of a chat page but am having issues tying it all together. What I'm trying to do is have messages sent to the server whenever the user clicks send, and also, for the messages shown to update every 3 seconds. Any insights, tips, or general comments would be much appreciated.
Issues right now:
When I fetch, I append the <ul class="messages"></ul> but don't want to reappend messages I've already fetched.
Make sure my chatSend is working correctly but if I run chatSend, then chatFetch, I don't retrieve the message I sent.
var input1 = document.getElementById('input1'), sendbutton = document.getElementById('sendbutton');
function IsEmpty(){
if (input1.value){
sendbutton.removeAttribute('disabled');
} else {
sendbutton.setAttribute('disabled', '');
}
}
input1.onkeyup = IsEmpty;
function chatFetch(){
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
method: "GET",
success: function(data){
$(".messages").clear();
for(var key in data) {
for(var i in data[key]){
console.log(data[key][i])
$(".messages").append("<li>"+data[key][i].text+"</li>");
}
}
}
})
}
function chatSend(){
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input1.draft').val()}),
success:function(message){
}
})
}
chatFetch();
$("#sendbutton").on('click',chatSend());
This seems like a pretty good project for Knockout.js, especially if you want to make sure you're not re-appending messages you've already sent. Since the library was meant in no small part for that sort of thing, I think it would make sense to leverage it to its full potential. So let's say that your API already takes care of limiting how many messages have come back, searching for the right messages, etc., and focus strictly on the UI. We can start with our Javascript view model of a chat message...
function IM(msg) {
var self = this;
self.username = ko.observable();
self.message = ko.observable();
self.timestamp = ko.observable();
}
This is taking a few liberties and assuming that you get back an IM object which has the name of the user sending the message, and the content, as well as a timestamp for the message. Probably not too far fetched to hope you have access to these data elements, right? Moving on to the large view model encapsulating your IMs...
function vm() {
var self = this;
self.messages = ko.observableArray([]);
self.message = ko.observable(new IM());
self.setup = function () {
self.chatFetch();
self.message().username([user current username] || '');
};
self.chatFetch = function () {
$.getJSON("https://api.parse.com/1/classes/chats", function(results){
for(var key in data) {
// parse your incoming data to get whatever elements you
// can matching the IM view model here then assign it as
// per these examples as closely as possible
var im = new IM();
im.username(data[key][i].username || '');
im.message(data[key][i].message || '');
im.timestamp(data[key][i].message || '');
// the ([JSON data] || '') defaults the property to an
// empty strings so it fails gracefully when no data is
// available to assign to it
self.messages.push(im);
}
});
};
}
All right, so we have out Javascript models which will update the screen via bindings (more on that in a bit) and we're getting and populating data. But how do we update and send IMs? Well, remember that self.message object? We get to use it now.
function vm() {
// ... our setup and initial get code
self.chatSend = function () {
var data = {
'user': self.message().username(),
'text': self.message().message(),
'time': new Date()
};
$.post("https://api.parse.com/1/classes/chats", data, function(result) {
// do whatever you want with the results, if anything
});
// now we update our current messages and load new ones
self.chatFetch();
};
}
All right, so how do we keep track of all of this? Through the magic of bindings. Well, it's not magic, it's pretty intense Javascript inside Knockout.js that listens for changes and the updates the elements accordingly, but you don't have to worry about that. You can just worry about your HTML which should look like this...
<div id="chat">
<ul data-bind="foreach: messages">
<li>
<span data-bind="text: username"></span> :
<span data-bind="text: message"></span> [
<span data-bind="text: timestamp"></span> ]
</li>
</ul>
</div>
<div id="chatInput">
<input data-bind="value: message" type="text" placeholder="message..." />
<button data-bind="click: $root.chatSend()">Send</button>
<div>
Now for the final step to populate your bindings and keep them updated, is to call your view model and its methods...
$(document).ready(function () {
var imVM = new vm();
// perform your initial search and setup
imVM.setup();
// apply the bindings and hook it all together
ko.applyBindings(imVM.messages, $('#chat')[0]);
ko.applyBindings(imVM.message, $('#chatInput')[0]);
// and now update the form every three seconds
setInterval(function() { imVM.chatFetch(); }, 3000);
});
So this should give you a pretty decent start on a chat system in an HTML page. I'll leave the validation, styling, and prettifying as an exercise to the programmer...

Get twitter tweet into javascript variable for display...?

This is going to be a bit more vague than usual as I am looking for direction and don't really have any code to share, yet.
On my business webpage there is a jquery plugin welcome message (growl style) that is populated by the text I have typed into the JS file. In my hopes to make changing this text easier for my employees I was hoping I could somehow get my most recent tweet into a variable that I could then display automatically... this way there is no changing of code needed.
My hope was to somehow take a string like, "This is a title:this is the message" and be able to separate them into 2 different variable by means of the colon as a seperator. Then I could display these variable using their var name.
This would be an example of the final product, minus the twitter parsing:
jQuery(function($) {
$("#stdWelcome").ready(function(){
growlwelcomeid = ("gs"+$.Growl._statsCount);
$.Growl.show(TwitterMessage, {
'title' : TwitterTitle,
'icon' : "star",
'timeout': "10000",
'speed': "900"
});
});
});
Any help would be greatly appreciated!
UPDATE:
So how would something like this look:
var Wusername = "username";
var Wurl = 'http://api.twitter.com/1/statuses/user_timeline/'+Wusername+'.json?callback=?';
$.getJSON(Wurl, function(tweet){
$Wtitle = tweet[0].text.split('|');
});
jQuery(function($) {
$("#stdWelcome").ready(function(){
growlwelcomeid = ("gs"+$.Growl._statsCount);
$.Growl.show(Wtitle[1], {
'title' : Wtitle[0],
'icon' : "star",
'timeout': "10000",
'speed': "900"
});
});
});
Thanks again!
If you had the title and message as seperate tweets you could do the following
var username = "twitter username";
var url = 'http://api.twitter.com/1/statuses/user_timeline/'+username+'.json?callback=?';
$.getJSON(url, function(tweet){
$title = tweet[0].text;
$message = tweet[1].text;
});
You can make a request to the Twitter API to retrieve the 'timeline' for a given user.
https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=USERNAME&count=1
https://dev.twitter.com/docs/api/1/get/statuses/user_timeline
Edit: See #Jon Taylor's post for an implementation
This probably isn't going to be what you're going for, but here's a twitter widget I coded a while back. I've included the JS that the client can edit (top section) along with the compressed "gears and working parts" that they shouldn't edit, along with the HTML container. Obviously you'll need to add your own CSS and customize as needed.
Here's a working example: ( jsfiddle )
/* Twitter initiates. Enter your username here. */
jQuery(function($){
$(".tweeter_widget").tweet({
join_text: "auto",
username: "YOUR_USERNAME",
avatar_size: null,
count: 1,
auto_join_text_default: "",
auto_join_text_ed: "",
auto_join_text_ing: "",
auto_join_text_reply: "",
auto_join_text_url: "",
loading_text: "loading tweets..."
})
// if tweet is over 106 characters long, set the line-height so that the text will wrap to the next line and appear centered in the tweet bar.
.bind("loaded", function() {
var $tweet = $(".tweet_first"); // maybe using $(this) is better
var $numWords = $tweet.text().length;
if (($numWords >= 1) && ($numWords > 106)) {
$tweet.css({ "line-height": "24px !important" });
}
else {
$tweet.css({ "line-height": "50px !important" });
}
});
});
Compressed code to go along with:
//twitter widget
(function(a){a.fn.tweet=function(b){function l(b){var d={};d.item=b;d.source=b.source;d.screen_name=b.from_user||b.user.screen_name;d.avatar_size=c.avatar_size;d.avatar_url=j(b.profile_image_url||b.user.profile_image_url);d.retweet=typeof b.retweeted_status!="undefined";d.tweet_time=g(b.created_at);d.join_text=c.join_text=="auto"?i(b.text):c.join_text;d.tweet_id=b.id_str;d.twitter_base="http://"+c.twitter_url+"/";d.user_url=d.twitter_base+d.screen_name;d.tweet_url=d.user_url+"/status/"+d.tweet_id;d.reply_url=d.twitter_base+"intent/tweet?in_reply_to="+d.tweet_id;d.retweet_url=d.twitter_base+"intent/retweet?tweet_id="+d.tweet_id;d.favorite_url=d.twitter_base+"intent/favorite?tweet_id="+d.tweet_id;d.retweeted_screen_name=d.retweet&&b.retweeted_status.user.screen_name;d.tweet_relative_time=h(d.tweet_time);d.tweet_raw_text=d.retweet?"RT #"+d.retweeted_screen_name+" "+b.retweeted_status.text:b.text;d.tweet_text=a([d.tweet_raw_text]).linkUrl().linkUser().linkHash()[0];d.tweet_text_fancy=a([d.tweet_text]).makeHeart().capAwesome().capEpic()[0];d.user=e('<a class="tweet_user" href="{user_url}" target="_blank">{screen_name}</a>',d);d.join=c.join_text?e(' <span class="tweet_join">{join_text}</span> ',d):" ";d.avatar=d.avatar_size?e('<a class="tweet_avatar" href="{user_url}" target="_blank"><img src="{avatar_url}" height="{avatar_size}" width="{avatar_size}" alt="{screen_name}\'s avatar" title="{screen_name}\'s avatar" border="0"/></a>',d):"";d.time=e('<span class="tweet_time">{tweet_relative_time}</span>',d);d.text=e('<span class="tweet_text">{tweet_text_fancy}</span>',d);d.reply_action=e('<a class="tweet_action tweet_reply" href="{reply_url}" target="_blank">reply</a>',d);d.retweet_action=e('<a class="tweet_action tweet_retweet" href="{retweet_url}" target="_blank">retweet</a>',d);d.favorite_action=e('<a class="tweet_action tweet_favorite" href="{favorite_url}" target="_blank">favorite</a>',d);return d}function k(){var a="https:"==document.location.protocol?"https:":"http:";var b=c.fetch===null?c.count:c.fetch;if(c.list){return a+"//"+c.twitter_api_url+"/1/"+c.username[0]+"/lists/"+c.list+"/statuses.json?page="+c.page+"&per_page="+b+"&callback=?"}else if(c.favorites){return a+"//"+c.twitter_api_url+"/favorites/"+c.username[0]+".json?page="+c.page+"&count="+b+"&callback=?"}else if(c.query===null&&c.username.length==1){return a+"//"+c.twitter_api_url+"/1/statuses/user_timeline.json?screen_name="+c.username[0]+"&count="+b+(c.retweets?"&include_rts=1":"")+"&page="+c.page+"&callback=?"}else{var d=c.query||"from:"+c.username.join(" OR from:");return a+"//"+c.twitter_search_url+"/search.json?&q="+encodeURIComponent(d)+"&rpp="+b+"&page="+c.page+"&callback=?"}}function j(a){return"https:"==document.location.protocol?a.replace(/^http:/,"https:"):a}function i(a){if(a.match(/^(#([A-Za-z0-9-_]+)) .*/i)){return c.auto_join_text_reply}else if(a.match(d)){return c.auto_join_text_url}else if(a.match(/^((\w+ed)|just) .*/im)){return c.auto_join_text_ed}else if(a.match(/^(\w*ing) .*/i)){return c.auto_join_text_ing}else{return c.auto_join_text_default}}function h(a){var b=arguments.length>1?arguments[1]:new Date;var c=parseInt((b.getTime()-a)/1e3,10);var d="";if(c<60){d=c+" seconds ago"}else if(c<120){d="a minute ago"}else if(c<45*60){d=parseInt(c/60,10).toString()+" minutes ago"}else if(c<2*60*60){d="an hour ago"}else if(c<24*60*60){d=""+parseInt(c/3600,10).toString()+" hours ago"}else if(c<48*60*60){d="a day ago"}else{d=parseInt(c/86400,10).toString()+" days ago"}return" "+d}function g(a){return Date.parse(a.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i,"$1,$2$4$3"))}function f(b,c){return function(){var d=[];this.each(function(){d.push(this.replace(b,c))});return a(d)}}function e(a,b){if(typeof a==="string"){var c=a;for(var d in b){var e=b[d];c=c.replace(new RegExp("{"+d+"}","g"),e===null?"":e)}return c}else return a(b)}var c=a.extend({username:null,list:null,favorites:false,query:null,avatar_size:null,count:3,fetch:null,page:1,retweets:true,intro_text:null,outro_text:null,join_text:null,auto_join_text_default:"i said,",auto_join_text_ed:"i",auto_join_text_ing:"i am",auto_join_text_reply:"i replied to",auto_join_text_url:"i was looking at",loading_text:null,refresh_interval:null,twitter_url:"twitter.com",twitter_api_url:"api.twitter.com",twitter_search_url:"search.twitter.com",template:"{avatar}{time}{join}{text}",comparator:function(a,b){return b["tweet_time"]-a["tweet_time"]},filter:function(a){return true}},b);var d=/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;a.extend({tweet:{t:e}});a.fn.extend({linkUrl:f(d,function(a){var b=/^[a-z]+:/i.test(a)?a:"http://"+a;return''+a+""}),linkUser:f(/#(\w+)/gi,'#$1'),linkHash:f(/(?:^| )[\#]+([\w\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0600-\u06ff]+)/gi,' #$1'),capAwesome:f(/\b(awesome)\b/gi,'<span class="awesome">$1</span>'),capEpic:f(/\b(epic)\b/gi,'<span class="epic">$1</span>'),makeHeart:f(/(<)+[3]/gi,"<tt class='heart'>♥</tt>")});return this.each(function(b,d){var f=a('<ul class="tweet_list">').appendTo(d);var g='<p class="tweet_intro">'+c.intro_text+"</p>";var h='<p class="tweet_outro">'+c.outro_text+"</p>";var i=a('<p class="loading">'+c.loading_text+"</p>");if(c.username&&typeof c.username=="string"){c.username=[c.username]}if(c.loading_text)a(d).append(i);a(d).bind("tweet:load",function(){a.getJSON(k(),function(b){if(c.loading_text)i.remove();if(c.intro_text)f.before(g);f.empty();var j=a.map(b.results||b,l);j=a.grep(j,c.filter).sort(c.comparator).slice(0,c.count);f.append(a.map(j,function(a){return"<li>"+e(c.template,a)+"</li>"}).join("")).children("li:first").addClass("tweet_first").end().children("li:odd").addClass("tweet_even").end().children("li:even").addClass("tweet_odd");if(c.outro_text)f.after(h);a(d).trigger("loaded").trigger(j.length===0?"empty":"full");if(c.refresh_interval){window.setTimeout(function(){a(d).trigger("tweet:load")},1e3*c.refresh_interval)}})}).trigger("tweet:load")})}})(jQuery);
and then HTML container:
<section class="footer-top">
<div class="f-top-inner" id="follow-me"> <a class="twit-logo" href="https://twitter.com/intent/follow?original_referer=https%3A%2F%2Ftwitter.com%2Fabout%2Fresources%2Fbuttons&screen_name=YOUR_USER_NAME&source=followbutton&variant=2.0" title="Follow Us" target="_blank" onClick="_gaq.push(['_trackEvent', 'Social', 'Social_Click', 'Twitter']);"></a>
<!--tweet position-->
<div class="tweeter_widget" id="tweetDiv"></div>
</div>
</section>

Categories