Create hyperlink with js dom - javascript

I'm trying to create a wikipedia viewer, get json data and then show it with a hyperlink that take you to the article. The problem is when I want to give the href attribute to a specific element.
$.getJSON(url1 + search + url2, function(data) {
for(i=0; i<data[1].length; i++) {
var p = document.createElement("P");
var id = p.setAttribute("id", i);
var t = document.createTextNode(data[1][i] + ': ');
var text = document.createTextNode(data[2][i]);
var a = document.getElementById(i);
var link = a.setAttribute("href", data[3][i]);
p.appendChild(t);
p.appendChild(text);
p.appendChild(link);
document.body.appendChild(p);
}
});
So, I'm calling the specific "p" element by Id(i value) and then I append to it the specific url. What am I missing?

It actually doesn't make much sense trying to correct parts of your code. The following is a cleaned up and corrected version of yours. Although it is untested, it should produce a format like <p>data[1][i]: data[2][i]</p>.
$.getJSON(url1 + search + url2, function(data)
{
for(var i = 0; i < data[1].length; ++i)
{
//main element
var p = document.createElement("p");
p.id = "element" + i; //you should not use just numbers as IDs
//preceding description
var t = document.createTextNode(data[1][i] + ': ');
//actual link
var text = document.createTextNode(data[2][i]);
var a = document.createElement("a");
a.href = data[3][i];
a.appendChild(text);
//merge all of them together
p.appendChild(t);
p.appendChild(a);
document.body.appendChild(p);
}
});

