How can create toggleable divs using javascript's innerhtml function? - javascript

I am trying to import information from an XML file, and create a name which, when clicked, will show more information. This information will be inside a div with no display until the header has been clicked.
This is the idea. Doesn't work.
$(document).ready(function () {
$.ajax({
type: "Get",
dataType: "xml",
url: 'service.xml',
success: function (xml) {
$(xml).find('Service[Name="j1979"]').find("Define").each(function () {
var PID = $(this).attr("PID");
var name = $(this).find("Name").text();
var source = $(this).find("source").text();
var doffset = $(this).find("DOffset").text();
var type = $(this).find("Type").text();
var length = $(this).find("Lenght").text();
var scale = $(this).find("Scale").text();
var noffset = $(this).find("NOffset").text();
var units = $(this).find("Units").text();
var moreinfo = "<div id='moreinfo'>source += '\r\n' += doffset += '\r\n' += type += '\r\n' += length += '\r\n' += scale += '\r\n' += noffset += '\r\n' += units</div>";
document.getElementById("j1979").innerHTML += PID += " ";
document.getElementById("j1979").innerHTML += < p onclick = "document.getElementById('moreinfo').style.display = 'inline-block'" > += "\r\n";
document.getElementById("j1979").innerHTML += moreinfo;
});
}
});
});
Sorry for any obvious mistakes and/or ugly code.

I assume that this is what you want to achieve: DEMO
just assume that the script in the demo is inside the success function
first, you have some error in here
document.getElementById("j1979").innerHTML += < p onclick = "document.getElementById('moreinfo').style.display = 'inline-block'" > += "\r\n";
this will not add the p element to the element with id j1979 because you write it like that, where you should be writing it like this
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\" ></p>";
note the quotes at start and end, and the closing tag
second, there's no word or anything inside the p element that indicates that you could click it to show more information, so put the PID inside the p like this
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\">" + PID + "</p>";
here's the full code with some CSS style to hide it before the user click on the PID
$(document).ready(function () {
var PID = "testPID";
var name = "Random Name";
var source = "Google";
var doffset = "1000";
var type = "A-9001";
var length = "50CM";
var scale = "100";
var noffset = "0";
var units = "Some Units";
var moreinfo = "<div id='moreinfo'>source: " + source + "</br>" + "doffset: " + doffset + "</br>" + "type: " + type + "</br>" + "length: " + length + "</br>" + "scale: " + scale + "</br>" + "noffset: " + noffset + "</br>" + "units: " + units + "</div>";
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\">" + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
});
#moreinfo {
display: none;
}
#j1979 {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="j1979"></div>

From the code you have, you can use '+' operator to concatenate strings.
When you need to use single quote inside string defined with single quote, you can use backslash (\) as escape character before it.
Also, you need to hide the div with class "moreinfo" initially.
As for new line, if you want each attribute in new line in moreinfo class, it can be achieved by using HTML "pre" tag or "br" tag or some other way.
So code would be:
var moreinfo = "<pre id='moreinfo' style='display:none'> source = " + source + "\r\n doffset = " + doffset + "\r\n type = " + type + "\r\n length = " + length + "\r\n scale = " + scale + "\r\n noffset = " + noffset + "\r\n units = " + units +"</pre>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
or
var moreinfo = "<div id='moreinfo' style='display:none'> source = " + source + "<br> doffset = " + doffset + "<br> type = " + type + "<br> length = " + length + "<br> scale = " + scale + "<br> noffset = " + noffset + "<br> units = " + units +"</div>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
If you want to toggle display on click, you can use ternary operator to give condition in onclick function:
var moreinfo = "<div id='moreinfo' style='display:none'> source = " + source + "<br> doffset = " + doffset + "<br> type = " + type + "<br> length = " + length + "<br> scale = " + scale + "<br> noffset = " + noffset + "<br> units = " + units +"</div>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display == \'inline-block\' ? document.getElementById(\'moreinfo\').style.display = \'none\' : document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;

I wrote a program where I needed to toggle a div with javascript. I found a solution with this code.
function toggle( selector ) {
var nodes = document.querySelectorAll( selector ),
node,
styleProperty = function(a, b) {
return window.getComputedStyle ? window.getComputedStyle(a).getPropertyValue(b) : a.currentStyle[b];
};
[].forEach.call(nodes, function( a, b ) {
node = a;
node.style.display = styleProperty(node, 'display') === 'block' ? 'none' : 'block';
});
You can then call the function with:
toggle('.idOrClass');
make sure you use single quotes around the class or id name
Hope this helps! :)

