code giving error "mail.getRange is not a function" - for-loop

I have a code that sends an email for every row that satisfies the condition that column CQ= "SI", there are currently 3 rows that satisfy the condition, however when I run the code an email for the first row that meets the criteria is sent and then I get the error mail.getRange is not a function. I am trying to pull a cell that contains a list of emails and I don't understand why it works for the first email that is sent and then stops working. The error is in line 58: var mail= mail.getRange(1,1).getValues();
The code is the following:
function maildrops(){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName("REFERENCIAS");
var mail = spreadsheet.getSheetByName("emails");
var lista_refes = SpreadsheetApp.getActive().getSheetByName("REFERENCIAS").getRange("D2:D").getValues(); //event list
var lista_refes_ok1 = lista_refes.reduce(function(ar, e) {
if (e[0]) ar.push(e[0])
return ar;
}, []);
var nombre = SpreadsheetApp.getActive().getSheetByName("REFERENCIAS").getRange("F2:F").getValues(); //event list
var nombre1 = nombre.reduce(function(ar, e) {
if (e[0]) ar.push(e[0])
return ar;
}, []);
var drop = SpreadsheetApp.getActive().getSheetByName("REFERENCIAS").getRange("BB2:BB").getValues(); //event list
var dropv = SpreadsheetApp.getActive().getSheetByName("REFERENCIAS").getRange("CP2:CP").getValues(); //event list
var tickn = SpreadsheetApp.getActive().getSheetByName("REFERENCIAS").getRange("CQ2:CQ").getValues(); //event list
for (var i = 0; i < lista_refes_ok1.length; i++) {
var responses = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("REFERENCIAS");
var nom = nombre1[i];
var dropa = drop[i];
var dropvv = dropv[i];
var refe = lista_refes_ok1[i];
var tick = tickn[i];
if (tick == "SI" ){
var subject = "SS23 cambios drop: " + refe + ".";
var body = "Hola chicos, el modelo " + refe + " " + nom+ " ha cambiado del drop " + dropvv + " al drop " + dropa+ ". \n\nCualquier cosa, podéis contestar a este mail :)";
var mail= mail.getRange(1,1).getValues()
GmailApp.sendEmail(mail, subject, body);
}
}
sheet.getRange('CP3:CP').activate();
sheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: false});
}
The last rows of the code are trying to empty the content of column CP after the emails have been sent, I have not been able to check if this part of the code is right because I get the error before getting to these lines.
Does anybody know how to fix the error? Any help is appreciated :)

In your script, from var mail = spreadsheet.getSheetByName("emails");, mail is Sheet object. But, at var mail = mail.getRange(1, 1).getValues(), mail is declared at the 1st loop. By this, after the 2nd loop, mail becomes a 2-dimensional array. Under this condition, when var mail = mail.getRange(1, 1).getValues() is run, such the error occurs. I thought that this might be the reason for your issue. In order to remove this issue, how about the following modification?
From:
for (var i = 0; i < lista_refes_ok1.length; i++) {
var responses = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("REFERENCIAS");
var nom = nombre1[i];
var dropa = drop[i];
var dropvv = dropv[i];
var refe = lista_refes_ok1[i];
var tick = tickn[i];
if (tick == "SI") {
var subject = "SS23 cambios drop: " + refe + ".";
var body = "Hola chicos, el modelo " + refe + " " + nom + " ha cambiado del drop " + dropvv + " al drop " + dropa + ". \n\nCualquier cosa, podéis contestar a este mail :)";
var mail = mail.getRange(1, 1).getValues()
GmailApp.sendEmail(mail, subject, body);
}
}
To:
var emailAddress = mail.getRange(1, 1).getValue();
for (var i = 0; i < lista_refes_ok1.length; i++) {
// var responses = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("REFERENCIAS"); // It seems that this is not used.
var nom = nombre1[i];
var dropa = drop[i];
var dropvv = dropv[i];
var refe = lista_refes_ok1[i];
var tick = tickn[i];
if (tick == "SI") {
var subject = "SS23 cambios drop: " + refe + ".";
var body = "Hola chicos, el modelo " + refe + " " + nom + " ha cambiado del drop " + dropvv + " al drop " + dropa + ". \n\nCualquier cosa, podéis contestar a este mail :)";
GmailApp.sendEmail(emailAddress, subject, body);
}
}

