JavaScript - writing html elements that don't show up? - javascript

I'm trying to write some code in javascript that uses a user's cookies to display a box containing some information. The page opens with some boxes containing news articles from Google News RSS feeds. I'm using a 3rd party app for the RSS; the feed is included in the HTML code as such:
<script language="JavaScript" src="http://www.feedroll.com/rssviewer/feed2js.php?src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed" charset="UTF-8" type="text/javascript"></script>
The user can move the boxes around, and I want to store the box locations using cookies so that if a user revisits the page, the boxes will be in the same location. However, when I try to load the page from the information in the cookies, the boxes are blank. This is an example of what my code looks like (RSS feed for news using keyword "Barack Obama"):
// Render boxes into HTML
function renderItem(container) {
var wrapper = document.getElementById(container);
var div_box = document.createElement('div');
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed';
var div_box_feed = document.createElement('div');
var feed_script = document.createElement('script');
feed_script.setAttribute('language', 'JavaScript');
feed_script.setAttribute('src', feed_url);
feed_script.setAttribute('charset', 'UTF-8');
feed_script.setAttribute('type', 'text/javascript');
div_box_feed.appendChild(feed_script);
div_box.appendChild(div_box_feed);
wrapper.appendChild(div_box);
}
When the page loads, the box appears but the news articles from the RSS feed are not there and the box is empty. When I look at the source code, however, it is identical to the code of the initial boxes (which did display the news articles).
Does anybody know what's wrong?
Thanks!

You never declared column_div here:
wrapper.appendChild(column_div);
Did you mean:
wrapper.appendChild(div_box);
?

I believe that by default script elements created in this manner have their async attribute set to true, so the rest of your code will execute before your JS has been retrieved.
Where does the column_div variable come from?

You're missing a question mark to separate the post variables from the URL, so the URL is resolving to
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php%20src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed';
It should be
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php?src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed'

Related

How to change an image on a site using XML data & jQuery

I have a site that has a banner at the top of the page. I've started to overhaul my HTML structure and am now getting various pieces of information that populate the site out of an XML file. My HTML that uses the jQuery is:
<script>
function myExampleSite()
{
var myURL = window.location.href;
var dashIndex = myURL.lastIndexOf("-");
var dotIndex = myURL.lastIndexOf(".");
var result = myURL.substring(dashIndex + 1, dotIndex);
return result;
}
var exampleSite = myExampleSite();
</script>
<script>
var root = null;
$(document).ready(function ()
{
$.get("Status_Pages.xml",
function (xml)
{
root = $(xml).find("site[name='" + exampleSite + "']");
result = $(root).find("headerImage");
$("td#headerImage").html($(result).text());
var imageSrc=$(root).find("headerImage").text();
$(".PageHeader img").attr("src",imageSrc);
result = $(root).find("version");
$("td#version").html($(result).text());
result = $(root).find("status");
$("td#status").html($(result).text());
result = $(root).find("networkNotes");
$("td#networkNotes").html($(result).text());
....etc etc
});
});
</script>
My XML file looks like this.
<sites>
<site name="Template">
<headerImage>images/template-header.png</headerImage>
<productVersion>[Version goes here]</productVersion>
<systemStatus color="green">Normal</systemStatus>
<networkNotes>System status is normal</networkNotes>
</site>
</sites>
I have several <site>s that all have their own data that will populate different areas of individual sites. I've ran into some snags though.
The first snag is how it currently obtains its header image:
html
<div class="container">
<div class "PageHeader"> <!-- Header image read from XML file -->
<img border="0" src=""/>
</div>
Right now it's hard-coded to be the template header image, but I need to make that generic and read the XML value for that site. So instead of being hard-coded as images/template-header.png it would read the XML value for the current site, which is still going to be the template header - but it won't for every page.
How can I read in the image string to populate my HTML so that each site has a different image depending on what's in the XML?
Edit: Edited code to match current issue. Currently, I just get a broken image, but I can still change it back to the hard-coded image URL (images/template-header.png) and it works.
As you already have the code that can extract the image URL information from the XML, which is
result = $(root).find("headerImage");
$("td#headerImage").html($(result).text());
It's now a matter of attaching that URL, to the image tag. We need to select the object, and then simply change it's src attribute. With jQuery this is actually pretty easy. It'll look something like
var root = $(xml).find("site[name='" + site + "']");
//get the image url from the xml
var imageSrc=$(root).find("headerImage").text()
//get all the images in class .PageHeader, and change the src
$(".PageHeader img").attr("src",imageSrc)
And it should work
Example
In conclusion, if you already have some values you want to put in HTML tags dynamically, it's pretty easy. There's .html("<b>bold</b>") for content, there's .attr("attrName","attrValue") for general attributes. .css("background","red") for changing CSS directly. There's also some class modifying stuff that would be useful in the future.

Javascript Validation of dynamic textarea