Related

Inserting Img tag inside div with innerHTML

I'm trying to have multiple tags inside a div using innerHTML.
Here's an example to better explain my issue.
var y = "jack.jpg";
var x = "Jack";
var f = "Hello world!";
document.getElementById("maindDiv").innerHTML += "<div class = 'result'>" + ": " + "<img src="y"/>" + ": " + x + ": " + f + "</div>" ;
As you can see I have too many apostrophes and I don't know how to use them so to have a variable in the src instead of a string. Thank you.
Check the quotes
document.getElementById("maindDiv").innerHTML += "<div class = 'result'>" + ": " + "<img src='"+y+"'/>" + ": " + x + ": " + f + "</div>" ;
var y = "jack.jpg";
var x = "Jack";
var f = "Hello world!";
document.getElementById("maindDiv").innerHTML += "<div class = 'result'>" + ": " + "<img src='"+y+"'/>" + ": " + x + ": " + f + "</div>" ;
<div id="maindDiv"></div>
You can also use Template strings:
var y = 'jack.jpg';
var x = 'Jack';
var f = 'Hello world!';
document.getElementById("maindDiv").innerHTML += `<div class='result'> + : + <img src=${y}/> + : + ${x} + : ${f} + </div>`;
But notice:
1) Those variables are strings (y, x, f) and you forgot the quotation marks;
2) You can't use the quotation marks when you are using the variable, you must use in the creation time.
Create dynamic variables to change image by just changing y:
You may optionally put them in for loop and iterate over an array to change the value of y:
var y = "jack.jpg";
var tagMaker = "<img src=\'./" + y + "\'>";
now use this:
document.getElementById("maindDiv").innerHTML += tagMaker
Assumptions: your image resides beside html file.

this.id is not working to detect which link is clicked in href

I am new to javascript and I am creating a bookstore using the google API. I have a small issue which I couldn't figure out. In the below piece of code that I saw from example code of google api bookstore function, I am trying to create href for the title of the book and pass its selfLink to the destination page i.e book-description.html.
When I put alert(this.id) on onclick It works, but for a normal method get(this) it does not work. I do not need an alertbox I want to take the id of the link clicked in href and pass it to another html.
handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
var a = item.volumeInfo.title;
var selfL = item.selfLink;
//var b = a.link("book-description.html");
var image = item.volumeInfo.imageLinks.smallThumbnail;
document.getElementById("content").innerHTML += "</br>" + "</br>" + "<br>" + "<img src =" + "'" + image + "'" + " class='im'/>";
document.getElementById("content").innerHTML += "<h4 class='right'>" + "<a href = 'book-description.html'id = " + "'" + selfL + "'" +
"onclick ='get(this);'>" + a + "</a></h4>";
function get(e) {
var link = e.id;
localStorage.setItem("Link", link);
}
document.getElementById("content").innerHTML += "<h4 class='right'>" + "AUTHOR:" + item.volumeInfo.authors + "</h4>";
document.getElementById("content").innerHTML += "<h5 class='right'>" + "PUBLISHER:" + item.volumeInfo.publisher + "</h5>";
var rating = item.volumeInfo.averageRating;
if (rating) {
document.getElementById("content").innerHTML += "<h5 class='right' id='rating'>" + rating + "</h5>";
} else {
document.getElementById("content").innerHTML += "<h5 class = 'right' id ='rating'>Not Rated Yet</h5>";
}
//document.getElementById("content").innerHTML += "<br>" + "<br>" + "<br>" + item.volumeInfo.publisheddate;
}
}
There are a number of problems with your code, but specifically in answer to your question; your function get is scoped so it is only available within the function handleResponse. For it to be accessible from an onclick it must be in page scope.
Simply move this
function get(e) {
var link = e.id;
localStorage.setItem("Link", link);
}
Into the head of your page
In programming there is the concept of DRY (Don't repeat yourself). So store a reference to document.getElementById("content") and reuse that variable.
var content = document.getElementById("content");
content.innerHTML = ...
You're missing some spaces in your output html. This may work in some browsers, others will struggle
<a href = 'book-description.html'id=
Should have a space between the end of one attribute and the start of another
<a href='book-description.html' id=
And for heaven sake, sort out the concatenation of your strings. You dont need a + if its just a simple string
document.getElementById("content").innerHTML += "</br>" + "</br>";
should be
document.getElementById("content").innerHTML += "</br></br>";

array for loop, looping too many times javascript

Instead of looping through one time to show
id1
id2
id3
it loops through 3 times before stopping. what can i put to make it loop through only once.
html:
<p id="show_me"></p>
<button onclick="ObjectArray()">click me</button>
javascript:
var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");
//create an array
var IdArray = [id1, id2, id3];
//for loop to display results
var text="";
var i;
for (i = 0; i < IdArray.length; i++){
text += IdArray[0].firstName + " " + IdArray[0].lastName + " " + IdArray[0].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
}
document.getElementById("show_me").innerHTML = text;
}
It iterates three times, because you loop for the length of the array, which has 3 items.
If you want to 'iterate' once, you can just omit the for loop:
text += IdArray[0].firstName + " " + IdArray[0].lastName + " " + IdArray[0].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
But I think you actually wanted to do this:
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
}
That way you use the loop what it's for: Iterate over an array of any length and repeat a piece of code for each item in the array.
Remove everything from the for loop, and add this instead:
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
Every thing is fine ... but please replaced the following code
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
}
with
for (i = 0; i < IdArray.length; i++){
text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
}