Related

Script runs too long after emails already sent

I am trying to have this code send emails faster and not hang up so much. Taking along time to end the script. How can I send the emails and end it quicker? That way if I need to send out more emails, it can run the whole script again.
function sendEmails() {
//Current spreadsheet emails are sent from
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Search Index").activate();
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var RowCountEmailPresent = 0
for (var i = 5;i<=lr;i++) {
var currentEmail = ss.getRange(i, 2).getValue();
if (currentEmail.includes('#')) {
RowCountEmailPresent = RowCountEmailPresent + 1
}
}
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
//How Many Sends We have left
var quotaLeft = MailApp.getRemainingDailyQuota();
if((RowCountEmailPresent) > quotaLeft){
Browser.msgBox("You have " + quotaLeft + "left and you're trying to send " + (lr-1) + " emails. Emails were not sent.");
}
else {
for (var i = 5;i<=lr;i++) {
//What values are being placed in the email
var currentEmail = ss.getRange(i, 2).getValue();
var ccmail = ss.getRange(i, 1).getValue();
var AlreadySent = ss.getRange(i, 3).getValue();
var currentStatus = ss.getRange(i, 7).getValue();
var currentOrdernumber = ss.getRange(i, 6).getValue();
var currentMon = ss.getRange(i, 6).getValue();
var code = ss.getRange(i, 13).getValue();
//Actual email being sent to Reps and TLs
var messageBody = templateText.replace("{Order Number}", currentMon).replace("{Jep Code}", code);
var subjectLine = "Offline Support - Order Status: " + currentStatus + " - Mon#: " + currentOrdernumber;
if (currentEmail.includes('#')) {
if (AlreadySent < 1){
MailApp.sendEmail(currentEmail, subjectLine, messageBody, {cc: ccmail})
ss.getRange(i, 3).setValue('1');
}
}
} // close for loop
} //close else statment
SpreadsheetApp.getUi().alert("Congratulations, your email has been sent", SpreadsheetApp.getUi().ButtonSet.OK);
}
See If this improves your efficiency.
var AlreadySent = ss.getRange(i, 3).getValue();
if (AlreadySent < 1){
var currentEmail = ss.getRange(i, 2).getValue();
if (currentEmail.includes('#')) {
var ccmail = ss.getRange(i, 1).getValue();
var currentStatus = ss.getRange(i, 7).getValue();
var currentOrdernumber = ss.getRange(i, 6).getValue();
var currentMon = ss.getRange(i, 6).getValue();
var code = ss.getRange(i, 13).getValue();
var messageBody = templateText.replace("{Order Number}", currentMon).replace("{Jep Code}", code);
var subjectLine = "Offline Support - Order Status: " + currentStatus + " - Mon#: " + currentOrdernumber;
MailApp.sendEmail(currentEmail, subjectLine, messageBody, {cc: ccmail})
ss.getRange(i, 3).setValue('1');
}
}

JQGrid setGridParam URL not working in firebox, the same code in working chrome, but its not not working firebox,

Here is my code , the same code hitting the URL in chrome, setGridParam function is not working properly, but its not working in firebox, i tried as much as possible ways, please help me to out.
Cur_Status = $("#ddlStatus option:selected").val();
var FromDate = $("#txtFromDate").attr("value");
var ToDate = $("#txtToDate").attr("value");
var pieces = FromDate.split('/');
pieces.reverse();
FromDate = pieces.join('-');
var pieces = ToDate.split('/');
pieces.reverse();
ToDate = pieces.join('-');
if (new Date(FromDate) > new Date(ToDate)) {
alert("Please select ToDate greater than FromDate.");
return false;
}
var MyCall = 0;
var check = document.getElementById("ChkMycall").checked;
if (check) {
MyCall = 1;
}
else {
MyCall = 0;
}
var CheckStatus =
$('input:radio[name=rbt_Type]:checked').val();
FromDate = $("#txtFromDate").attr("value");
ToDate = $("#txtToDate").attr("value");
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
var today = mm + '/' + yyyy;
var Cur_Date = today;
var qryStr = CheckStatus + "^" + FromDate + "^" + ToDate + "^" + MyCall;
$("#tblCallStatus").jqGrid("clearGridData");
$("#tblCallStatus").setGridParam({ url: "../Handlers/CallStatusHandler.ashx? Mode=Load & iStatus=" + Cur_Status + "&Date=" + Cur_Date + "& QryString=" + qryStr, datatype: "json" });
$("#tblCallStatus").trigger('reloadGrid');
this the code i am using, to hit the URL, through the javascript i try to load the JQGrid.
The URL, which you set contains a lot of spaces, which should be not used. Try to replace
url: "../Handlers/CallStatusHandler.ashx? Mode=Load & iStatus=" + Cur_Status + "&Date=" + Cur_Date + "& QryString=" + qryStr
to
url: "../Handlers/CallStatusHandler.ashx?Mode=Load&iStatus=" + Cur_Status + "&Date=" + Cur_Date + "&QryString=" + qryStr