Hi I'm using a CMS which dynamically creates textareas on product pages of an ecommerce site. The text area has a different ID on each different product page. I am in need of some javascript that will check if all textareas on a page are empty and if so display a warning message. I cant assign an id to the text areas so cant use this script I normally use. Any help is much appreciated!
function validate() {
var val = document.getElementById('textarea').value;
if (/^\s*$/g.test(val)) {
alert('Wrong content!');
}
}
Hey Benjamin thanks for your reply, I couldn't get the code working in comments, thinking I'm having a bad day. So as i was trying to say I'm not the greatest at Javascript (but eager to learn!) I've added this to my page but it doesn't appear to work:
<script>
var areas = document.getElementsByTagName("textarea");
// now iterate them for
(var i=0;i<areas.length;i++){
var val = areas[i].value;
if (/^\s*$/g.test(val)) {
// whatever
}
} </script>
With this as in the body
<div class="description">Further Details <br>
<textarea id="catProdInstructions_6486638" class="productTextarea"></textarea>
</div>
Thanks for your time on this :)
You can use getElementsByTagName to fetch all <textarea>s.
It returns a NodeList of all the text areas currently in the page which you can iterate.
var areas = document.getElementsByTagName("textarea");
// now iterate them
for(var i=0;i<areas.length;i++){
var val = areas[i].value;
if (/^\s*$/g.test(val)) {
// whatever
}
}
The NodeList returned is live , this means that it'll update itself automatically as new textarea elements are added dynamically even if you fetch them with ajax or create them with code.

Tampermonkey - add page using non-existing URL

I'm creating a userscript which adds new functions to a website.
The website has many users, but doesn't have a feature to search for users.I want to create such a function. To do that, I have created a button in the already existing search page for other search purposes. When I click the button, I need the script to search for the input on Google and fetch the URLs and show the results in a piece of HTML code on a non-existing page.
Can I fake an URL with a userscript, so that it uses it to show HTML?
If not, can I replace certain HTML within the page?
The code isn't really that interesting. It just adds a button with a link and selects it when on the non-existing page.
CODE:
if (document.URL == "http://www.bierdopje.com/search" || document.URL == "http://www.bierdopje.com/search/" || window.location.href.indexOf("search/shows") > -1 || window.location.href.indexOf("search/episodes") > -1 || window.location.href.indexOf("search/forum") > -1) {
var users = document.createElement('li');
users.setAttribute('class', 'strong');
var UsersNode = document.createTextNode("Gebruikers");
var UsersLink = document.createElement('a');
UsersLink.setAttribute('href', 'http://www.bierdopje.com/search/users/');
document.getElementById("submenu").childNodes[1].appendChild(users).appendChild(UsersLink).appendChild(UsersNode);
if (window.location.href.indexOf("search/users/") > -1) {
UsersLink.setAttribute('href', './');
UsersLink.setAttribute('class', 'selected');
}
}
Sorry for answering my own question, but like Brock Adams already said: it may have been too localized.
The solution to fake an url is to replace the 404 not found content.
If there's like a container with a header and a paragraph, find the container by making it a variable, and then replace it with another variable:
// find the container
var example = document.getElementById('container').childNodes[0];
// set new container
var newcontainer = document.createElement('div');
newcontainer.setAttribute('id', 'ncontainer');
// replace the existing container with the new one
example.parentNode.replaceChild(replacement, example);
// write content to the new container
document.getElementById('ncontainer').innerHTML ='<p>This is not a 404 anymore</p>';
There are probably a lot more and shorter ways to accomplish this, but they can be found by Google (javascript replace).
To replace the complete page, use
document.write()
To finish the page, you can set the title with the following:
document.title = "WEBSITE TITLE";

Counting classes on another page and displaying them