How to add new class to the existing class in this case

I am new to Javascript and Jquery so please excuse if this is a dumb question
HTML is being constructed dynamically as shown
var favoriteresultag = '<ul>';
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
How can i add/concat one more variable to the class ulseWrap lielement ??
I tried this way
var classactive = '';
if (some condition) {
classactive = 'activeRest';
} else {
classactive = '';
}
favoriteresultag += "<section id='" + name + "' class='ulseWrap lielement '+classactive+' '>" + "<div class='intit someclassss'>" + name + "</div>" + "</section>";
String concatenation, just like you're doing:
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement " + classactive + "'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
Try this with jquery if you are using it
$('.actual_class').addClass('new_class')
In your case can be
$('#'+name).addClass('activeRest')
or
$('.ulseWrap.lielement').addClass('activeRest')

How can I jump to another page by clicking a button in Javascript?

I am going to redirect my page by clicking a button. But I am totally messed up by the quotes.
Here is the code:
child.innerHTML += "<a class='sliding-element' href='javascript:sendSurvey(" + (m + 1) + ")'>Survey " + surveyList[m].Name + "</a>" + "<input type='button' onClick='parent.location='QuestionPage.aspx''/>";
It can't redirect me to the QuestionPage.aspx. It simply does nothing.
I don't know what your function does, but you could try escaping the double quotes:
child.innerHTML += "<a class=\"sliding-element\" href=\"javascript:sendSurvey(\" + (m + 1) + \")\">Survey " + surveyList[m].Name + "</a>" + "<input type=\"button\" onClick="parent.location=\"QuestionPage.aspx\""/>";
Don't construct the HTML, construct the elements:
var link = document.createElement("a");
link.className = "sliding-element";
link.href = "";
link.onclick = function (e) {
e = e || window.event;
e.preventDefault && e.preventDefault();
e.returnValue = false;
sendSurvey(m + 1);
};
link.appendChild(document.createTextNode("Survey " + surveyList[m].Name));
var btn = document.createElement("input");
btn.type = "button";
btn.value = "click me";
btn.onclick = function (e) {
parent.location.href = "QuestionPage.aspx";
};
child.appendChild(link);
child.appendChild(btn);
It's a little more verbose, but less prone to errors.
Here's your code made legible-ish:
child.innerHTML += "<a class='sliding-element'"
+ "href='javascript:sendSurvey(" + (m + 1) + ")'>Survey "
+ surveyList[m].Name + "</a>"
+ "<input type='button' "
+ "onClick='parent.location='QuestionPage.aspx''/>";
The quotes inside onClick (that last line) are wrong. You have nested quotes and must escape them, and there's an extra quote at the end.
Change to:
child.innerHTML += "<a class='sliding-element'"
+ "href='javascript:sendSurvey(" + (m + 1) + ")'>Survey "
+ surveyList[m].Name + "</a>"
+ "<input type='button' "
+ "onClick='parent.location=\"QuestionPage.aspx\" />";
child.innerHTML += "<a class='sliding-element' href='javascript:sendSurvey(" + (m + 1) + ")'>Survey " + surveyList[m].Name + "</a>" + "<input type='button' onClick=\"parent.location='QuestionPage.aspx'\"/>";
There's a problem with your quotation marks: You need to use escaped " and not nested '

Categories

Resources