Running Two onLoad From an External JavaScript? - javascript

I currently have two external scripts for my site that both require the use of onLoad. They are:
One that automatically generates a table of contents:
window.onload = function () {
var toc = "";
var level = 1;
document.getElementById("contents").innerHTML =
document.getElementById("contents").innerHTML.replace(
/<h([\d])>([^<]+)<\/h([\d])>/gi,
function (str, openLevel, titleText, closeLevel) {
if (openLevel != closeLevel) {
return str;
}
if (openLevel > level) {
toc += (new Array(openLevel - level + 1)).join("<ol>");
} else if (openLevel < level) {
toc += (new Array(level - openLevel + 1)).join("</ol>");
}
level = parseInt(openLevel);
var anchor = titleText.replace(/ /g, "_");
toc += "<li><a href=\"#" + anchor + "\">" + titleText
+ "</a></li>";
return "<h" + openLevel + "><a name=\"" + anchor + "\">"
+ titleText + "</a></h" + closeLevel + ">";
}
);
if (level) {
toc += (new Array(level + 1)).join("</ol>");
}
document.getElementById("toc").innerHTML += toc;
};
And another that is used to find certain words in a paragraph and replace them with given JavaScript.
var doc, bod, E, makeLink;
var pre = onload;
onload = function(){
if(pre)pre();
doc = document; bod = doc.body;
E = function(id) {
return doc.getElementById(id);
}
T = function(tag) {
return doc.getElementsByTagName(tag);
}
makeLink = function(node, word, href) {
if(node.innerHTML) {
node.innerHTML = node.innerHTML.replace(word, "<a href='"+href+"'>"+word+'</a>');
}
return false;
}
makeLink(E('testId'), 'Within', 'within.html');
makeLink(E('testId'), 'assuming', 'assuming.html');
}
However, as they're both using onLoad, they don't work together. Is there a way to get them both to function on the same page?

functionA() {
var toc = "";
var level = 1;
document.getElementById("contents").innerHTML =
document.getElementById("contents").innerHTML.replace(
/<h([\d])>([^<]+)<\/h([\d])>/gi,
function (str, openLevel, titleText, closeLevel) {
if (openLevel != closeLevel) {
return str;
}
if (openLevel > level) {
toc += (new Array(openLevel - level + 1)).join("<ol>");
} else if (openLevel < level) {
toc += (new Array(level - openLevel + 1)).join("</ol>");
}
level = parseInt(openLevel);
var anchor = titleText.replace(/ /g, "_");
toc += "<li><a href=\"#" + anchor + "\">" + titleText
+ "</a></li>";
return "<h" + openLevel + "><a name=\"" + anchor + "\">"
+ titleText + "</a></h" + closeLevel + ">";
}
);
if (level) {
toc += (new Array(level + 1)).join("</ol>");
}
document.getElementById("toc").innerHTML += toc;
}
functionB() {
var doc, bod;
//var pre = onload;
//onload = function(){
//if(pre)pre();
doc = document; bod = doc.body;
makeLink(E('testId'), 'Within', 'within.html');
makeLink(E('testId'), 'assuming', 'assuming.html');
}
}
window.E = function(id) {
return doc.getElementById(id);
}
window.T = function(tag) {
return doc.getElementsByTagName(tag);
}
window.makeLink = function(node, word, href) {
if(node.innerHTML) {
node.innerHTML = node.innerHTML.replace(word, "<a href='"+href+"'>"+word+'</a>');
}
return false;
}
Then you call onload from body tag(If you want one to execute before the other, change the order):
<body onload="functionA(); functionB();">

Use addEventListener instead of setting the property of the window object. Here's a MDN page.
You can do something like that:
window.addEventListener('load', function() {
console.log('Loaded 1');
});
window.addEventListener('load', function() {
console.log('Loaded 2');
});
Both of them should fire off.

Related

Facebook Graph API get original picture size not working

