Google news box within div - javascript

I'm trying to place a google news search within a div on my site. I'm currently using the script google provides, but am a novice at Ajax/JavaScript. I am able to display the most recent stories from google news, but don't know how to have it display within a div let alone manipulate the style with CSS. Below is the code I'm using. Any help would be greatly appreciated!
<script type="text/javascript">
google.load('search', '1');
var newsSearch;
function searchComplete() {
// Check that we got results
document.getElementById('averagecontainer').innerHTML = '';
if (newsSearch.results && newsSearch.results.length > 0) {
for (var i = 0; i < newsSearch.results.length; i++) {
// Create HTML elements for search results
var p = document.createElement('p');
var a = document.createElement('a');
a.href = newsSearch.results[i].url;
a.innerHTML = newsSearch.results[i].title;
// Append search results to the HTML nodes
p.appendChild(a);
document.body.appendChild(p);
}
}
}
function onLoad() {
// Create a News Search instance.
newsSearch = new google.search.NewsSearch();
// Set searchComplete as the callback function when a search is
// complete. The newsSearch object will have results in it.
newsSearch.setSearchCompleteCallback(this, searchComplete, null);
// Specify search quer(ies)
newsSearch.execute('Barack Obama');
// Include the required Google branding
google.search.Search.getBranding('branding');
}
// Set a callback to call your code when the page loads
google.setOnLoadCallback(onLoad);
</script>

If I understand correctly, this is what you need:
Create the <div> and give it an ID:
<div id="your-div">HERE BE NEWS</div>
Then modify the searchComplete funcion like this:
function searchComplete() {
var container = document.getElementById('your-div');
container.innerHTML = '';
if (newsSearch.results && newsSearch.results.length > 0) {
for (var i = 0; i < newsSearch.results.length; i++) {
// Create HTML elements for search results
var p = document.createElement('p');
var a = document.createElement('a');
a.href = newsSearch.results[i].url;
a.innerHTML = newsSearch.results[i].title;
// Append search results to the HTML nodes
p.appendChild(a);
container.appendChild(p);
}
}
}
As for style manipulation, you can match the elements by the given ID in css. For example like this:
#your-div a {
font-weight: bold;
}
EDIT:
To show you that this is working, I have created a jsfiddle: http://jsfiddle.net/enjkG/
There is not a lot of things you can mess up here. I think you may have a syntactic error and did not check the console for errors.

Related

Javascript pulling content from commented html

Bit of a JS newbie, I have a tracking script that reads the meta data of the page and places the right scripts on that page using this:
var element = document.querySelector('meta[name="tracking-title"]');
var content = element && element.getAttribute("content");
console.log(content)
This obviously posts the correct tag to console so I can make sure it's working .. and it does in a test situation. However, on the actual website the meta data i'm targeting is produced on the page by a Java application and beyond my control, the problem is it is in a commented out area. This script cannot read within a commented out area. ie
<!-- your tracking meta is here
<meta name="tracking-title" content="this-is-the-first-page">
Tracking finished -->
Any ideas appreciated.
You can use this code:
var html = document.querySelector('html');
var content;
function traverse(node) {
if (node.nodeType == 8) { // comment
var text = node.textContent.replace(/<!--|-->/g, '');
var frag = document.createDocumentFragment();
var div = document.createElement('div');
frag.appendChild(div);
div.innerHTML = text;
var element = div.querySelector('meta[name="tracking-title"]');
if (element) {
content = element.getAttribute("content");
}
}
var children = node.childNodes;
if (children.length) {
for (var i = 0; i < children.length; i++) {
traverse(children[i]);
}
}
}
traverse(html);
One way is to use a NodeIterator and get comment nodes. Quick example below. You will still need to parse the returned value for the data you want but I am sure you can extend this here to do what you want.
Fiddle: http://jsfiddle.net/AtheistP3ace/gfu791c5/
var commentedOutHTml = [];
var iterator = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT, NodeFilter.FILTER_ACCEPT, false);
var currentNode;
while (currentNode = iterator.nextNode()) {
commentedOutHTml.push(currentNode.nodeValue);
}
alert(commentedOutHTml.toString());
You can try this. This will require you to use jQuery however.
$(function() {
$("*").contents().filter(function(){
return this.nodeType == 8;
}).each(function(i, e){
alert(e.nodeValue);
});
});

Google Apps Script - Move Cursor onclick

I would like to implement a Table of Contents in the sidebar of a Google Docs document which will take you to the appropriate sections when clicked. I am generating the HTML for the sidebar element by element, and I see that there is a moveCursor(position) function in Document class, but I can't see how to actually call it using onclick. Not the full code but shows the problem:
function generateHtml() {
var html = HtmlService.createHtmlOutput('<html><body>');
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
//Iterate each document element
var totalElements = body.getNumChildren();
for(var i = 0; i < totalElements; ++i) {
var element = body.getChild(i);
if(element.getType() == DocumentApp.ElementType.PARAGRAPH) {
var text = paragraph.getText();
if(text.trim()) { //Not blank paragraph
var position = document.newPosition(element, 0);
/**Would like to have <a onclick=document.moveCursor(position)> here**/
//Show first 20 chars as preview in table of contents
html.append('Detected paragraph ')
.append(text.substring(0, 20))
.append('<br />');
}
}
}
html.append('</body></html>');
return html;
}
How can I accomplish this in Apps Script? The code can be completely restructured as needed.
This line:
/**Would like to have <a onclick=document.moveCursor(position)> here**/
Change to:
<div onmouseup="myClientFunction()">Text Here</div>
Add a <script> tag to your HTML:
<script>
var valueToSend = code to get value;
window.myClientFunction = function() {
google.script.run
.myGsFunctionToMoveCursor(valueToSend);
};
</script>
Then you need a myGsFunctionToMoveCursor() function in a script file (.gs extension)
function myGsFunctionToMoveCursor(valueReceived) {
//To Do - Write code to move cursor in Google Doc
. . . Code to move cursor
};

