I'm pretty new to javascript and wondering if there's another way of doing this without the use of document.write()
<script>
for (i = 1; i <= 2; i++){
document.write("<div class='menu'>");
document.write("<button id='btn"+i+"' value='"+i * 10+"'>");
document.write("<img class='screen_icon' src='./assets/img/screen.png'>");
document.write("<span class='screenSource'>None</span>");
document.write("<span class='screen_text'>Screen "+i+"</span>");
document.write("</button>");
document.write("</div>");
}
</script>
you can append the div to the parent container
for (var i = 0; i < =2; i++) {
var div = document.createElement('div');
div.innerHTML = "<div class='menu'>" +
"<button id='btn"+i+"' value='"+i * 10+"'>" +
"<img class='screen_icon' src='./assets/img/screen.png'>" + '
"<span class='screenSource'>None</span>" +
"<span class='screen_text'>Screen "+i+"</span>" +
"</button>"+
"</div>"
document.getElementById('parent').appendChild(div);
}
Thanks for your answers , and pointing me in the right direction.
Ended up with this code that you suggested, with a little modification.
for (var i = 1; i <= 2; i++) {
var div = document.createElement('div');
div.innerHTML = "<button id='btn"+i+"' value='"+i * 10+"'>" +
"<img class='screen_icon' src='./assets/img/screen.png'>" +
"<span class='screenSource'>None</span>" +
"<span class='screen_text'>Screen "+i+"</span>" +
"</button>";
document.getElementById('main_menu').appendChild(div);
div.classList.add("menu");
};
Related
Hie i am practicing XML , Javascript. I want to display image for each animal in a row. But my main problem arises uneven nesting in images . Some have two images while some have 4. I have XML File as follows:
<zoo>
<animal>
<common_name>Elephant</common_name>
<images>
<image>elephant13.jpg</image>
</images>
</animal>
<animal>
<common_name>Emu</common_name>
<images>
<image>emu12.jpg</image>
<image>emu26.jpg</image>
<image>emu23.jpg</image>
</images>
</animal>
<animal>
<common_name>Lion</common_name>
<images>
<image>lion51.jpg</image>
<image>lion46.jpg</image>
</images>
</animal>
<zoo>`
My javascript for img is :
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
images.src ="images/" + zooRoot.getElementsByTagName("image")[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
Try this. This get's the document node of xml and queries for images from it. Once you have the array, you iterate over it and get the inner text from the node.
var xmlimages = xml.getElementsByTagName('image');
for(var i=0; i< xmlimages.length; i++) {
images.src = "images/" + xmlimages[i].innerHTML.trim(); // trim used to remove all the white space from text that you get when you use innerHTML
}
Please insert loop on node:
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
var imgData = zooRoot.getElementsByTagName("image");
for (i = 0; i <imgData.length; i++) {
images.src ="images/" + imgData[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
}
Try to get Animal as an object, then create a HTMLstring and insert it in node;
var animalsNode = zooRoot.getElementsByTagName('animal');
var animals = [];
for(var i=0; i<animalsNode.length; i++){
var animalName = animalsNode[i].getElementsByTagName("common_name").innerHTML;
var animalImageNodes = animalsNode[i].getElementsByTagName("image");
var animalImages = [];
//will store image paths into animalImages
for(var j=0; j<animalImageNodes.length; j++){
animalImages.push("image/" + animalImageNodes.innerHTML);
}
animals.push({
common_name: animalName,
images: animalImages //array of image urls
})
}
var animalsHTML = function(animals){
//lets cereate string with "html table"
var animalsHtml = "<table>";
for(var i=0; i<animals.length; i++){
animalsHtml += "<tr>";
animalsHtml += "<td>" + animals[i].name + "</td>"
+ "<td><img src='" + animals[i].images[0] + "' /></td>";
animalsHtml += "</tr>";
}
animalsHtml += "</table>";
return animalsHtml;
}
tableNode.innerHTML = animalsHTML(animals);
or you can define animal array more functional way =)
var animals = zooRoot.getElementsByTagName('animal').map(function(animalNode){
return {
common_name: animalNode.getElementsByTagName('common_name')[0].innerHTML,
images: animalNode.getElementsByTagName('image').map(function(imageNode){
return "image/" + imageNode.innerHTML;
})
};
});
//and more js style of draw-function
var animalsHTML = function(animals){
return "<table>" + animals.reduce(function(curr, next){
return curr + "<tr><td>" + next.name + "</td>"
+ "<td>"
+ next.images.reduce(function(c, n){
return c + "<img src='" + n "' />"
},'')
+ "</td>"
+ "</tr>";
}, '') + "</table>";
}
tableNode.innerHTML = animalsHTML(animals);
I didn't test it, but it should work.
I started new project and I use jquery to add content to article
when I create a slider with this code:
$(".inserttabtext1").click(function () {
var count = parseInt($(".firsttabtextcount").attr("name"), 10);
var name = parseInt($(this).attr("name"));
var id = "#" + name;
var idi,idt,content,idic,idtc;
content = "<div class='short-tabs'><ul>";
for (var i = 1; i <= count; i++)
{
idi = "#ftti" + i;
idic = $(idi).val();
if (i == 1)
{
content += "<li class='active'><a href='#'> " + i + idic + "</a></li>";
}
else
{
content += "<li><a href='#'> "+ i + idic +"</a></li>";
}
}
content += "</ul>";
for (var i = 1; i <= count; i++)
{
if (i==1)
{
content += "<div class='active'>";
}
else
{
content += "<div>";
}
idt = "#fttt" +i;
idtc = $(idt).val();
content += "<p class='text-go-center'>"+idtc+"</p></div>";
}
content += "</div>";
$(id).html(content);
});
and put them into html code my text slider not worked
but when I put manual html code in my page it work
I use these code for copy my html code
$(id).html(content);
$(id).append(content);
where is my wrong?
create a function and put your slider codes inside it, then call it in $(document).ready, and call it again after adding html
$(document).ready(function(){
Init();
});
function Init(){
//Call your slide function here
}
call Init after Adding Html
$(id).html(content);
$(id).append(content);
Init();
I am building a cat clicker game. Where I Have five cat and each one has click function which increase count on every click.
I have created a DOM from javascript function, I have create image from document.create method so that I can attached event to it. So my javascript code contains both pure HTML and HTMLElementObj. fiddle.
But innerHTML is not paring the element which is creating by the document.createElement
function fac(name) {
this.name = name;
this.count = 0;
}
var cats = ['cat1', 'cat2', 'cat3', 'cat4', 'cat5']
function $(name) {
return document.querySelector(name);
}
var html = "";
for (var i = 0; i < cats.length; i++) {
var cat = new fac(cats[i])
html += "<div>";
html += "<div>" + cat.name + "</div>";
var elem = document.createElement('img');
elem.src = 'https://c2.staticflickr.com/2/1126/625069434_db86b67df8_n.jpg';
html += elem;
html += "<div class='count " + i + "'></div>";
html += "</div>";
elem.addEventListener('click', function() {
$('.count' + i).innerText = ++cat.count;
}, false);
$('#getClicked').innerHTML = html
}
You are mixing strings and dom elements and that won't work. Just do everything as strings
html += "<div>";
html += "<div>" + cat.name + "</div>";
var elem = "<img src='https://c2.staticflickr.com/2/1126/625069434_db86b67df8_n.jpg'>";
html += elem;
html += "<div class='count " + i + "'></div>";
or as dom elements (a bit more learning needed to start with but better in the long run)
I am wondering if there is a function I can use so that I can seperate data being called into groups of 6.
here is the long form of the code
var currentResults;
function init() {
getProducts();
}
function getProducts() {
$.ajax({
url:"php/products.php",
dataType: "json",
data: { public: true },
success:function(result){
processResults(result);
}
});
}
function processResults(results) {
currentResults = null;
if (!results && !results.products)
return;
currentResults = results.products;
for (var i = 0; i < results.products.length; i++) {
processResult(results.products[i]);
}
$(".galleryitem").click(handleThumbnailClick);
}
function processResult(result) {
var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">';
newDiv += '<div class="imageHover" style="background: ' + result.color + '"> </div>';
newDiv += '<img class="galleryImage" src="' + encodeImagePath(result.thumbnail) + '" />';
if (result.artist)
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#gallery').append(newDiv);
}
i would like the function to be able to sort the images to groups of 6, something like this... (see areas at bottom with ***'s)
function processResult(result) {
var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">';
newDiv += '<div class="imageHover" style="background: ' + result.color + '"> </div>';
newDiv += '<img class="galleryImage" src="' + encodeImagePath(result.thumbnail) + '" />';
if ***(!!first 6 called!!)***
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#galleryfirst').append(newDiv);
if ***(!!second 6 called!!)***
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#gallerysecond').append(newDiv);
}
Is doing something like this possible? Or does this whole code need an overhaul?
First, pass the index:
for (var i = 0; i < results.products.length; i++) {
processResult(results.products[i], i);
}
Then check it:
function processResult(result, index) {
var newDiv = ...
//check if the index is a multiple of 6
if(index % 6 == 0){
//do something every six results
}
HTH,
-Ted
Since you want to append the new items to different DIVs, the processResults function might be the better place to do this:
function processResults(results) {
var i = 0,
length = results.length,
first = $("#galleryfirst"),
second = $("gallerysecond");
first.append('<div class="imageArtist">' + results[0].artist + '</div>');
for (i; i < 6 && i < length; i++) {
processResult(results[i], first);
}
if (length > 6) {
second.append('<div class="imageArtist">' + results[6].artist + '</div>');
for (i = 6; i < 12 && i < length; i++) {
processResult(results[i], second);
}
}
}
function processResult(product, containerId) {
var newDiv = "...";
// build the HTML for newDiv...
$(containerId).append(newDiv);
}
When I add a padding-left to class ui-block-b it has the side effect that my fixed navbar gets this padding as well, which I do not want. I would like only to apply the padding to the ui-block-b in my ui-gid-a. So I tried to add a new class ui-block-b-own but i do not get the padding in ui-block-b:
CSS:
.ui-block-b-own {
padding-left: 10px !important
}
And this is the code:
function showDetails(index){
var suchresultat = search(); // gets either rezepte or result
$("#rezept h1").html(suchresultat[index].name);
var inhalt = "";
var p = suchresultat[index].portionen;
var m = suchresultat[index].menge;
var z = suchresultat[index].zubereitung;
var textM = "";
var textZ = "";
for( var i = 0; i < m.length; i++ )
{
textM += "<br />" + m[i];
}
for( var i = 0; i < z.length; i++ )
{
textZ += "<br />" + z[i];
}
var por;
if (p == 1){
por = "Portion:";
}
else {
por = "Portionen:";
}
inhalt += '<section class="ui-grid-a">';
inhalt += '<!-- Row1 -->';
inhalt += '<div class="ui-block-a"><strong>Zutaten für<br>'+ p + ' '+ por +'</strong></div>';
inhalt += '<div class="ui-block-b"><strong>Zubereitung:</strong></div>';
inhalt += '<!-- Row2 -->';
inhalt += '<div class="ui-block-a">' + textM + '</div>';
inhalt += '<div class="ui-block-b ui-block-b-own"' + textZ + '</div>';
inhalt += '</section>';
$("#rezeptInhalt").html(inhalt); // füllt page id rezept content
$.mobile.changePage($("#rezept"));
}
Any ideas what I do wrong?
This looks like it is generating invalid HTML. The element in question is missing its closing > before you insert content via textZ. CSS will therefore not be correctly applied, since the browser is probably guessing as to what the correct text content of the node should be.
inhalt += '<div class="ui-block-b ui-block-b-own">' + textZ + '</div>';
//----------------------------------------------^^^^