Need some help to get a normal or larger image from posts using the Facebook Graph API, at the moment it only gives a 130 x 130 px image in the object.
function fbFetch() {
var access_token = "";
var url = "https://graph.facebook.com/?ids=intel&fields=posts.limit(5){message,created_time,picture.type(normal)}&access_token=' + access_token;
$.getJSON(url, function(response) {
var messages = [];
Object.getOwnPropertyNames(response).forEach(function(page, idx, array) {
response[page].posts.data.forEach(function(post, idx, array) {
messages.push(post);
});
});
function compare(a, b) {
if (a.created_time < b.created_time)
return -1;
if (a.created_time > b.created_time)
return 1;
return 0;
}
var html = "<ul>";
$.each(messages.sort(compare), function(i, fb) {
if (typeof fb.picture != "undefined") {
html += "<li>" + fb.message + "</br>" + '<img SRC="' + fb.picture + '">' + "</br>" + fb.created_time + "</li></br>";
} else {
html += "<li>" + fb.message + "</br>" + fb.created_time + "</li></br>";
}
});
html += "</ul>";
$('.facebookfeed').html(html);
});
}
fbFetch();
<div class="facebookfeed"></div>
Fiddle here: http://jsfiddle.net/6fhq3dat/17/
use full_picture instead of picture
var url = "https://graph.facebook.com/?ids=intel&fields=posts.limit(3){message,created_time,full_picture}&access_token=" + access_token;
demo

Can I save multiple JavaScript Object methods as a variable?

I am writing an extension for a text-editor (Brackets) that can generate HTML and append libraries automatically in the HTML.
I have an Object called 'choice'.
This modal requests the users input:
choice grabs the user's input by defining methods on choice
partial JS here:
var choice = new Object();
choice.language = function () {
//Buid HTML top 'head'
var htmlTop = "<!DOCTYPE html>" + "<html>" + "<head lang='";
//Grab Selected Language Type
var languageChoice = document.getElementById("languages").value;
//Determine what Selected Language type is and complete HTML 'head'
if (languageChoice === "english") {
languageChoice = "en";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "german") {
languageChoice = "de";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "spanish") {
languageChoice = "es";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "french") {
languageChoice = "fr";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "italian") {
languageChoice = "it";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "chinese") {
languageChoice = "zh-cn";
return htmlTop + languageChoice + "'>";
}
}; //end choice.language
choice.charset = function () {
//Build meta and the rest of the 'head tag'
var htmlCharset_Beginning = "<meta charset='";
var htmlCharset_End = "'>" + "<title> -Insert Title- </title>" + "<!-- Insert CSS links below -->" + "</head>" + "<body>";
var charsetChoice = document.getElementById("charset").value;
if (charsetChoice === "utf8") {
charsetChoice = "UTF-8";
return htmlCharset_Beginning + charsetChoice + htmlCharset_End;
} else {
charsetChoice = "UTF-16";
return htmlCharset_Beginning + charsetChoice + htmlCharset_End;
}
}; // end choice.charset
choice.doctype = function () {
var doctypeChoice = document.getElementById("doctype").value;
return doctypeChoice;
}; // end doctype
choice.libraries = function () {
var checkedBoxes = getCheckedBoxes("lib_checkboxes");
checkedBoxes.forEach(function(item){
var scripts =+ $(item).data('script');
});//End forEach
var bottomHTML = scripts + "</body>" + "</html>";
return bottomHTML;
}; //End choice.libraries
var chosenTemplate = function(){
var template = choice.language() + choice.charset() + choice.libraries();
// insert html into file, this will overwrite whatever content happens to be there already
EditorManager.getCurrentFullEditor()._codeMirror.setValue(template);
// automatically close the modal window
$('#templates_modalBtn').click();
};
//Get checkedBoxes function
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i = 0; i < checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
} // End action();
//JEFF STOP CODING HERE
// Register the commands and insert in the File menu
CommandManager.register(Strings.MENU_COMMAND, 'templates', action);
var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
menu.addMenuDivider();
menu.addMenuItem('templates');
}); //end define;
QUESTION:
Can I save multiple methods (each method returns a string) as a variable?
Example here:
var chosenTemplate = function(){
var template = choice.language() + choice.charset() + choice.libraries();
// insert html into file, this will overwrite whatever content happens to be there already
EditorManager.getCurrentFullEditor()._codeMirror.setValue(template);
// automatically close the modal window
$('#templates_modalBtn').click();
};
My code is loading with no errors, but its not executing at all so I am trying to debug and figure out what is going wrong...
Before you realize the function 'chosenTemplate', you should check whether the document stream of the page has already downloaded. If it not, you may not be able to get the value of the widget (empty).

Javascript Maintain Scroll Position