How to loop 2 Dimensional Array on Google Script

There is a problem with my run time execution in my code. It takes too long to finish, since I have to loop a large amounts of data to look for matching data. I used array on the first loop value though, I don't know how to array the second value without affecting the first array.
Name of the first array : Source
Name of the Second array : Target
Here is my Code:
function inactive_sort_cebu() {
var ss = SpreadsheetApp.openById('169vIeTMLK4zN5VGCw1ktRteCwMToU8eGABFDxg52QBk');
// var sheet = ss.getSheets()[0];// Manila Roster
var sheet2 = ss.getSheets()[1];// Cebu Roster
var column = sheet2.getRange("C1:C").getValues();
var last = column.filter(String).length;
// -----------------------------------------------------------
var ss1 = SpreadsheetApp.openById('153ul2x2GpSopfMkCZiXCjmqdPTYhx4QiOdP5SBYzQkc');
// var sched_sheet = ss1.getSheets()[0];// ScheduledForm_Manila
var sched_sheet2 = ss1.getSheets()[1];// ScheduledForm_Cebu
var column2 = sched_sheet2.getRange("C1:C").getValues();
var last2 = column2.filter(String).length;
//// -------------------------Manila-Roster---------------------------------
var i= 2;
var column3 = sched_sheet2.getRange("J1:J").getValues();
var a = column3.filter(String).length - 1;
// var a = 0;
try{
var source = sched_sheet2.getRange("C2:C").getValues();
for (a;a<=last2;){
/// this is the code that i need to array without affecting the other array which is the source variable
var target = sheet2.getRange("C"+ i).getValue();
if(source[a] == target){
// Get "No Schedule Request data on Cell H
var data = sched_sheet2.getRange("H"+(a+2)).getValue();
// Get "Schedule Request data on Cell F
var data1 = sched_sheet2.getRange("F"+(a+2)).getValue();
var condition_1 = sched_sheet2.getRange("D"+(a+2)).getValue();
var condition_2 = sched_sheet2.getRange("G"+(a+2)).getValue();
var format_Con_2 = Utilities.formatDate(condition_2, 'Asia/Manila', 'm/dd/yyyy');
var condition_3 = sched_sheet2.getRange("K"+ (a+2)).getValue();
var date = new Date();
var date_Manila = Utilities.formatDate(date, 'Asia/Manila', 'm/dd/yyyy');
if(condition_1 == "No Schedule Request" && format_Con_2 <= date_Manila && condition_3 ==""){
sheet2.getRange("AA"+ i).setValue("N - "+ data);
sched_sheet2.getRange("J"+ (a+2)).setValue("Cebu");
sched_sheet2.getRange("K"+ (a+2)).setValue("Done");
a++;
}
else if (condition_1 == "Schedule Request" && format_Con_2 <= date_Manila && condition_3 ==""){
sheet2.getRange("AA"+ i).setValue("Y - "+data1);
sched_sheet2.getRange("J"+ (a+2)).setValue("Cebu");
sched_sheet2.getRange("K"+ (a+2)).setValue("Done");
a++;
}
else{a++;}
i=2;}
else {i++;}
}
This is a simple example of a web app that puts an editable spreadsheet on an HTML Page. Publish as a webapp. I loops through the 2D array that you get when you getValues from the getDataRange() method. In this case I'm just intertwining html into the mix.
Code.gs:
var SSID='SpreadsheetID';
var sheetName='Sheet Name';
function htmlSpreadsheet(mode)
{
var mode=(typeof(mode)!='undefined')?mode:'dialog';
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
//s+='<div id="success"></div>';
s+='</body></html>';
switch (mode)
{
case 'dialog':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
userInterface.append(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Spreadsheet Data for ' + ss.getName() + ' Sheet: ' + sht.getName());
break;
case 'web':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.append(s).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
}
function updateSpreadsheet(i,j,value)
{
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet()
{
var output=htmlSpreadsheet('web');
return output;
}
htmlss.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
});
function updateSS(i,j)
{
var str='#txt' + String(i) + String(j);
var value=$(str).val();
$(str).css('background-color','#ffff00');
google.script.run
.withSuccessHandler(successHandler)
.updateSpreadsheet(i,j,value)
}
function successHandler(data)
{
$('#success').text(data.message);
$('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
}
console.log('My Code');
</script>
<style>
th{text-align:left}
</style>
</head>
<body>
<div id="success"></div>

Scroll Events in TouchGridPanel

I am building a mobile application using Sencha Touch 1.0. I need to display report, for that am using grid given by Ext.ux.TouchGridPanel.
It is working fine.
Where as I need to capture Scroll event in Ext.ux.TouchGridPanel.
I have added 'scroll' in bubble event of Dataview.
I am also trying to capture the event after the Dataview created.
But nothing seems to be working. Below is the code which I have changed.
Does anybody has any idea how to capture the start of scroll event?
Thanks in advance.
Ext.ux.TouchGridPanel = Ext.extend(Ext.Panel, {
layout: "fit",
multiSelect: false,
initComponent: function () {
var me = this;
me.items = me.dataview = me.buildDataView();
Ext.ux.TouchGridPanel.superclass.initComponent.call(me);
var store = me.store;
store.on("update", me.dispatchDataChanged, me);
var dataview = me.dataview;
dataview.on('scroll', me.startScroll);
},
dispatchDataChanged: function (store, rec, operation) {
var me = this;
me.fireEvent("storeupdate", store, rec, operation);
},
startScroll: function (scroller, offset) {
console.log('is this event captured???')
var me = this;
me.fireEvent("scroll", this.scroller, offset);
},
buildDataView: function () {
var me = this, colModel = me.colModel, colNum = me.getColNum(false), cellWidth = 100 / colNum,
colTpl = '<div class="x-grid-head">';
colTpl += '<thead><tr class="x-grid-header">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + (col.width - 4) + "%") : '';
colTpl += '<th class="x-grid-cell" ' + width + ' style="' + col.style + '" >' + col.header + '</th>';
}
colTpl += '</tr></thead>';
colTpl += '<tbody ><tpl for="."><tr class="x-grid-row">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + col.width + "%") : '';
colTpl += '<td class="x-grid-cell" style="' + col.style + '" >{' + col.mapping + '}</td>';
}
colTpl += '</tr></tpl></tbody>';
colTpl += '</table></div>'
return new Ext.DataView({
store: me.store,
itemSelector: "tr.x-grid-row",
simpleSelect: me.multiSelect,
scroll: me.scroll,
tpl: new Ext.XTemplate(colTpl,
{
isRowDirty: function (dirty, data) {
return dirty ? "x-grid-row-dirty" : "";
}
}
),
prepareData: function (data, index, record) {
var column,
i = 0,
ln = colModel.length;
var prepare_data = {};
prepare_data.dirtyFields = {};
for (; i < ln; i++) {
column = colModel[i];
if (typeof column.renderer === "function") {
prepare_data[column.mapping] = column.renderer.apply(me, [data[column.mapping], column, record, index]);
} else {
prepare_data[column.mapping] = data[column.mapping];
}
}
prepare_data.isDirty = record.dirty;
prepare_data.rowIndex = index;
return prepare_data;
},
bubbleEvents: [
"beforeselect",
"containertap",
"itemdoubletap",
"itemswipe",
"itemtap",
"selectionchange",
"scroll"
]
});
},
// #private
onScrollStart: function () {
console.log("Are you coming here");
var offset = this.scroller.getOffset();
this.closest = this.getClosestGroups(offset);
this.setActiveGroup(this.closest.current);
},
// #private
onScroll: function (scroller, pos, options) {
}
});
Ext.reg("touchgridpanel", Ext.ux.TouchGridPanel);
We can directly access dataview scroller and check event of the same.
For eg.
newGrid = new Ext.ux.TouchGridPanel({....
after creation of the Panel just access its dataview scroller
newGrid.dataview.scroller.on('scroll', scrollGrid1);
var scrollGrid1 = function(scroller, offsets){
console.log(' Grid scrolling with offset ' + offsets.x + ' & ' + offsets.y);
}

Twitter and jQuery , render tweeted links

I am using jquery ajax to pull from the twitter api, i'm sure there's a easy way, but I can't find it on how to get the "tweet" to render any links that were tweeted to appear as a link. Right now it's only text.
$.ajax({
type : 'GET',
dataType : 'jsonp',
url : 'http://search.twitter.com/search.json?q=nettuts&rpp=2',
success : function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});
UPDATE:
The following function (plugin) works perfectly.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 100,
fadeSpeed : 500,
tweetName: 'jquery'
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q="+settings.tweetName+"&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
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);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
Within my Ready Statement :
$.socialFader({ tweetHolder:"#twitter", tweetName:"nettuts", tweetCount:2 });
Here is a plugin I wrote which really simplifies the tweet/json aggregation then parsing. It fades the tweets in and out. Just grab the needed code. Enjoy.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=jquery&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
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);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
You need to parse the tweet content, find the urls and then put them in between yourself.
Unfortunately, at the moment, the search API doesn't have the facility to break out tweet entities (i.e., links, mentions, hashtags) like some of the REST API methods. So, you could either parse out the entities yourself (I use regular expressions) or call back into the rest API to get the entities.
If you decide to call back into the REST API, and once you have extracted the status ID from the search API results, you would make a call to statuses/show like the following:
http://api.twitter.com/1/statuses/show/60183527282577408.json?include_entities=true
In the resultant JSON, notice the entities object.
"entities":{"urls":[{"expanded_url":null,"indices":[68,88],"url":"http:\/\/bit.ly\/gWZmaJ"}],"user_mentions":[],"hashtags":[{"text":"wordpress","indices":[89,99]}]}
You can use the above to locate the specific entities in the tweet (which occur between the string positions denoted by the indices property) and transform them appropriately.
If you prefer to parse the entities yourself, here are the (.NET Framework) regular expressions I use:
Link Match Pattern
(?:<\w+.*?>|[^=!:'"/]|^)((?:https?://|www\.)[-\w]+(?:\.[-\w]+)*(?::\d+)?(?:/(?:(?:[~\w\+%-]|(?:[,.;#:][^\s$]))+)?)*(?:\?[\w\+%&=.;:-]+)?(?:\#[\w\-\.]*)?)(?:\p{P}|\s|<|$)
Mention Match Pattern
\B#([\w\d_]+)
Hashtag Match Pattern
(?:(?:^#|[\s\(\[]#(?!\d\s))(\w+(?:[_\-\.\+\/]\w+)*)+)
Twitter also provides an open source library that helps capture Twitter-specific entities like links, mentions and hashtags. This java file contains the code defining the regular expressions that Twitter uses, and this yml file contains test strings and expected outcomes of many unit tests that exercise the regular expressions in the Twitter library.
How you process the tweet is up to you, however I process a copy of the original tweet, and pull all the links first, replacing them in the copy with spaces (so as not to modify the string length.) I capture the start and end locations of the match in the string, along with the matched content. I then pull mentions, then hashtags -- again replacing them in the tweet copy with spaces.
This approach ensures that I don't find false positives for mentions and hashtags in any links in the tweet.
I slightly modified previous one. Nothing lefts after all tweets disappears one by one.
Now it checks if there is any visible tweets and then refreshes tweets.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=istanbul&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
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);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$(settings.tweetHolder).find('li.cycles').remove();
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
if (jQuery('#twitter ul li.cycles:visible').length==1) {
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
}
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
jQuery(document).ready(function(){
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
});

Resources