How to dynamically create list of <a> tags using js

I am creating html page which needs to create a list of links dynamically on a click of button. I know how to create this list when number of links to be created is known before like this:
//For 4 tags:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.innerHTML = "link1 text";
aTag.setAttribute('onclick',"func()");
mydiv.appendChild(aTag);
var bTag = document.createElement('b');
bTag.innerHTML = "link2 text";
bTag.setAttribute('onclick',"func()");
mydiv.appendChild(bTag);
var cTag = document.createElement('c');
cTag.innerHTML = "link3 text";
cTag.setAttribute('onclick',"func()");
mydiv.appendChild(cTag);
var dTag = document.createElement('d');
dTag.setAttribute('onclick',"func()");
dTag.innerHTML = "link4 text";
mydiv.appendChild(dTag);
But the problem is that the count will be known at run time and also on function call i need to identify the id of link that invoked function.. Can anybody help?
I don't know weather you receive or not the HTML to be shown in the anchor, but anyway, this should do the work:
function createAnchor(id, somethingElse) {
var anchor = document.createElement('a');
anchor.innerHTML = "link" + id + " text";
anchor.setAttribute("onclick", "func()");
return anchor;
}
Then you call the function like this:
function main(num_anchors) {
var mydiv = document.getElementById("myDiv");
for (var i = 0; i < num_anchors; i += 1) {
mydiv.appendChild(createAnchor(i));
}
}
Of course this code can be improved, but this is just for show how can this be possible.
Yes it is possible to do this at runtime .
JQuery provides very useful dom manipulation . So you can traverse the dom , filter what you need ..
you can find a lot of useful functions here .
http://api.jquery.com/category/traversing/
It would look something like this.
$( document ).ready(function() {
$( "a" ).each(function( index ) {
// enter code here..
}
});
document.ready gets invoked once the DOM has loaded.

Greasemonkey - Find link and add another link

We have an internal inventory at work that is web based. I am looking at add a link say under a link on the page. There is no ID, or classes for me to hook into. Each link at least that I want to add something below it, starts with NFD. I basically need to pull the link text (not the link itself the text that appears to the end user) and use that in my url to call a web address for remoting in.
var links = document.evaluate("//a[contains(#href, 'NFD')]", document, null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i=0; i < links.snapshotLength; i++)
{
var thisLink = links.snapshotItem(i);
newElement = document.createElement("p");
newElement = innerHTML = ' Remote';
thisLink.parentNode.insertBefore(newElement, thisLink.nextSibling);
//thisLink.href += 'test.html';
}
Edit:
What I am looking for basically is I have a link NFDM0026 I am looking to add a link now below that using the text inside of the wickets so I want the NFDM0026 to make a custom link to call url using that. Like say a vnc viewer. The NFDM0026 changes of course to different names.
Here's how to do what you want (without jQuery; consider adding that wonderful library):
//--- Note that content search is case-sensitive.
var links = document.querySelectorAll ("a[href*='NFD']");
for (var J = links.length-1; J >= 0; --J) {
var thisLink = links[J];
var newElement = document.createElement ("p");
var newURL = thisLink.textContent.trim ();
newURL = 'http://YOUR_SITE/YOUR_URL/foo.asp?bar=' + newURL;
newElement.innerHTML = ' Remote';
InsertNodeAfter (newElement, thisLink);
}
function InsertNodeAfter (newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
parent.appendChild (newElement);
else
parent.insertBefore (newElement, targetElement.nextSibling);
}

Google Feed API

I'm having trouble getting Google's load feed to work. Example is supposed to be at www.eslangel.com
I put this code in the header
<script type="text/javascript"
src="https://www.google.com/jsapi?key=ABQIAAAAO2BkRpn5CP_ch4HtkkOcrhQRKBUhIk5KoCHRT6uc9AuUs_-7BhRyoJdFuwAeeqxoUV6mD6bRDZLjSw">
</script>
And then, just to test, I copied and pasted their sample code using a Digg feed into the body of my blog, but there's no result of any kind.
Does anyone have any idea what I might be doing wrong?
/*
* How to load a feed via the Feeds API.
*/
google.load("feeds", "1");
// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
if (!result.error) {
// Grab the container we will put the results into
var container = document.getElementById("content");
container.innerHTML = '';
// Loop through the feeds, putting the titles onto the page.
// Check out the result object for a list of properties returned in each entry.
// http://code.google.com/apis/ajaxfeeds/documentation/reference.html#JSON
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
}
function OnLoad() {
// Create a feed instance that will grab Digg's feed.
var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
// Calling load sends the request off. It requires a callback function.
feed.load(feedLoaded);
}
google.setOnLoadCallback(OnLoad);​
Well, did you also create a container for the feed? :-)
Try placing
<div id="content"></div>
before the feed loading script.

Categories

Resources