I'm trying to make my webpage refresh and maintain it's scroll position with this code:
function refreshPage() {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
window.onload = function() {
setTimeout(refreshPage, 35000);
if ( window.location.href.indexOf('page_y') != -1 ) {
var match = window.location.href.split('?')[1].split("&")[0].split("=");
document.getElementsByTagName("body")[0].scrollTop = match[1];
}
}
While this successfully adds the ?page_y=scrollposition and the scroll position is accurate, and I can print match and match[1] to the console successfully, the only problem is it does not scroll the page.
EDIT:
Apparently, the script is loading before my script to generate the content of the web page and I'm not quite sure why. Posting entire code below:
<script>
$(window).load(function(){
$.getJSON("sun.json", function(json1) {
$.each(json1, function(key, data) {
document.body.innerHTML +=
"<div id='" + data.video + "' class='caption' data-source='" + data.video + "' data-title='" + data.title + "' data-desc='" + data.description + "' onclick='parent.changeVideo(dataset.source, dataset.title, dataset.desc); reloadImg()'>" +
"<img class='thumbnail' src='" + data.thumb + "' alt='" + data.title + "'>" +
"<div class='caption-text'>" +
"<b class='caption-title'>" + data.title + "</b>" +
data.description +
"</div>" +
"</div>" +
"<hr>"
console.log("This should be first");
$(".caption").hover(function(){
$(this).find(".caption-text").fadeIn(400);
},
function(){
$(this).find(".caption-text").fadeOut(400);
});
});
});
});
var scroll = $(window).scrollTop();
// yada
$("html").scrollTop(scroll);
function changeVid() {
document.querySelector("#current-video_html5_api").src = data.video
console.log(data.video);
}
</script>
<script>
function refreshPage() {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
var match = window.location.href.split('?')[1].split("&")[0].split("=");
window.onload = function() {
setTimeout(refreshPage, 35000);
if ( window.location.href.indexOf('page_y') != -1 ) {
//document.getElementsByTagName("body")[0].scrollTop = match[1];
window.scrollTo(0, match[1]);
console.log(match[1]);
console.log("This should come second");
}
}
</script>
You can use window.scrollTo:
function refreshPage() {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
window.onload = function() {
setTimeout(refreshPage, 35000);
if ( window.location.href.indexOf('page_y') != -1 ) {
var match = window.location.href.split('?')[1].split("&")[0].split("=");
window.scrollTo(0, match[1]);
}
}
You need to use scrollTo as a function - not as a property. I believe scrollTop (as a function) is only available in libraries (like jquery). Here's some documentation on how to use window.scrollto()...
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo

AngularJS: Factory and filters - factory is not working

I have this code, and it works:
var app = angular.module('twitterApp', ['twitterApp.services', 'ngSanitize']);
app.filter('clearImage', function () {
return function (text) {
var str = text.replace(/_normal./g, '.');
return str;
};
});
app.filter('links', function () {
return function (text) {
var str = text.replace(/#([^ ']+)/g, function(u, screen_name) {
var link = '<a target=blank href="http://twitter.com/intent/user?screen_name=' + screen_name + '">' + u + '</a>';
return link;
});
str = str.replace(/#([^ ']+)/g, function (t, hash) {
var link = '<a target=blank href="https://twitter.com/hashtag/' + hash + '?src=hash">' + t + '</a> ';
return link;
});
return str;
};
});
I am trying to be more object oriented and modular, so I have made the following code, but it is not working:
var app = angular.module('twitterApp', ['twitterApp.services', 'ngSanitize']);
app.factory('StratoFactory', function() {
var factory = {};
return {
removeNormalStringFromImage : function(text) {
var str = text.replace(/_normal./g, '.');
return str;
},
userName2Link : function(text) {
var str = text.replace(/#([^ ']+)/g, function(u, screen_name) {
var link = '<a target=blank href="http://twitter.com/intent/user?screen_name=' + screen_name + '">' + u + '</a>';
return link;
});
str = str.replace(/#([^ ']+)/g, function (t, hash) {
var link = '<a target=blank href="https://twitter.com/hashtag/' + hash + '?src=hash">' + t + '</a> ';
return link;
});
return str;
}
};
return factory;
});
app.filter('clearImage', function(StratoFactory) {
return function(text) {
StratoFactory.removeNormalStringFromImage(text);
};
});
app.filter('links', function(StratoFactory) {
return function(text) {
StratoFactory.userName2Link(text);
};
});
Can someone explain me the reason what is wrong with the second version of the code? Thanks!
You have two return statements in your factory.
you need to create an object, assign method to it, then return it.
try this:
app.factory('StratoFactory', function() {
var factory = {};
factory.removeNormalStringFromImage = function(text) {
var str = text.replace(/_normal./g, '.');
return str;
}
factory.userName2Link = function(text) {
var str = text.replace(/#([^ ']+)/g, function(u, screen_name) {
var link = '<a target=blank href="http://twitter.com/intent/user?screen_name=' + screen_name + '">' + u + '</a>';
return link;
});
str = str.replace(/#([^ ']+)/g, function (t, hash) {
var link = '<a target=blank href="https://twitter.com/hashtag/' + hash + '?src=hash">' + t + '</a> ';
return link;
});
return str;
}
return factory;
});
I have finally found the solution! There wasn't any error in the console, because everything was structured ok. But the problem was that my filters weren't returning anything. So I have simply added a return, and now everything is ok. Really a banal mistake. Here is the code:
var app = angular.module('twitterApp', ['twitterApp.services', 'ngSanitize']);
app.factory('StratoFactory', function() {
var factory = {};
factory.removeNormalStringFromImage = function(text) {
var str = text.replace(/_normal./g, '.');
return str;
},
factory.userName2Link = function(text) {
var str = text.replace(/#([^ ']+)/g, function(u, screen_name) {
var link = '<a target=blank href="http://twitter.com/intent/user?screen_name=' + screen_name + '">' + u + '</a>';
return link;
});
str = str.replace(/#([^ ']+)/g, function (t, hash) {
var link = '<a target=blank href="https://twitter.com/hashtag/' + hash + '?src=hash">' + t + '</a> ';
return link;
});
return str;
};
return factory;
});
app.filter('clearImage', function(StratoFactory) {
return function(text) {
**return** StratoFactory.removeNormalStringFromImage(text);
};
});
app.filter('links', function(StratoFactory) {
return function(text) {
**return** StratoFactory.userName2Link(text);
};
});