To save me a lot of work editing a number in when adding a document to a site I decided to use javascript to count the number of elements with a class doc .
I am two main problems:
There is trouble displaying the variable. I initially thought this was because I hadn't added function, however when I tried adding this the variable was still not displayed.
The elements with the class I want to count are on another page and I have no idea how to link to it. For this I have tried var x = $('URL: /*pageURL*/ .doc').length; which hasn't worked.
Essentially I want the total elements with said class name and this to be displayed in a span element.
Currently I have something similar to what's displayed below:
<script>
var Items = $('.doc').length;
document.getElementById("display").innerHTML=Items;
</script>
<span id="display"></span>
Found an example of something similar here where the total numbers of articles are displayed.
Edit:
#ian
This code will be added to the homepage, domain.net/home.html. I want to link to the page containing this documents, domain.net/documents.html. I've seen this done somewhere before and if I remember correctly they used url:domainname.com/count somewhere in their code. Hope this helps.
Here is a jQuery call to retrieve the url "./" (this page) and parse the resulting data for all elements with class "lsep" "$('.lsep', data)". You should get back a number greater than 5 or so if you run this from within your debug console of your browser.
$.get("./", function(data, textStatus, jqXHR)
{
console.log("Instances of class: " + $('.lsep', data).length)
});
One important thing to remember is that you will run into issues if the URL your are trying to call is not in the same origin.
Here's an updated snippet of code to do what you're describing:
$(document).ready(
function ()
{
//var url = "/document.html" //this is what you'd have for url
//var container = $("#display"); //this is what you'd have for container
//var className = '.data'; //this is what you'd have for className
var url = "./"; //the document you want to parse
var container = $("#question-header"); //the container to update
var className = '.lsep'; //the class to search for
$.get(url, function (data, textStatus, jqXHR) {
$(container).html($(className, data).length);
});
}
);
If you run the above code from your browser's debug console it will replace the question header text of "Counting classes on another page and displaying them" with the count of instances the class name ".lsep" is used.
First, you have to wait until the document is ready before manipulating DOM elements, unless your code is placed after the definition of the elements you manipulate, wich is not the case in your example. You can pass a function to the $ and it will run it only when the document is ready.
$(function () {
//html() allows to set the innerHTML property of an element
$('#display').html($('.doc').length);
});
Now, if your elements belongs to another document, that obviously won't work. However, if you have used window.open to open another window wich holds the document that contains the .doc elements, you could put the above script in that page, and rely on window.opener to reference the span in the parent's window.
$('#display', opener.document.body).html($('.doc').length);
Another alternative would be to use ajax to access the content of the other page. Here, data will contain the HTML of the your_other_page.html document, wich you can then manipulate like a DOM structure using jQuery.
$.get('your_other_page.html', function(data) {
$('#display').html($('.doc', data).length);
});

retrieve list of all labels in blogger

Is there a way to use gdata api to retrieve the list of all labels in a blogger?
I need to create a menu based on that list, but cannot simply list all posts and get it, because it is a busy blog and has more than 2000 posts.
Here is the most easy way to get a list of labels by using json call:
<script>
function cat(json){ //get categories of blog & sort them
var label = json.feed.category;
var lst=[];
for (i=0; i<label.length; i++){
lst[i] = label[i].term ;
}
alert(lst.sort()); //use any sort if you need that
}
</script>
<script src="http://yourblog.blogspot.com/feeds/posts/summary?alt=json&max-results=0&callback=cat"></script>
Just use your blog url.
Very simple, I give you two ways
With Javascript API
First, you must use:
<script type="text/javascript" src="http://www.google.com/jsapi"></ script>
<script type='text/javascript'>
google.load("gdata", "1.x", { packages : ["blogger"] });
</script>
Second, you can use the code below to retrieve the labels
postRoot.entry.getCategories()[i].getTerm()
For more tutorials, you can read from http://www.threelas.com/2012/05/how-to-retrieve-posts-using-blogger.html and http://www.threelas.com/2012/04/basic-blogger-javascript-api.html
With JSON
with json, if you want to learn how to retrieve the list of labels, use this object
json.feed.entry[i].category[j].term
for more detail tutorials, read from http://www.threelas.com/2012/02/basic-blogger-json-feed-api.html and http://www.threelas.com/2012/09/blogger-json-feed-with-jquery-ajax.html
The way I found was using the Blogger's own gadget called Labels. It prints the list of labels and their usage count within some unordered lists(ul) and links(a). You can pull the labels from that after they are loaded using javascript as follows:
$(".list-label-widget-content a").each(function (i, el) {
var labelText = $(el).text();
// do what you want with the labels
});
in the end, remove the Labels div element (<div class='widget Label' id='Label1'>)
Widget to server the same purpose is provided by bloggers itself.
Widget provides various options like -
You can either show all Labels or choose from your existing List
You can sort the Labels alphabetically or by number of times that label is used (frequency).
You can choose to display these as a List or as a cloud (jumbled).
You can see the same in my blog - Link
I don't see a method to get the list of labels in a blog, but you can retrieve all posts (https://developers.google.com/blogger/docs/2.0/json/reference/posts/list) and check the labels field for each of them: https://developers.google.com/blogger/docs/2.0/json/reference/posts#resource
First add the JQuery through the following code in console.
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
// ... give time for script to load, then type (or see below for non wait option)
jQuery.noConflict();
Once you are done with this we can take advantage of the JQuery and get the list of labels
Now what I am doing will work for the Blogger Theme Notable and newly added Theme for blogger.
Normally in these themes you will see Labels in the rights side toogle menu of the page.
So What you need it Click on the Label and Click on Show more.
Now Open Browser Debugging console and declare and variable.
var str = "";
Now run the two codes below
1. $('.first-items .label-name').each(function(){str = str + ", "+($(this).text())})
2. $('.remaining-items .label-name').each(function(){str = str + ", "+($(this).text())})
3. str
all the labels you will be get in comma(;) separated format.

Categories

Resources