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
Related
I am getting no response from a 2nd ajax request. I am trying to display an google information window on google map that contains only a single tab when a certain criteria is matched otherwise I want to display two tabs. I thought I could easily implement this with another marker function with tailored behaviour, but I receive no response. Any help on this is always appreciated. Thanks in advance.
// click event handler
google.maps.event.addListener(marker, 'click', function () {
var ecoli_array = [];
var marker = this;
var str = "";
var beach_status; // beach_status flag
// load gif before ajax request completes
infoWindow.setContent('<img src="img/loading.gif" alt="loading data"/>');
infoWindow.open(map, marker);
// override beach data when a beach is closed
beach_status = this.getBeachStatus();
beach_status = beach_status.toLowerCase();
if (beach_status === 'closed') {
str = [
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>' + this.status_description + '</p>'
].join('');
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
} else {
// chained ajax invocations
if ( this.displayOnlyAlgaeResults === false ) {
// Standard Use case
$.when(this.getEcoliData(), this.getAlgaeData()).done(function (data1, data2) {
str += marker.getHeader() + marker.afterGetEcoliData(data1[0].rows);
str += marker.afterGetAlgaeData(data2[0].rows);
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
// render tabs UI
$(".tabs").tabs({ selected: 0 });
}); // end when call
}else{
// Algae Only Use Case
var d = this.getOnlyAlgaeData();
console.log(d);
$.when( this.getOnlyAlgaeData() ).done(function ( rsp ) {
//console.log(rsp);
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp[0].rows );
//str += marker.afterGetOnlyAlgaeData(data2[0].rows);
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
// render tabs UI
$(".tabs").tabs({ selected: 0 });
}); // end when call
} // end inner if else
} // end outer if else
}); // End click event handler
getOnlyAlgaeData: function () { // begin getAlgaeData
var obj;
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=xxxxx&callback=?';
var whereClause = " WHERE 'Beach_ID' = " + this.beach_id;
var query = "SELECT * FROM xxxx "
+ whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
// ecoli request
return $.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp'
});
}, // end getAlgaeData method
// added afterGetOnlyAlgaeData
afterGetOnlyAlgaeData: function (data) {
var algae_rows_str = "";
algae_rows = data;
var algae_rows_str = [
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<table id="algae_table " class="data">',
'<tr>',
'<th>Sample Date</th>',
'<th class="centerText">Blue Green Algae Cells <br/>(cells/ mL) </th>',
'<th>Recreational Water Quality Objective <br/>(100,000 cells/mL)</th>',
'<th class="centerText">Algal Toxin Microcystin <br/> (μg/L)</th>',
'<th>Recreational Water Quality Objective <br/> (20 μg/L)</th>', // &mu instead of u
'</tr>'
].join('');
//console.log(algae_rows);
if (typeof algae_rows === 'undefined') {
algae_rows_str = [
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>This season, no algal blooms have been reported at this beach.</p>',
'</div>',
'</div>',
'</div>',
'</div>'
].join('');
} else {
for (var i = 0; i < algae_rows.length; i++) {
//console.log(rows[i]);
//algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td class="centerText">' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + checkAlgaeToxinForAdvisory(algae_rows[i][4]) + '</td><td class="centerText">' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + checkBlueGreenAlgaeCellsForAdvisory(algae_rows[i][6]) + '</td></tr>';
algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td class="centerText">' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + checkBlueGreenAlgaeCellsForAdvisory(algae_rows[i][6]) + '</td><td class="centerText">' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + checkAlgaeToxinForAdvisory(algae_rows[i][4]) + '</td></tr>';
}
algae_rows_str += '</table>'
algae_rows_str += '</div></div></div>';
//return algae_rows_str;
} //end if
return algae_rows_str;
}, // end afterGetOnlyAlgaeData
}); // ====================end marker
I essentially copied two identical functions that work, gave them a slightly different name and customized each function to display 1 tab instead of two, but I get no response.
Thoughts?
thanks for the help, it ended up being something simple.
I was incorrectly referencing the response. Ie. I change the following line:
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp[0].rows );
to
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp.rows );
Geez!
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.
I'm trying to make a website using jquery-1.11.1 where I want a <textarea> to be spawned whenever I click on the link which only shows on mouseenter on a div. But I'm getting an error in my console,
Uncaught ReferenceError: inputdivEditor is not defined (Please ignore JSFiddle errors)
I've absolutely no idea why I'm getting this. Here are my codes,
$(document).ready(function () {
$("[id^=divEditor-]").each(function () {
var content = $(this).html();
var targetID = $(this).attr('id');
var txtID = 'input' + targetID;
$('<textarea id="input' + targetID + '" name="' + txtID + '" >' + content + '</textarea>').insertBefore(this).css('display', 'none');
var button = "<a onclick='activateDivEditor(this, " + txtID + ")' class='custom-edit-button editDiv' id='active" + targetID + "'>Embed Code</a>";
$(this).on('mouseenter', function () {
$(this).prepend($(button));
$(this).css('position', 'relative');
});
$(this).on('mouseleave', function () {
$('.editDiv').remove();
});
});
});
function activateDivEditor(btn, txtId) {
var targetID = $(btn).parent().get(0).id;
var update = "<a onclick='deactivateDivEditor(this, " + txtId + ")' class='custom-edit-button updatediv' id='deactive" + targetID + "'>Update</a>";
var cancel = "<a onclick='cancelactivateDivEditor(this)' class='custom-edit-button cancel' id='cancelactive" + targetID + "'>Cancel</a>";
var targetClass = $('#' + targetID).attr('class');
var targetWidth = $('#' + targetID).width();
$('#' + targetID).css('display', 'none');
$('#input' + targetID).css('display', 'block').css('width', targetWidth - 2).css('height', '125px');
$('#input' + targetID).parent().css('position', 'relative');
$(update).prependTo($('#input' + targetID).parent());
$(cancel).prependTo($('#input' + targetID).parent());
}
JSFiddle Demo
How can I generate a textarea whenever I click on the button link? Need this help badly. Thanks.
My end goal is to have a home page that pulls RSS feeds and displays them on my home page for my personal website. This is all done from the client side and I'm not looking to build a server site script to do this (I will though only if no other way is possible).
Below is the page load code. (I don't think this is a problem area but it nice to see the starting point)
$(document).ready(function () { // Here
loadpageF(); //<- problems is in this function
GetBackGround(document.body); //this just messes with the css of the site
});
function loadpageF() {
addTableFeed("http://www.npr.org/rss/rss.php?id=1001");
addTableFeed("http://news.yahoo.com/rss/odd");
addTableFeed("http://www.nfl.com/rss/rsslanding?searchString=team&abbr=DAL");
addTableFeed("http://www.npr.org/rss/rss.php?id=1007");
$(".MainArea").css("width",$("iframe").length * (270));
}
//This function sets up where the RSS data will be place after formatting
function addTableFeed(feedlink) {
var numOfCell = maintb.getElementsByTagName("iframe").length;
maintb.innerHTML += "<iframe id='f" + numOfCell + "' class='iframeFeed'></iframe>";
getRSSFeed(feedlink, "f" + numOfCell);
}
This code basically calls a function for each rss to add and iframe and the passes the iframe id and the URL to another function (shown below and I am 99% sure is the problem) which getting the data.
function getRSSFeed(feedlink, iframeid) {
/*var xmlhttp; old way I did it below realizing it did not work in firefox
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var hold = xmlhttp.responseText
loadData(hold, iframeid);
}
}
xmlhttp.open("get", feedlink, false);
xmlhttp.send();*/ //end of the old way
//new way to try to use JSON of course failing at my in goal
$.ajax({
type: "GET",
url: feedlink,
async: true,
dataType: "text",
success: function(data){
loadData(data, iframeid);
},
error: function(data, statusCode) {
alert("ERROR: "+data.error)
}
});}
The function loadData works fine when called, however it is not called for the Yahoo.com and NFL.com feed. Instead I get an alert as shown below.
//Note I has to transcribe from dialog box there may be errors
ERROR: function () {
if( list ) {
// First, we save the current length
var start = list length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
¡f( jQuery.isFunction( arg ) && (!options unique || self.has( arg)
list .push( arg);
else if( arg && arg.length ) {
// Inspect recursively
add( arg);
}
});
})( arguments);
//Do we need to add the callbacks to the
// current firing batch?
if (firing ) (
firingLength = list length;
//wiIh memory, if we’re not firing then
// we should call right away
J else if ( memory ) (
firingstart = start;
fire( memory);
Just in case it is needed, below is the load data code.
function loadData(xml, ifid) {
var htmlStr;
var artCount = 0;
var $xml = $($.parseXML(xml));
$("#" + ifid)[0].contentDocument.open();
$("#" + ifid)[0].contentDocument.close();
$("#" + ifid)[0].contentDocument.write("<head><link rel='Stylesheet' type='text/css' href='" + document.getElementById("StyleSheet").href + "' /></head>");
//RSS 2.0 handler
$xml.find("channel item").each(function () {
var $article = $(this);
var title = $article.find("title").text();
var description = $article.find("description").text();
var link = $article.find("link").text();
var pubDate = $article.find("pubDate").text();
htmlStr = "<div id='" + artCount + "Span" + ifid + "' class='ArticalHead'><h3>" + title + "</h3></div>\n";
htmlStr += "<div class='ArticalBody' id='" + artCount + "Div" + ifid + "'>\n";
htmlStr += "\t<p>" + description + "</p><a href='" + link + "' target='_blank' > Click Here For more </a>\n";
htmlStr += "\t<h6>" + pubDate + "</h6><br />\n";
htmlStr += "</div>\n"
$("#" + ifid)[0].contentDocument.write(htmlStr);
$("#" + ifid).contents().find("#" +artCount + "Span" + ifid).click(function () {
$("#" + ifid).contents().find("#" + $(this).attr("id").replace("Span", "Div")).toggle();
});
artCount++;
});
//Atom 1.0 handler
$xml.find("feed entry").each(function () {
var $article = $(this);
var title = $article.find("title").text();
var description = $article.find("summary").text();
var link = $article.find("link").attr("href");
var pubDate = $article.find("published").text();
htmlStr = "<div id='" + artCount + "Span" + ifid + "' class='ArticalHead'><h3>" + title + "</h3></div>\n";
htmlStr += "<div class='ArticalBody' id='" + artCount + "Div" + ifid + "'>\n";
htmlStr += "\t<p>" + description + "</p><a href='" + link + "' target='_blank' > Click Here For more </a>\n";
htmlStr += "\t<h6>" + pubDate + "</h6><br />\n";
htmlStr += "</div>\n"
$("#" + ifid)[0].contentDocument.write(htmlStr);
$("#" + ifid).contents().find("#" + artCount + "Span" + ifid).click(function () {
$("#" + ifid).contents().find("#" + $(this).attr("id").replace("Span", "Div")).toggle();
});
artCount++;
});
//$("#" + ifid).contents().find(".ArticalBody").hide();
}
Please forgive me for any typos or spelling errors. I can also post the whole web page if needed.
I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.