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

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>

Related

Js: customize #tag value generated by field name 'via' in addthis twitter share JS Plugin

i need to share a hashtag (example: #myPlutonicHash) from my website to twitter account. i have used addThis javascript object present in addThis plugin Feature, as shown below
var addthis_share = {};
addthis_share = {
title : 'PlutonicTitle',
passthrough : {
twitter: {
via: "#myPlutonicHash"
}
}
};
From my website, When i click twitter icon to share the title of my website and required #tag, i get the following output which is the default text output format when used field 'via' in twitter textbox.
Output1
PlutonicTitle via ##myPlutonicHash
But, i dont need the text 'via' and '#' in my twitter text box. i need to customize the default text output format of field 'via'.
My required text output is shown below.
Output2
PlutonicTitle #myPlutonicHash
kindly help me out in getting my required output.
You're almost there. Here's how to do it:
var addthis_share = {};
addthis_share = {
title : 'PlutonicTitle',
passthrough : {
twitter: {
hashtags: "myPlutonicHash"
}
}
};
If you want more than one hash tag, separate them with commas like this:
var addthis_share = {};
addthis_share = {
title : 'PlutonicTitle',
passthrough : {
twitter: {
hashtags: "myPlutonicHash,myOtherPlutonicHash"
}
}
};
If you've got more questions send us an email at help#addthis.com

Parsing Dynamic JSON Generated From Website (CoovaChilli) And Display It Into Javascript Webpage?

i really need your help to help me solving my problem. I setup a captive portal using CoovaChilli, and want to show the usage feedback provided by Coova JSON Interface that can be accessed via url like this http://login.domain.com:3990/json/status from the internal network where the CoovaChilli listen on. If you already logged in into the captive portal and then if you access that url you will see data formated like this in your browser:
{
"version": "1.0",
"clientState": 1,
"redir": {
"originalURL": "http://www.gstatic.com/generate_204",
"redirectionURL": "",
"logoutURL": "http://10.1.0.1:3990/logoff",
"ipAddress": "10.1.0.6",
"macAddress": "AA-BB-CC-DD-EE-FF"
},
"session": {
"sessionId": "5108c39600000003",
"userName": "user#ri",
"startTime": 1359529249,
"sessionTimeout": 0,
"idleTimeout": 900
},
"accounting": {
"sessionTime": 867,
"idleTime": 0,
"inputOctets": 1428643,
"outputOctets": 391752,
"inputGigawords": 0,
"outputGigawords": 0,
"viewPoint": "client"
}
}
My question is, what should i do if want to parsing that data into a webpage using *Javascript* so i can see that data formatted more nicely (html formatted). For example i can access it via url using same domain like this http://login.domain.com/status/status.html rather than unformatted data in the previous url ?
Please note : i want use javascript to parsing because the data is different by the user who logged in into that CoovaChilli, different user have different data, only user who logged in and accessing that url can see only their own statistic, so i think the best practice is use a client side language to parsing that data.
Any of your help is very appreciated. Thank you before.
Try this
This link may help you http://www.w3schools.com/json/json_intro.asp
<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p>
Name: <span id="jname"></span><br>
Age: <span id="jage"></span><br>
Address: <span id="jstreet"></span><br>
Phone: <span id="jphone"></span><br>
</p>
<script>
var JSONObject = {
"name":"John Johnson",
"street":"Oslo West 16",
"age":33,
"phone":"555 1234567"};
document.getElementById("jname").innerHTML=JSONObject.name
document.getElementById("jage").innerHTML=JSONObject.age
document.getElementById("jstreet").innerHTML=JSONObject.street
document.getElementById("jphone").innerHTML=JSONObject.phone
</script>
</body>
</html>
Edit
If you want to remove var json you can use ajax or jquery
eg:
$.getJSON("your url",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
http://www.w3schools.com/jquery/ajax_getjson.asp
<script src="js/jquery.min.js"></script>
<script>
$.getJSON("http://10.1.0.1:3990/json/status?callback=?", function(data) {
console.log(data);
});
</script>

routing/asset pipeline issue - undefined javascript method

I'm getting back into Rails (it's been a few years) so I'm pretty sure I'm just missing something simple. Tho it could also be my lack of understand of how javascript works within Rails.
I think I have my view (in haml) set up correctly. I have added the javascript to a file that I made sure was included in the layout. (And the css looks right.) I'm just not getting the javascript function (a slideshow I found online) to connect to the view. I'm trying to use %body{ :onload => setUpslideShow() }
Here's my view:
%body{ :onload => setUpSlideShow() }
%script{type: 'text/javascript'}
if ( ! window.CMFmainmenu ) { CMFmainmenu = {}; }
var s = CMFmainmenu;
s.user_id = "#{#user.id.to_s}";
s.partial_mainmenu_path = "/users/" + s.user_id + "/xx/mainmenu";
s.add_new_senior = "#{UsersController::ADD_NEW_SENIOR}"
s.add_new_senior_path = "#{new_seniors_settings_path(#locale,#user,#senior)}"
#mainmenu
... (edited out to save space) ...
#slideshow.greenBorder
#slides
= image_tag '/assets/newlook/div_1_img.png', class: 'slide'
%p
Everyone loves photo albums.
Get your user ready to brag, and
populate and arrange albums by
event, special people, year or any
category you can imagine.
=link_to "Learn how.", ''
= image_tag '/assets/newlook/div_2_img.png', class: 'slide'
%p
If typing is difficult for your
loved one, remove the frustration
of a typed response. They can
respond with a voice message, or
with auto replies that you set up.
=link_to "Learn how.", ''
= image_tag '/assets/newlook/div_3_img.png', class: 'slide'
%p
Arms too short? You can specify
the minimum font size used for
your user's email.
=link_to "Learn how.", ''
#slides-controls
1
2
3
Here's my javascript:
if (! window.CMFuser) { CMFuser = {}; }
$(function() {
var s = CMFuser;
... (edited out to save space) ...
// slideshow
slidePrefix = "slide-";
slideControlPrefix = "slide-control-";
slideHighlightClass = "highlight";
slidesContainerID = "slides";
slidesControlsID = "slides-controls";
setUpSlideShow = function()
{
... lots of code that doesn't get called so I'm leaving it out to save space ...
And here's what I think the relevant line is in the layout: = javascript_include_tag "lib/modernizr-2.0.6.min", "lib/respond.min","application", "users" where "users" is the javascript file. When I comment out the %body{ :onload => setUpslideShow() }, the javascript file appears in the html source.
The full text of the error:
NoMethodError in Users#mainmenu
Showing /opt/cmf/app/views/users/mainmenu.html.haml where line #4 raised:
undefined method `setUpSlideShow' for #<#<Class:0x007fe054fa0a28>:0x007fe05594ae20>
Extracted source (around line #4):
2: - # users/mainmenu
3:
4: %body{ :onload => setUpSlideShow() }
Thanks
Shouldn't the value for :onload be a string?
%body{ :onload => 'setUpSlideShow()' }
You do want to produce this HTML after all, right?
<body onload="setUpSideShow()">

Inserting Anchors in a Javascript Photo Gallery - Not Working?

I am using jAlbum(with the lightflow skin) to create a photo gallery for my website. The gallery loads and is in a nice carousel format. I would like to add anchors that way I can link directly to a certain photo within the gallery. I tried to add an anchor in the HTML yet it does not work. I assume this is because when the page loads the gallery takes a few seconds to load and thus does not redirect to the anchor. I easily could be wrong and need some advice on what I should try to get anchors to work. Here is an example code for the anchor and the photo itself:
<div class="item">
<a name="anchor3" id="anchor3"></a>
<img class="content hidden" src="thumbs/tree-w-sun.jpg" alt="Gifts" />
<div class="ref hidden">item8</div>
<div class="caption"><h3>Gifts</h3></div>
<div class="comment hidden"></div>
<div class="author hidden"></div>
<div class="params hidden"></div>
<div class="info hidden"><div><p>Artist: UBhapE2</p></div></div>
<div class="thumbWidth hidden">261</div>
<div class="thumbHeight hidden">350</div>
<a id="item8" class="lightwindow hidden" title="<h3>Gifts</h3>"
rel="gal[cat]" href="slides/tree-w-sun.jpg" ></a>
</div>
I have tried linking to the anchor I inserted (anchor3) and to the id inserted by jAlbum (item8) and neither work.
There are a few scripts that control the gallery and will put them here:
Script 1 - "Lightflow JS"
var LightFlowGlobal = {};
function getParam( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
Script 2 - "ContentFlow JS" This JS is long and for sake of space I put the link directly to the JS file here
Script 3 - This script is in the page:
<script language="JavaScript" type="text/javascript">
var startItem = getParam('p');
if(startItem == "") startItem = "first";
if(startItem.isNaN) startItem = "'"+startItem+"'";
new ContentFlow('contentFlow', {
reflectionColor: "#000000",
maxItemHeight: 350,
marginTop: 50,
reflectionHeight: 0.25,
endOpacity: 1,
startItem: startItem,
circularFlow: false,
stretchThumbs: false
});
function lightWindowInit() {
LightFlowGlobal.myLightWindow = new lightwindow({
infoTabName : "More Info",
rootPath: "res/lightwindow/",
loadingTxt: "loading or ",
cancelTxt: "cancel",
playTxt: "start slideshow",
stopTxt: "stop slideshow",
slowerTxt: "slower by 1 second",
fasterTxt: "faster by 1 second",
downloadSlideTxt: "Download",
downloadSlide: false,
showSlideshow: false,
slideshowDuration: 5000,
circular: false,
animationDuration: 0.25
});
}
LightFlowGlobal.readyJS=true;
var rootPath = ".";
</script>
I am unsure what other scripts or css is needed. I link to the test-gallery I am working with here if you need to view the page. I will post additional info if requested.
So now how do I get anchors to work with this? I am not that great at javascript so please explain the answer vs "you need to add this function to the script" without explaining.
Thank Your for any and all assistance!
On the ContentFlow site, under Documentation --> items as links, the developer specifically states that "no element within the item may contain any anchors". maybe someone can offer a way around this restriction.
I figured out a way answer was provided by the Photo Gallery Creater:
It's not only the js. You'd need to pass a parameter to AddThis in order to
identify the image. Without it, you wouldn't know which image has been clicked.
The best would be to use LightFlow's query paramter p=index, where index is the
number of the image of the current web page.
For example, the following link would focus the 4th image of the gallery
(index begins at 0): http://your-domain.com/album/index.html?p=3

How to insert variables into text when storing content in an object?

I'm using the code below to insert content into a page. I need to insert some variables in the text to generate some dynamic values and am unsure how to do this. Can someone tell me what I'd need to change?
Here's a slimmed down example of how I'm storing the data in my JS:
var fruit = {
'apples': {
'goldenDelicious' : {
color: 'yellow',
sale: 'A sale of $XXXXX (need to insert a number in here). Be sure to buy some before they are all gone!',
link: {
linkText: ('This company sells this for $XXXXX (eed to insert a price here). Click here to visit their site.'),
url: 'I NEED TO INSERT THE URL HERE'
}
}
}
}
Here's an example of how I'm calling it: (it's more dynamic than this, but you get the idea)
var fruitType = 'apples';
var fruitVariety = 'goldenDelicious';
fruit[fruitType][fruitVariety], function () {
// do something
});
So what I'd like is to be able to insert values like a price, sale, and URL into the object.
There are a bunch of ways to do this. If you're going to be doing a lot of this type of replacement, you'll probably want to look at a templating engine. I've been using Trimpath, and am happy with it.
If you don't want to get that fancy yet, put your own placeholder tokens in the string and then replace them.
var fruit = {
'apples': {
'goldenDelicious' : {
color: 'yellow',
sale: 'A sale of PLACEHOLDER_1. Be sure to buy some before they are all gone!',
link: {
linkText: ('This company sells this for PLACEHOLDER_2. Click here to visit their site.'),
url: 'I NEED TO INSERT THE URL HERE'
}
}
}
}
fruit.apples.goldenDelicious.sale = fruit.apples.goldenDelicious.sale.replace("PLACEHOLDER_1", "the real value");

Categories