You are using
p.appendChild(link);
You should be using:
p.appendChild(link);
I think that's not the only thing wrong, your var a = document.getElementById(i); assumes you have an element in the DOM with ids looking like "1" 'var a = document.createElement(a);
$.getJSON(url1 + search + url2, function(data){
for(i=0; i<data[1].length; i++){
var p = document.createElement("p");
var t = document.createTextNode(data[1][i] + ': ');
var text = document.createTextNode(data[2][i]);
var a = document.getElementById(i);
var link = a.setAttribute("href", data[3][i]);
a.appendChild(t);//put text inside the clickable link
a.appendChild(text);//put additional text inside the clickable link
p.appendChild(a);//put the link inside the <p> element
document.body.appendChild(p);//add the link into the DOM at the end of the body
});
//now your element is a <p>data[1][i]: data[2][i]</p>

Related

Remove items from a list if they exist and repopulate the list

I have some code that builds elements of a list on a sidebar. If a button is clicked I want to clear the list and repopulate it with new results. Right now the information just adds to the list. I would like to clear all of the items in the list so I can readd them.
function buildLocationList(data) {
for (i = 0; i < data.locations.length; i++) {
var currentFeature = data.locations[i];
var prop = currentFeature.locations;
var listings = document.getElementById('listings');
var listing = listings.appendChild(document.createElement('div'));
listing.className = 'item';
listing.id = "listing-" + i;
var link = listing.appendChild(document.createElement('a'));
link.href = '#';
link.className = 'title';
link.dataPosition = i;
link.innerHTML = '<b>' + currentFeature.company; + '</b>'
var address = listing.appendChild(document.createElement('div'));
address.innerHTML = currentFeature.address;
var csz = listing.appendChild(document.createElement('div'));
csz.innerHTML = currentFeature.csz;
/*var hours = listing.appendChild(document.createElement('div'));
hours.innerHTML = currentFeature.hours[0].days + ': ' + currentFeature.hours[0].hours;
hours.style.color = 'gray'; */
link.addEventListener('click', function(e){
// Update the currentFeature to the store associated with the clicked link
var clickedListing = data.locations[this.dataPosition];
// 1. Fly to the point
flyToStore(clickedListing);
// 2. Close all other popups and display popup for clicked store
createPopUp(clickedListing);
// 3. Highlight listing in sidebar (and remove highlight for all other listings)
var activeItem = document.getElementsByClassName('active');
if (activeItem[0]) {
activeItem[0].classList.remove('active');
}
this.parentNode.classList.add('active');
});
}
}
For your particular case, add this before you do anything else:
document.getElementById('listings').innerHTML = "";

Javascript button.onclick not functioning like I thought

So I was in the presumption that this function
button.onclick = exampleFunk;
would give me a handler on each button when I click them, but it doesn't. When replacing it with:
button.onclick = alert("bananas");
I'm getting alerts at page onload. The problem is already solved with this:
button.setAttribute("onclick", "removeIssue(this)");
Out of curiousity... What's going on?
edited layout of post
EDIT
var issues = [];
window.onload = function () {
//alert("venster geladen");
issuesToList()
}
function issuesToList(data) {
/*alert(
"array length is " + data.issues.length + "\n" +
"total_count is " + data.total_count + "\n" +
"limit is " + data.limit + "\n" +
"offset is " + data.offset + "\n" + ""
);*/
for (i = 0; i < data.issues.length; i++) {
issue = data.issues[i];
createIssue(issue);
}
}
function createIssue(issue){
var id = issue.id;
var tracker = issue.tracker;
var status = issue.status;
var priority = issue.priority;
var subject = issue.subject;
var description = issue.description;
var assignee = issue.assignee;
var watchers = issue.watchers;
var ticket = new Issue(id, tracker, status, priority, subject, description, assignee, watchers);
issues.push(ticket);
var button = document.createElement("button");
button.innerHTML = "-";
button.onclick = function (){ alert("bananas")};
//button.setAttribute("onclick", "removeIssue(this)");
var item = document.createElement("div");
item.setAttribute("id", id);
item.appendChild(button);
item.innerHTML += " " + subject;
var container = document.getElementById("container");
container.appendChild(item);
}
function removeIssue(e){
var key = e.parentNode.getAttribute("id");
var count = issues.length;
if(confirm("Confirm to delete")){
for(i=0; i<count; i++){
if (issues[i].id == key ){
issues.splice(i,1);
var element = document.getElementById(key);
element.parentNode.removeChild(element);
}
}
}
}
function Issue(id, tracker, status, priority, subject, description, assignee, watchers){
this.id = id;
this.tracker = tracker;
this.status = status;
this.priority = priority;
this.subject = subject;
this.description = description;
this.assignee = assignee;
this.watchers = watchers;
}
EDIT
<body>
<h1>List of Issues</h1>
<div id="container"></div>
<script src="http://www.redmine.org/issues.json?limit=10&callback=issuesToList"></script>
</body>
You need to mask the alert in a function:
button.onclick = function (){ alert("bananas")};
As such:
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.appendChild(t);
btn.onclick = function() {alert("bananas")};
document.body.appendChild(btn);
Whats going on?
You alert() is executed on page load because its a function call. When the execution of your script reaches that line your assignment
button.onclick = alert("bananas");
is actually executing the alert statement and not assigning it to button.onclick
You can bind arguments to the function so that it returns with the function you want it to call using your arguments (with additional arguments passed later added on to the end). This way doesn't require writing extraneous code (when all you want to do is call a single function) and looks a lot sleeker. See the following example:
button.onclick = alert.bind(window, "bananas");
An unrelated example of how it works in your own code is like this:
var alert2 = alert.bind(window, 'Predefined arg');
alert2(); // 'Predefined arg'
alert2('Unused'); // 'Predefined arg'
For IE, this requires IE9 as a minimum. See MDN for more information.
EDIT: I've looked closer at your code and there was one significant change that was needed for it to work... You cannot add onto the innerHTML when you've added JavaScript properties to a child element. Changing the innerHTML of the parent element will convert your element into HTML, which won't have the onclick property you made before. Use element.appendChild(document.createTextNode('My text')) to add text dynamically.
See a functioning example here: http://jsfiddle.net/2ftmh0gh/2/

Getting the id of <a> tag dynamically

I have to create 'a' tags dynamically when the function (lect) get called! And on the onclick() event of this tag, i need to know the id of it. Here is the code that is explaning problem more clearly
function lect(j) {
var mydiv = document.getElementById("cd" + j);
var count = 3;
for (var k = 1; k <= 3; k++) {
var aTag = document.createElement('a');
var inn = "analysis" + k;
var id = "link" + k;
var hr = "#";
aTag.setAttribute('id', id);
aTag.setAttribute('href', hr);
aTag.innerHTML = inn;
aTag.onclick = function (e)
{ // here i want to get the id of tag, so that it could be passed to
// the second html page
location.href = 'gallery-2.html?lectName=' + //name of id// ;
};
mydiv.appendChild(aTag);
}
}
Please help me how should i do it!
You can do:
aTag.onclick = function (e)
{
location.href = 'gallery-2.html?lectName=' + this.id;
};
Within your onclick event, this will refer to the aTag object.

hr tag in javascript

I am working on phonegap and I am new to it. I want to draw a line using hr under the menu items which are displayed. but unfortunately I am unable to do so.
if somebody can help in this regard. Thanks in advance.
here is the code snippet
{
success:function(res,code) {
entries = [];
var xml = $(res);
var items = xml.find("item");
$.each(items, function(i, v) {
category1.push($(v).find("category").text());
/* $("#status").append("menu_type <b>"+menu_type+"</b><br/>"); */
console.log( "PRICE" + ": " + $(v).find("menu_type").text() );
});
var category = category1.unique();
var select = document.getElementById("selectNumber");
for(var i = 0; i < category.length; i++) {
var el1 = document.createElement("li");
var opt = category[i];
var el = document.createElement("a");
el.textContent = opt;
el.value = opt;
el1.appendChild(el);
select.appendChild(el1);
}
}
Try adding something like this
document.getElementById("ElementBelowWhichHRShouldCome").appendChild(document.createElement('hr'));
Try innerHTML. Here is an example:
http://jsfiddle.net/Wxv6n/
var doc = document;
var get = function(id){return doc.getElementById(id);};
get("foo").innerHTML = '<hr/>';
..and don't forget to cache your references to document
After Every Menu Item,you can use this.Its pretty simple.
$("#menu_item").after('<hr/>');
after() in jquery
DEMO FIDDLE

How to add rel='bookmark'?

I'm new here and I'm also not much of a programmer but I hope you guys could help me with Javascript.
You see, I have this 3rd-party script that enables bloggers blogging on Blogger to add some kind of a list of related posts on their pages. Here is the script:
<script type='text/javascript'>
//<![CDATA[
// takes a json feed and creates an HTML-formatted list of the elements
function RelatedPostEntries(json) {
// change the next three variables as required
var homeUrl = 'http://whatever.blogspot.com/';
var maxNumberOfPostsPerLabel = 7;
var TargetElement = 'relatedcontent-list';
var ul = document.createElement('ul');
var maxPosts = (json.feed.entry.length <= maxNumberOfPostsPerLabel) ? json.feed.entry.length : maxNumberOfPostsPerLabel;
for (var i=0; i<maxPosts; i++) {
var entry = json.feed.entry[i];
var alturl;
for (var k=0; k<entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
alturl = entry.link[k].href;
break;
}
}
var li = document.createElement('li');
var a = document.createElement('a');
a.href = alturl;
if(a.href!=location.href) {
var txt = document.createTextNode(entry.title.$t);
a.appendChild(txt);
li.appendChild(a);
ul.appendChild(li);
}
}
for (var l=0; l<json.feed.link.length; l++) {
if (json.feed.link[l].rel == 'alternate') {
var raw = json.feed.link[l].href;
var label = raw.substr(homeUrl.length+13) + ':';
var txt = document.createTextNode(label);
var h = document.createElement('b');
var div = document.createElement('div');
div.appendChild(h);
div.appendChild(ul);
document.getElementById(TargetElement).appendChild(div);
}
}
}
function CodeHook(url, label, callback) {
var script = document.createElement('script');
script.setAttribute('src', url + 'feeds/posts/default/-/' + label + '?alt=json-in-script&callback=' + callback);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
}
//]]>
</script>
The script works fine but the problem is the original programmer has forgotten to add rel='bookmark' to his codings thus leaving us bloggers with a huge headache when it comes to SEO.
Can you guys show me where and how to add that rel attribute?
Thanks.
Try putting a.rel = 'bookmark' after when the element is declared, around here:
...
var li = document.createElement('li');
var a = document.createElement('a');
a.href = alturl;
a.rel = 'bookmark';
...
I think this will work.
var a = document.createElement('a');
a.href = alturl;
a.rel = "bookmark";

Categories