How to call own function from click method

I know it sounds stupid, but i have no idea how to call my function from "onclick" function?
I made own class and what i wanna do is to call my function inside a class.
I have tried various stuff inside that onclick function:
function(){this.getWidth()}
this.getWidth()
Test.getWidth()
function Datagrid(_parent, _data)
{
this.table = [];
this.parent = $("#"+_parent)[0] ? $("#"+_parent) : ($("."+_parent)[0] ? $("."+_parent) : ($(+_parent)[0] ? $(_parent) : null));
this.data = _data;
this.Datagrid = function(parent,data)
{
this.setParent(parent);
if(data != null)
this.setData(data);
return this;
}
this.setParent = function(parent)
{
return this.parent = $("#"+parent)[0] ? $("#"+parent) : ($("."+parent)[0] ? $("."+parent) : ($(+parent)[0] ? $(parent) : null));
}
this.getParent = function()
{return this.parent;}
this.setData = function(data)
{this.data = data;}
this.buildTable = function()
{
var dtTbl = [];
dtTbl.push('<table class="TimeSheetmainTable" cellpadding="10" cellspacing="0" border="0">');
var style;
//Header//////////////////////
dtTbl.push('<tr class="header">');
for (var cell in this.data.row[0].cell) {
dtTbl.push('<td>' + this.data.row[0].cell[cell].id + '</td>');
}
dtTbl.push('</tr>');
//Content//////////////////////
for(var r in this.data.row)
{
if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r1\'"'; }
else { style = 'class="r2" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r2\'"'; }
dtTbl.push('<tr ' + style + ' >');
for(var c in this.data.row[r].cell)
{
dtTbl.push('<td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value + '</td>');
}
dtTbl.push('</tr>');
}
//Footer//////////////////////
dtTbl.push('<tr class="footer">');
for (var cell in this.data.row[0].cell) {
dtTbl.push('<td> </td>');
}
dtTbl.push('</tr></table>');
this.parent.html(dtTbl.join(''));
}
this.buildTableDiv = function()
{
var tableString = [];
//Header//////////////////////
tableString.push('<div class="container"><div class="header"><table><tr id="header">');
for (var cell in this.data.row[0].cell) {
tableString.push('<td>' + this.data.row[0].cell[cell].id + '</td>');
}
tableString.push('</tr></table></div>');
//Content//////////////////////
tableString.push('<div class="content"><table>');
var TD1 = new Object();
var TD2 = new Object();
for(var r in this.data.row)
{
if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r1\'"'; }
else { style = 'class="r2" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r2\'"'; }
for(var c in this.data.row[r].cell)
{
if(c == 0)
{ if(TD1.value != this.data.row[r].cell[c].value){
TD1.value = this.data.row[r].cell[c].value;
TD1.show = true;
}
else
TD1.show = false;
}
if(c == 1)
{ if(TD2.value != this.data.row[r].cell[c].value){
TD2.value = this.data.row[r].cell[c].value;
TD2.show = true;
}
else
TD2.show = false;
}
if(TD1.show && c == 0){//First line
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td alt="' + this.data.row[r].cell[c].id + '"><input type="button" class="arrow_down" /> ' + this.data.row[r].cell[c].value + '</td>');
for(var c = 0; c < this.data.row[r].cell.length - 1; c++)
{
tableString.push('<td>&nbsp</td>');
}
tableString.push('</tr>');
}
else if(TD2.show && c == 1)//Second line
{
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td> </td><td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value + '</td>');
for(var c = 0; c < this.data.row[r].cell.length - 2; c++)
{
tableString.push('<td>&nbsp</td>');
}
tableString.push('</tr><tr id="content" ' + style + ' ><td> </td><td> </td>');
}
else if(!TD2.show && c == 1)//third line (distincts second cells name)
{
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td> </td><td alt="' + this.data.row[r].cell[c].id + '"> </td>');
}
else if(c > 1)//Rest filling (not ordered stuff)
{
tableString.push('<td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value.replace(""," ") + '</td>');
}
}
tableString.push('</tr>');
// $(".arrow_down").children(":nth-child(1)").click(function(){alert("test");});
}
tableString.push('</table></div>');
//Footer//////////////////////
tableString.push('<div class="footer"><table><tr id="footer">');
for (var cell in this.data.row[0].cell) {
tableString.push('<td> </td>');
}
tableString.push('</tr></table></div></div>');
this.parent.html(tableString.join(''));
// Setting width to all cells
for (var i in this.data.row[0].cell)
{
cell = parseInt(i)+1;
var h = this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var c = this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var f = this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var width = h > c ? h : (c > f ? c : f);
this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
}
// this.activateScroller(0);
}
this.getScrollerWidth = function()
{
var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
// Append our div, do our calculation and then remove it
$('body').append(div);
var w1 = $('div', div).innerWidth();
div.css('overflow-y', 'scroll');
var w2 = $('div', div).innerWidth();
$(div).remove();
return (w1 - w2);
}
this.activateScroller = function(value)
{
var d = [];
d.push('<div style="height: ' + this.parent.children(":first").children(".content").height() + '; width:20px; background:#FFF"><div style="background:#333; height:200"> </div></div>');
this.parent.children(":first").children(".content").scrollTop(value);
}
expandParent = function()
{
alert(this.parent);
}
};
i am kinda makig datagrid based on javascript. i am not allowed to use jQuery UI.
My datagrid is made from tables. now i try to add a button inside a td element like User Name
The problem is that i cant access my function inside my class without making instance. is it even possible to do that without making an instance?
Once your html is generated using your generateHTML function, the handler for onclick on div looses context of what "this" is. To be more specific, this in onclick handler for div refers to that div node in DOM.
To access getWidth method you have to make it available to global context or (better solution) do something like this:
// new version of your generateHTML function
this.generateHTML() {
var str = [];
str.push('<div><input type="button" value="button"/></div>');
var that = this;
$("#testDiv").append(str.join('')).find('button:first').click(function() {that.getWidth()});
}
EDIT:
To further explain how code above works, here's simplified example with comments.
​​Test = function() {
this.generate = function() {
var newnode = $('<button>click me</button>');
$("body").append(newnode);
// "cache" this in a variable - that variable will be usable in event handler
var that = this;
// write event handler function here - it will have access to your methods by using "that" variable
newnode.click(function(e) {
// here this refers to button not Test class
// so we have to "reach" to outer context to gain access to all methods from Test
that.doSomething('learn');
})
}
this.doSomething = function(x) {
alert('do it: '+x);
}
}
// initialize part
// make instance of Test "class"
t = new Test();
// generate the button (clicking on a button will essentialy fire Test.doSomething function in a context of "t"
t.generate();

Categories