I have craeted a new div and inside the div Idisplay the information about a topic and also a link to read more about the topic, but my onlick funciton is not working it keeps telling that id is not define. How can I pass value thru innerHTML
function displayNews(section, id, title) {
var section = section;
var id = id;
var title = title;
contentDiv.innerHTML = '<div onclick="displayInfo(id, title);">More info</div>';
}
You could make a real element rather than html to optionally do this.
function displayNews(section, id, title) {
var section = section;
var id = id;
var title = title;
var element = document.createElement('div');
element.onclick = function () {
displayInfo(id, title);
};
element.innerHTML = "More info";
//i don't see contentDiv defined, but this shows the operation
contentDiv.appendChild(element);
}
You didn't properly concatenate the values.
This is what you meant to do, I guess:
function displayNews(section, id, title) {
var section = section;
var id = id;
var title = title;
var div = '<div onclick="displayInfo(' + id + ', "' + title + '");">More info</div>';
alert(div);
}
displayNews(1, 2, 3);
Related
I'm looping through some elements by class name, and adding event listeners to them. I then grab the id of the selected element (in this case "tom"), and want to use it to find the value of "role" in the "tom" object. I'm getting undefined? can anyone help?
var highlightArea = document.getElementsByClassName('highlightArea');
for (var i = 0; i < highlightArea.length; i++) {
highlightArea[i].addEventListener("mouseover", showPopup);
highlightArea[i].addEventListener("mouseover", hidePopup);
}
function showPopup(evt) {
var tom = { title:'tom', role:'full stack man' };
var id = this.id;
var role = id.role;
console.log(role)
}
You are not selecting the elements correctly, the class is hightlightArea and you are querying highlightArea (missing a 't'), so, no elements are found (you can easily discover that by debugging or using console.log(highlightArea) that is the variable that holds the elements found.
Just because the id of an element is the same name as a var, it doesn't mean that it have the properties or attributes of the variable... So when you get the Id, you need to check which one is and then get the variable that have the same name.
Also, you are adding the same listener two times mouseover that way, just the last would work, it means just hidePopup. I changed to mouseenter and mouseleave, this way will work correctly.
After that, you will be able to achieve your needs. Below is an working example.
var highlightArea = document.getElementsByClassName('hightlightArea');
var mypopup = document.getElementById("mypopup");
var tom = { title:'tom', role:'marketing'};
var jim = { title:'jim', role:'another role'};
for (var i = 0; i < highlightArea.length; i++) {
highlightArea[i].addEventListener("mouseenter", showPopup);
highlightArea[i].addEventListener("mouseleave", hidePopup);
}
function showPopup(evt) {
let ElemId = this.id;
let role;
let title;
if (ElemId == 'tom'){
role = tom.role;
title = tom.title;
}else if (ElemId == 'jim'){
role = jim.role;
title = jim.title;
}
let iconPos = this.getBoundingClientRect();
mypopup.innerHTML = role;
mypopup.style.left = (iconPos.right + 20) + "px";
mypopup.style.top = (window.scrollY + iconPos.top - 60) + "px";
mypopup.style.display = "block";
}
function hidePopup(evt) {
mypopup.style.display = "none";
}
<div class="hightlightArea" id="jim">Div Jim</div>
<div class="hightlightArea" id="tom">Div Tom</div>
<div id="mypopup"></div>
in your function 'showPopup' you have this:
var id = this.id
but this.id is not defined. You probably meant to write this:
var title = dom.title;
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>
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/
I've got this method speak(), which takes two arguments. It's a property of the prototype, so multiple objects will use it.
I'd like to grab those values it returns, loop through them, and output them to my html. The part I can't figure out is, how do I target each individual paragraph tag to correspond with the output of each from each of my variables generated results?
Would this require a double loop? I'm lost.
var para = document.querySelectorAll('p');
var speak = function(what, job) {
var whoWhat = this.name + ' says, ' + what,
whoJob = this.name + "'s job is: " + job;
console.log(whoWhat);
console.log(whoJob);
return whoWhat, whoJob;
};
function Peep(name, job) {
this.name = name;
this.job = job;
}
Peep.prototype.speak = speak;
var randy = new Peep('Randy', 'lawyer');
randy.speak('"blahblah"', randy.job);
var mandy = new Peep('Mandy', 'mom');
mandy.speak('"woooooaahhhh"', mandy.job);
Here's a jsfiddle
Check this one - jsFiddle
Keep adding the HTML to a text. And finally add them to the DOM.
var speak = function(what, job) {
var whoWhat = this.name + ' says, ' + what,
whoJob = this.name + "'s job is: " + job;
console.log(whoWhat);
console.log(whoJob);
return "<p>"+whoWhat+", "+whoJob+"</p>";
};
var txt = "";
var randy = new Peep('Randy', 'lawyer');
txt+=randy.speak('"blahblah"', randy.job);
var mandy = new Peep('Mandy', 'mom');
txt+=mandy.speak('"woooooaahhhh"', mandy.job);
document.getElementById('result').innerHTML = txt;
//in HTML add the result node
<body>
<p id='result'>
</p>
</body>
Using JavaScript you can access the DOM (Document Object Model) and can append new elements to existing elements. For example, you could create a new paragraph element and add this paragraph element to an existing div with the id "result". Here is an example:
var appendText = function (text, parentId) {
var para = document.createElement("p");
var node = document.createTextNode(text);
para.appendChild(node);
var parentElement = document.getElementById(parentId);
parentElement.appendChild(para);
}
var speak = function (what, job) {
var whoWhat = this.name + ' says, ' + what,
whoJob = this.name + "'s job is: " + job;
return [whoWhat, whoJob];
};
function Peep(name, job) {
this.name = name;
this.job = job;
}
Peep.prototype.speak = speak;
var randy = new Peep('Randy', 'lawyer');
var randySays = randy.speak('"blahblah"', randy.job);
appendText(randySays[0], "result");
appendText(randySays[1], "result");
var mandy = new Peep('Mandy', 'mom');
var mandySays = mandy.speak('"woooooaahhhh"', mandy.job);
appendText(mandySays[0], "result");
appendText(mandySays[1], "result");
Here is the jsfiddle with the required html: http://jsfiddle.net/stH7b/2/. You can also find more information on how to append a paragraph to the DOM here: http://www.w3schools.com/js/js_htmldom_nodes.asp
function B(sName) {
this.name = sName;
}
B.prototype = {
instanceCreatButtonCount: 0,
funA: function () { // alert instance's name
alert(this.name);
},
funB: function () { // create a button which clikced can alert this instance's name through funA;
var that = this;
B.prototype.instanceCreatButtonCount++;
var id = "_id" + that.instanceCreatButtonCount;
var str = "<button id='" + id + "' >clike me</button>";
var a = document.getElementById("btns");
a.innerHTML += str;
var btn = document.getElementById(id);
btn.onclick = function () {
that.funA();
};
}
};
var b1 = new B("Jim");
var divB1 = document.getElementById("b1");
divB1.onclick = function () {
b1.funB();
}
var b2 = new B("Dad");
var divB2 = document.getElementById("b2");
divB2.onclick = function () {
b2.funB();
}
After I click divB1, I create a button through b1.funB().
After I click divB2, I create a button througb b2.funB().
Why can only newest button alert name ? I find that other button's onclick function is null.
When you use a.innerHTML += str to append a new element, the entire subtree of a gets removed before the new elements are added again; the removal also unbinds any events you have added before.
It's better to use proper DOM functions in this case, i.e. var btn = document.createElement(), etc. and a.appendChild(btn).
Fiddle provided by #ShadowWizard: http://jsfiddle.net/qR6e8/