I am running a DOM script and it is working PERFECTLY in Chrome and Firefox, but not IE8 or 9. The error messages in IE that I get are
document.getElementByld(..) is null or not an object
Object doesn't support this property or method
Unable to set value of the property 'innerHTML': object is null or undefined (URL: http://twitter.com/javascripts/blogger.js)
Code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
// DOM Ready
$(function() {
$.getJSON('http://twitter.com/status/user_timeline/LaunchSeven.json?count=2&callback=?', function(data){
$.each(data, function(index, item){
$('#twitter').append('<div class="tweet"><p>' + item.text.linkify() + '</p><p><strong>' + relative_time(item.created_at) + '</strong></p></div>');
});
});
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.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
});
</script>
Thank you in Advance,
Adam
Your page needs to have an element with the ID twitter_update_list...
document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
Can't say why it isn't available in IE without seeing more code.
Second argument. That's a function definition and not a function being fired. but if m.link(m) didn't work by itself, executing the function properly wouldn't work either.
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
So just make the second arg m.link(m) (no semi)
I'm not sure this explains your document.getElementById issue though. But it might be causing a bug cascade somewhere.
Also, you should really define that string prototype before everything else. I believe only named functions hoist e.g. function someName(){.. vs. var someName = function(){...
Related
How can I auto-complete an input date using JavaScript?
Like for example I input 5/2 it'll automatically be 20190502
function dateManagement(dateValue) {
var inputs = dateValue.split('/');
var month = (inputs[0].length == 1) ? '0' + inputs[0] : inputs[0];
var date = (inputs[1].length == 1) ? '0' + inputs[1] : inputs[1];
return new Date().getFullYear() + '' + month + '' + date;
}
function setupLevel1ItemDateManagementEditFunction(dateValue){
addLoadEvent(initLevel1ItemDateManagementEditFunction(dateValue));
}
function initLevel1ItemDateManagementEditFunction(dateValue){
return function(){
var dateVal = disp.getElement(dateValue);
addEventHandler(dateVal ,"onkeydown", function(e){
if(e.keyCode == KEY_ENTER){
var input = disp.get(dateValue);
var edited = "";
try{
edited = dateManagement(dateValue);
} catch(e){
console.log(e);
}
if(edited != "" && edited !=null){
disp.set(dateValue, edited);
}
}
return true;
});
return true;
};
}
i have tried reading a lot of threads and forums and i still dont get it.
i am completely new to coding so pls bear with me.
This is a very bad approach to set a date. But if you really needs to do this, you can use following function.
function getFullDate(yourInputText) {
var inputs = yourInputText.split('/');
var month = (inputs[0].length == 1) ? '0' + inputs[0] : inputs[0];
var date = (inputs[1].length == 1) ? '0' + inputs[1] : inputs[1];
return new Date().getFullYear() + '/' + month + '/' + date;
}
console.log(getFullDate('5/2')); //output: '2019/05/02'
Note:
new Date().getFullYear() will give you the current year.
The code below works. The code calls an API to get historical trades (100 trades each time pér pull). Because there is an limit - how many and how often im allowed to call the API - the structure is like recursive.
The flow is like this:
Get the current MAX tradeId - which is stored in the DB.
Now make a new PULL with startIndex = MaxId and a length of 100 (to pull 100 new trades).
FIRST when the callback function is called the main code continues and 100 new trades are pulled... ect. ect.
So...
The code SHOULD behave like - Psydo-code
var maxId = GetMaxIdFromDB();
Pull(maxId, 100, callback);
function callback(){
... do different stuff..
maxId += 100;
Pull(maxId, 100, callback);
}
The strange thing and my question is: How can the API function "getProductTrades " be called more than one time - where my cursor variable contains the SAME value - when it is incremented with 100 (or the number of valid data elements each time).
I'm talking/ref. especially to the following lines:
wl.debug("getProductTrades - cursor: " + cursor + " Limit: " + limit);
publicClient.getProductTrades({'after': cursor, 'limit': limit}, callback);
The insertQuery.InsertMatchMsgArrayToDB(allData); method calls another DB method which returns a promise.
You can see a screenshot of the issue here:
http://screencast.com/t/DH8rz3UxnyZ
The real code is here:
pullTradesBetween: function (minTradeId, maxTradeId) {
var wl = new WinLog();
var tradeCounter = 0;
try {
var WebSocketEmit = new WSemitter();
var startTime = new Date().toLocaleString();
var executeTradePullAgain = null;
wl.debug("REST API START: " + startTime);
var cursor;
var incrementedCursorWith = 0;
if ((maxTradeId - minTradeId) < 100) {
cursor = maxTradeId + 1;
}
else
cursor = minTradeId + 100;
var callback = function (err, response, data) {
if (executeTradePullAgain !== null)
clearTimeout(executeTradePullAgain);
if (err)
wl.info("Err: " + err);
var validData = [];
incrementedCursorWith = 0;
if (response == null)
wl.info("RESPONSE ER NULL");
if (data !== null) {
for (var i = data.length - 1; i >= 0; i--) {
var obj = data[i];
var tradeId = parseInt(obj.trade_id);
if (obj !== null && (minTradeId <= tradeId && tradeId <= maxTradeId)) {
validData.push(data[i]);
}
}
if (validData.length == 0) {
wl.debug("Contains 0 elements!");
}
else {
cursor = cursor + validData.length;
incrementedCursorWith = validData.length;
insertDataToDB(validData);
}
}
else
wl.debug("DATA IS NULL!");
wl.debug("cursor: " + cursor + " maxTradeId: " + maxTradeId);
var diffToMax = maxTradeId - (cursor - incrementedCursorWith);
if (diffToMax >= 100)
pullTrades(cursor, 100); // 100 is default
else if (diffToMax >= 0)
pullTrades(maxTradeId + 1, diffToMax + 1); // X = Only the last trades in the given series of trades
else {
wl.info("REST API START: " + startTime + " REST API DONE: " + new Date().toLocaleString());
WebSocketEmit.syncHistoricalDataDone();
}
};
function pullTrades(cursor, limit) {
tradeCounter += limit;
if(tradeCounter % 10000 == 0){
wl.info('Downloaded: ' + tradeCounter + ' trades via REST API (Total: ' + cursor + ')');
}
pullTradesAgainIfServerDoesNotRespond(cursor, limit);
wl.debug("getProductTrades - cursor: " + cursor + " Limit: " + limit);
publicClient.getProductTrades({'after': cursor, 'limit': limit}, callback);
}
function pullTradesAgainIfServerDoesNotRespond(cursor, limit) {
executeTradePullAgain = setTimeout(function () {
wl.debug('pullTradesAgainIfServerDoesNotRespond called!');
pullTrades(cursor, limit);
}, 30000);
}
// SAVE DATA IN DB!
function insertDataToDB(allData) {
insertQuery.InsertMatchMsgArrayToDB(allData);
}
wl.debug("pull trades: " + cursor);
pullTrades(cursor, 100);
}
catch(err){
wl.info('pullTradesBetween: ' + err);
} }};
It happens when you get no data out of getProductionTrades.
If the data returned is null, you will never reach the lines
cursor = cursor + validData.length;
incrementedCursorWith = validData.length;
but you still call
pullTrades(cursor, 100);
at the end. I don't know if it's intended or an actual error so i leave the solution (should be trivial now) up to you.
I try to simplify your code
pullTradesBetween: function (minTradeId, maxTradeId) {
var WebSocketEmit = new WSemitter(); // try-catch ?
var curr = (maxTradeId - minTradeId < 100) ? maxTradeId + 1 : minTradeId + 100;
// function always return data or infinite error-loop
function getProductTrades (after, limit, callback) {
// try-catch ?
publicClient.getProductTrades ({after, limit}, function(err, data) {
if (err) {
console.log(err);
return getTrades(after, limit, callback);
}
callback(null, data);
});
}
function onDataReady (err, data) {
if (err)
throw new Error('Impossible!');
if (!data || !(data instanceof Array))
return ... smth on empty data ...
var validData = data.filter(function(obj) {
return obj &&
minTradeId <= parseInt(obj.trade_id) &&
parseInt(obj.trade_id) <= maxTradeId;
}).reverse();
if (validData.length == 0)
return ... smth on empty data ...
insertDataToDB(validData);
curr += validData.length; // maybe +-1
var remaining = maxTradeId - curr;
if (remainig == 0) {
console.log('Done');
// try-catch ?
WebSocketEmit.syncHistoricalDataDone();
}
return (remaining >= 100) ?
getProductTrades(curr, 100, onDataReady) :
getProductTrades(maxTradeId + 1, remaining + 1, onDataReady); // ??
}
getProductTrades(curr, 100, onDataReady);
}
Need help, because I have an error in my code and I can't see it.
I'm trying to do a newton raphson method.
The user enters a polinomy and the function calculates the derivate, then applys the Newton's raphson formula and shows the final result in a table.
My problem is that I can't make it work, because I can't show the final table with the results.
See an example here: http://codepen.io/anon/pen/Qyddoy?editors=101
Thats my JS code.
function funcion(func, x) {
var nuevaFuncion= func.replace(/x/g, x);
return eval(nuevaFuncion);
}
function derivada(x) {
var func = document.getElementsByName("func")[0].value.trim();
var derivative = nerdamer('diff(' + func + ')').evaluate();
}
function procesar(formulario) {
var i = 0;
var func = document.getElementsByName("func")[0].value;
var err, x_1, x = parseFloat(formulario.x.value);
var resultado = '<table border="3"><tr><td align="center">i</td><td align="center">x<sub></sub></td><td align="center">error</td></tr>';
do {
x_1 = x;
x = x - funcion(func, x) / derivada(x);
err = Math.abs((x - x_1) / x);
resultado += '<tr><td>x<sub>' + i + '</sub></td><td>' + x_1 + '</td><td>' + err + '</td></tr>';
i++;
} while (x != x_1 && i < 100);
document.getElementById('resultado').innerHTML = resultado + '</tbody> </table><br>' + (i == 100 ? 'La solucion no es convergente. ' : 'La solucion es ' + x);
return false;
}
There are a few things that I would do differently. The first is that I would avoid replacing and using eval and let nerdamer do the work. For example sin(x) would give an error since there isn't a native JS function called sin but rather Math.sin. I'm guessing your i < 100 is a safety. I prefer using a break statement since this is a lot easier to read and debug in my opinion. Also if you already know the variable name you can avoid calling buildFunction and use evaluate instead for example if the variable is x
nerdamer(func).evaluate({x:x});
And lastly, Newton's method requires some stop condition up to some accuracy. Your stop condition of x != x_1 is risky at best.
Here are my edits
http://codepen.io/anon/pen/gPgXbK?editors=101
function funcion(func, x) {
return nerdamer(func).buildFunction().call(undefined, x);
}
function derivada(x){
var func = document.getElementsByName("func")[0].value.trim();
return nerdamer('diff(' + func + ')').buildFunction().call(undefined, x);
}
function procesar(formulario) {
var i = 0;
var func = document.getElementsByName("func")[0].value;
var err, x_1, x = parseFloat(formulario.x.value);
var resultado = '<table border="3"><tr><td align="center">i</td><td align="center">x<sub></sub></td><td align="center">error</td></tr>';
do {
var x_1 = x - funcion(func, x) / derivada(x);
//get the error
var e = Math.abs(x-x_1);
x = x_1
err = Math.abs((x - x_1) / x);
resultado += '<tr><td>x<sub>' + i + '</sub></td><td>' + x_1 + '</td><td>' + err + '</td></tr>';
i++;
//I imagine that this is your safety so I would implement it like this
if(i > 100) break;
} while (e > 0.01);
document.getElementById('resultado').innerHTML = resultado + '</tbody></table><br>' + (i == 100 ? 'La solucion no es convergente. ' : 'La solucion es ' + x);
return false;
}
The function derivada doesn't return nothing so the division in procesar function fails.
You have to return a value so the calculus can go ahead. And I think you want to return the result of derivating the function, like this:
function derivada(x) {
var func = document.getElementsByName("func")[0].value.trim();
var derivative = nerdamer('diff(' + func + ')').evaluate();
return eval(derivative.text());
}
i already found a good solution to the named problem on this website. But it is not working in my script.
I hope someone could help. (Note: the function hour() day() month() changes with an onclick (that is still working correctly)
<script>
var d = new Date();
function hour(i) {
d.setUTCHours(i);
var h = addZero(d.getUTCHours());
}
function day(i) {
d.setUTCDate(i);
var d = addZero(d.getUTCDate());
}
function month(i) {
d.setUTCMonth(i);
var m = addZero(d.getUTCMonth());
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function img() {
var dateString = d.getUTCFullYear() +""+ m +""+ d + "_" + h ;
document.getElementById("demo").innerHTML = dateString;
}
</script>
Your variables are local to the scope of the function they're defined in. You need to move the var statements outside.
<script>
var d = new Date();
var h, m, day;
function hour(i) {
d.setUTCHours(i);
h = addZero(d.getUTCHours());
}
function day(i) {
d.setUTCDate(i);
day = addZero(d.getUTCDate()); // changed the name here to avoid conflicting
}
function month(i) {
d.setUTCMonth(i);
m = addZero(d.getUTCMonth());
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function img() {
var dateString = d.getUTCFullYear() +""+ m +""+ day + "_" + h ;
document.getElementById("demo").innerHTML = dateString;
}
</script>
function getElsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("div"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
function getSong() {
console.log("getSong ran");
var songN = getElsByClass("info")[0], nmSong = getCookie();
console.log(songN);
songN = songN.getElementsByTagName("a");
songN = songN[0].innerText + " - " + songN[1].innerText;
if (nmSong != songN) {
setCookie(songN);
} else {
setCookie(songN);
}
sendSong(songN);
return songN;
}
setInterval(getSong(), 10000);
I've tried songN = document.getElemenetsByClassName("info"), and every combination I could find, and it will only run for maybe 30 seconds before it closes, I need it to run for hours, unattended...
I can run
var songN = getElsByClass("info")[0];
console.log(songN); //is actually defined when ran in Javascript Console in Chrome..
songN = songN.getElementsByTagName("a");
songN = songN[0].innerText + " - " + songN[1].innerText;
in Javascript console, and it returns exactly, what I'm trying to do, but if it runs as a userscript or after it's been injected into the web page, I get Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined, and I've tried to define it many different ways I found through searching google, and stackoverflow, I've ran the script on window.load, in the <head>, and tried to make it run in <body>.
getElsByClass() is my last attempt at it, it's not actually apart of my script, just a bit I tried from another script, tried shortening the name so it couldn't possibly conflict, but still nothing.
=== Update ===
Here is some more of the code..
function getCookie() {
console.log("getCookie ran");
var sname = "songname=", ca = document.cookie.split(';'), i = 0, c, t;
for (i; i < ca.length; i++) {
c = ca[i].trim();
if (c.indexOf(sname) == 0) {
t = c.substring(sname.length, c.length);
console.log(t);
return t;
}
}
return "";
}
function setCookie(cvalue) {
console.log("setCookie ran");
var d = new Date();
d.setTime(d.getTime() + 210000);//set it to expire in 3 minutes and 30 seconds from current time (this is average song time.)
document.cookie = "songname=" + cvalue + "; expires=" + d.toGMTString();
}