Creating div and adding a background image to it - javascript

I've managed to make a div in the place where I wanted it to be, but when it comes to adding a background image, I just can't do it.
I'm creating divs with the loop and then I'm trying to add a background image to it in the same loop. I don't know if that's the problem or something else, if that's the case, please help me make another.
I tried doing something like itemContainer[i] but I can't get that to work either.
Update: the reason is that my array is empty, don't really know what I'm doing wrong though.
var cicon = [];
$.ajax({
url: '/json/test.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.test).each(function(index, value) {
cicon.push(value.Icon);
/*console.log(value.Icon) works here,
so there's something wrong when I'm adding it to the array.*/
});
}
});
for (var i = 0, n = 10; i < n; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.innerHTML = "item" + i;
itemContainer.style.width = "86px";
itemContainer.style.height = "86px";
itemContainer.style.margin = "5px";
itemContainer.style.border = "2px solid black";
itemContainer.style.borderRadius = "10px";
itemContainer.style.float = "left";
var iconstring = 'url(\'' + cicon[i] + '\')';
itemContainer.style.backgroundSize = "100% 100%";
itemContainer.style.backgroundImage = iconstring;
document.getElementById('page').appendChild(itemContainer);
}
If anyone is wondering, the array contains urls that look like this: https://steamcdn-a.akamaihd.net/apps/440/icons/earbuds.f6dc85683202f2530ae8728880f4a47d4b013ea8.png

If you re-declare:
var cicon = [];
you are simply emptying the array variable. (how do i empty an array in javascript)
Example:
var cicon = [];
function doWork() {
for (var i = 0; i < cicon.length; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.innerHTML = "item" + i;
itemContainer.style.width = "86px";
itemContainer.style.height = "86px";
itemContainer.style.margin = "5px";
itemContainer.style.border = "2px solid black";
itemContainer.style.borderRadius = "10px";
itemContainer.style.float = "left";
var iconstring = 'url(\'' + cicon[i] + '\')';
itemContainer.style.backgroundSize = "100% 100%";
itemContainer.style.backgroundImage = iconstring;
document.getElementById('page').appendChild(itemContainer);
}
}
$(function () {
$.ajax({
url: '/json/BotCopper.json',
dataType: 'json',
type: 'get',
cache: false,
success: function (data) {
$(data.BotCopper).each(function (index, value) {
cicon.push(value.Icon);
doWork();
});
},
error: function (jqXHR, textStatus, errorThrown) {
// this is only for test
cicon = ['https://rawgit.com/Pixabay/jQuery-flexImages/master/images/1.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/2.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/3.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/4.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/5.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/6.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/7.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/8.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/9.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/10.jpg'];
doWork();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="page"></div>
Instead, removing the line:
var cicon = [];
the result is:
window.onload = function() {
var cicon = ['https://rawgit.com/Pixabay/jQuery-flexImages/master/images/1.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/2.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/3.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/4.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/5.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/6.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/7.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/8.jpg',
'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/9.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/10.jpg'];
for (var i = 0, n = 10; i < n; i++) {
var itemContainer = document.createElement("div");
itemContainer.id = "div" + i;
itemContainer.innerHTML = "item" + i;
itemContainer.style.width = "86px";
itemContainer.style.height = "86px";
itemContainer.style.margin = "5px";
itemContainer.style.border = "2px solid black";
itemContainer.style.borderRadius = "10px";
itemContainer.style.float = "left";
var iconstring = 'url(\'' + cicon[i] + '\')';
itemContainer.style.backgroundSize = "100% 100%";
itemContainer.style.backgroundImage = iconstring;
document.getElementById('page').appendChild(itemContainer);
}
}
<div id="page"></div>

There is nothing wrong with your script but you need elements in cicon. e.g
var cicon = ["url1","url2",...];
Check here for a working example: Div Background image

Related

Changing DOM properties inside AJAX call not working

I have a function which makes an AJAX call and depending on the answer, sets the colour of an input. The function core itself works fine. However, when it comes to changing the colour of the input, it is not working.
function Nueva_Red() {
var e1 = document.getElementById("rrss_tipo");
var e2 = document.getElementById("rrss_usuario");
var e3 = document.getElementById("redes");
var e4 = document.getElementById("alta_nueva_red");
var id_red = e1.options[e1.selectedIndex].value;
var red = e1.options[e1.selectedIndex].text;
var usuario = e2.value;
e2.style.backgroundColor = "none";
e2.style.borderColor = "black";
if ((id_red > 0) && (usuario != "")) {
var datastr = 'seccion=rrss_check&dato=' + id_red + "|" + usuario;
$.ajax({
type: 'GET',
url: 'validacion.php',
data: datastr,
success: function(html) {
if (html == 1) {
document.getElementById("nuevas_rrss").style.visibility = "visible";
document.getElementById("nuevas_rrss").style.display = "inline-block";
var opcion = document.createElement("option");
opcion.value = id_red + "-" + usuario;
opcion.innerHTML = red + " -> " + usuario;
e3.appendChild(opcion);
e1.value = 0;
e2.value = "";
e2.title = "";
e2.style.backgroundColor = "none";
e2.style.borderColor = "black";
} else {
e2.title = html;
e2.style.backgroundColor = error_error;
e2.style.borderColor = error_error;
}
},
error: function(html) {
e2.style.borderColor = error_app;
e2.style.backgroundColor = error_app;
}
});
}
}
Thank you!

How to filter content by category in JavaScript

I have created an accordion with categories. I am pulling the content from a share point list with an ajax call. Each item on the share point list has its category assigned (automotive, entertainment, housing, etc). I need every item to be filtered by category.
https://jsfiddle.net/angelogianopulos/7L392emj/11/
$(document).ready(function() {
/*r container = document.createElement("div");
container.setAttribute('id', 'container');
container.classList.add('container', 'text-center', 'my-5');*/
$.ajax({
url: "http://bc-net/_api/web/lists/GetByTitle('specialDiscounts')/items",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
var items = data.d.results;
console.log(items);
var createRows = function(i, items) {
//Creates 3 Rows inside container
var row = document.createElement("div");
row.setAttribute('id', 'row' + i);
row.classList.add('row', 'animated', 'fadeInUp');
//Appends Row to Container
var getContainer = document.getElementById('automotive');
getContainer.appendChild(row);
createColumns(i, items);
}; //End of creare Rows Function
//Creates columns
var createColumns = function(i, items) {
for (var j = i; j < (i + 3); j++) {
//Creates 3 Columns inside the 3 rows
var columns = document.createElement("div");
columns.setAttribute('id', 'columns' + j);
columns.classList.add('col-md-4');
//appends the 3 columns inside the rows
var getRow = document.getElementById('row' + i);
getRow.appendChild(columns);
//Create single News
var singleNews = document.createElement("div");
singleNews.setAttribute('id', 'singleNews' + j);
singleNews.classList.add("single-news", "mb-4");
var getColumns = document.getElementById('columns' + j);
getColumns.appendChild(singleNews);
//Inside Row
var insideRow = document.createElement("div");
insideRow.setAttribute('id', 'insideRow' + j);
insideRow.classList.add('row');
var getsingleNews = document.getElementById('singleNews' + j);
getsingleNews.appendChild(insideRow);
//Col-md-3
var insideCol = document.createElement("div");
insideCol.setAttribute('id', 'insideCol' + j);
insideCol.classList.add('col-md-3');
//Col-md-9
var insideColRight = document.createElement("div");
insideColRight.setAttribute('id', 'insideColRight' + j);
insideColRight.classList.add('col-md-9');
var getInsideRow = document.getElementById('insideRow' + j);
getInsideRow.appendChild(insideCol);
getInsideRow.appendChild(insideColRight);
//Rounded Image Class
var rounded = document.createElement("div");
rounded.setAttribute('id', 'rounded' + j);
rounded.classList.add('rounded', 'z-depth-1', 'mb-4');
var getinsideCol = document.getElementById('insideCol' + j);
getinsideCol.appendChild(rounded);
//Pulls the images from the list
var image = document.createElement("img");
image.setAttribute('id', 'image' + j);
image.classList.add("img-fluid");
image.src = items[j].Image.Url;
var getRounded = document.getElementById('rounded' + j);
getRounded.appendChild(image);
//Pulls header from the list
var title = document.createElement("p");
title.setAttribute('id', 'title' + j);
title.innerHTML = items[j].Title;
title.classList.add("font-weight-bold", "dark-grey-text");
insideColRight.appendChild(title);
var justifyContent = document.createElement('div');
justifyContent.setAttribute('id', 'justifyContent' + j);
justifyContent.classList.add('d-flex', 'justify-content-between', 'topSpace');
insideColRight.appendChild(justifyContent);
var textTruncate = document.createElement('div');
textTruncate.setAttribute('id', 'textTruncate' + j);
textTruncate.classList.add('col-11', 'text-truncate', 'pl-0', 'mb-3');
justifyContent.appendChild(textTruncate);
//Pulls anchor from the list
var anchor = document.createElement("a");
anchor.setAttribute('id', 'anchor' + j);
anchor.setAttribute('href', items[j].Link.Url, +j);
anchor.setAttribute('target', '_blank', +j);
anchor.classList.add("dark-grey-text");
anchor.innerHTML = items[j].Description;
textTruncate.appendChild(anchor);
var arrowAnchor = document.createElement("a");
arrowAnchor.setAttribute('id', 'arrowAnchor' + j);
arrowAnchor.setAttribute('target', '_blank' + j);
arrowAnchor.setAttribute('href', items[j].Link.Url, +j);
justifyContent.appendChild(arrowAnchor);
var iconArrow = document.createElement('i');
iconArrow.classList.add('fas', 'fa-angle-double-right');
var getarrowAnchor = document.getElementById('arrowAnchor' + j);
getarrowAnchor.appendChild(iconArrow);
//var test = document.getElementById( 'arrowAnchor' + j);
//test.onclick = function() {
// console.log('Hello');
//}
} //End of j Loop
return;
} // End of createColumns function
//Array of categories
var catGroup = [];
console.log(catGroup);
if (items.length > 0) {
for (var i = 0; i < items.length; i++) {
var categories = items[i].Category;
console.log(categories)
catGroup.push(categories);
if (catGroup[i] === "Automotive") {
var automotive = document.getElementById('automotive');
console.log(catGroup[i]);
}
if (catGroup[i] === "Entertainment") {
var entertainment = document.getElementById('entertainment');
console.log(catGroup[i]);
}
if (catGroup[i] === "Health and Beauty") {
var health = document.getElementById('health');
console.log(catGroup[i]);
}
if (catGroup[i] === "Travel") {
var travel = document.getElementById('travel');
console.log(catGroup[i]);
}
if (catGroup[i] === "Electronics") {
var electronics = document.getElementById('electronics');
console.log(catGroup[i]);
}
if (catGroup[i] === "Services") {
var services = document.getElementById('services');
console.log(catGroup[i]);
}
if (catGroup[i] === "Housing") {
var housing = document.getElementById('housing');
console.log(catGroup[i]);
} else {}
if (i % 3 == 0) {
createRows(i, items);
} //end of % if statement
} //End of for loop
} //End of if item.length statement
},
error: function(data) {
alert("Error: " + data);
}
}); //End Service Icons //End Service Icons
}); //End ready function
I expect every item to be placed by category in its own content panelenter image description here
After looking into your question, what I understood is you just want to filter your data on the basis of 'category assigned'.
I will refer you to use JavaScript Filter like so:
const result = items.filter(Category => Category === "Automotive" );
Or, if you can use Lodash, there are a lot of ways to filter and even you can group by the Category.
You can check out here for Lodash:
Documentation Lodash
If I misunderstood your question, please let me know so I can edit my answer.

CSS to style javascript dynamically created table

I'm needing to style a table that's dynamically created by javascript. I know how to style it if it were just a static HTML table but this is different and I'm not too familiar with javascript. Here is the javascript code:
[var aryPortalList = \[\];
function getPortalList() {
var wP = window.location.protocol;
var wH = window.location.host;
var wPath = "ibi_apps/rs/ibfs/BIP/Portals?IBIRS_action=get";
//http://webfocusclidev:8080/ibi_apps/rs/ibfs/BIP/Portals?IBIRS_action=get;
var webfocusAPI = wP + "//" + wH + "/" + wPath;
$.ajax({
type: "GET",
async: false,
url: webfocusAPI,
dataType: 'xml',
success: function(xml) {
$(xml).find('children').children().each(function() {
var portal = { Name: $(this).attr('bipName'),
Link: "/ibi_apps/bip/portal" + $(this).attr('bipPath'),
IconLink: "/ibi_apps/WFServlet.ibfs?IBFS1_action=RUNFEX&IBFS_path=" + $(this).attr('bipIconPath')
}; //var portal
console.log("portal.name=" + portal.Name);
if (portal.Name != "GlobalBI") aryPortalList.push(portal);
}); //each
console.log("Portals in List = " + aryPortalList.length);
} //success function
}); //ajax
}
function displayPortalList_Icon() {
if (aryPortalList.length == 0) {
var hTxt = "<p>You do not have access to any portals</p>";
$("#portallist").append(hTxt);
} else {
var bRowAdded = false;
var hTbl=$("<table id='tbl_portallist'></table>");
var row = $('<tr></tr>').addClass('ingrPL_row');
console.log("Portals in List = " + aryPortalList.length);
for(var j=0; j < aryPortalList.length; j++) {
var cell = $("<td align = 'center'></td>");
var hTxt = $("<p>" + aryPortalList\[j\].Name + "</p>");
var hLink = $("<a>").attr({"href": aryPortalList\[j\].Link,
"target": "_blank"});
var img = $("<img>").attr("src", aryPortalList\[j\].IconLink);
img.width("100px");
img.height("100px");
console.log("hTxt=" + hTxt);
hLink.append(img);
cell.append(hTxt);
cell.append(hLink);
row.append(cell);
bRowAdded = false;
if ((j+1) % 4 == 0) {
hTbl.append(row);
bRowAdded = true;
var row = $('<tr></tr>').addClass('ingrPL_row');
}
}
if (!bRowAdded) {
hTbl.append(row);
}
$("#portallist").html(hTbl);
}
}
function displayPortalList_List() {
if (aryPortalList.length == 0) {
var hTxt = "<p>You do not have access to any portals</p>";
$("#portallist").append(hTxt);
} else {
var bRowAdded = false;
var hTbl=$("<table id='tbl_portallist'></table>");
console.log("Portals in List = " + aryPortalList.length);
for(var j=0; j < aryPortalList.length; j++) {
var row = $('<tr></tr>').addClass('ingrPL_row');
var cell = $("<td align = 'center'></td>");
var hTxt = $("<p>" + aryPortalList\[j\].Name + "</p>");
var hLink = $("<a>").attr({"href": aryPortalList\[j\].Link,
"target": "_blank"});
console.log("hTxt=" + hTxt);
hLink.append(hTxt);
cell.append(hLink);
row.append(cell);
hTbl.append(row);
}
$("#portallist").html(hTbl);
console.log("portal.name=" + portal.Name);
}
}][1]
And I've attached a photo of how the 'portal' looks.
What I need to do is space out the icons more and have the title's on the bottom of the icons, to look more like an 'iphone app'
Any help is greatly appreciated.
you can style it in the same way you style static elements
looking at your code I can see the table have an ID and the rows have classes
var hTbl=$("<table id='tbl_portallist'></table>");
var row = $('<tr></tr>').addClass('ingrPL_row');
so you can select those in your CSS file
CSS
#tbl_portallist {
/*table style here */
}
#tbl_portallist th {
/*table head style here*/
}
#tbl_portallist tr {
/*table row style here*/
}
#tbl_portallist td {
/*table data (cell) style here*/
}

How can I wait until all my images are loaded before adding them to html?

I am trying to get multiple images from an ajax source and load the on the page when they have all finished loading. The issue I was having that has caused me to try to find a solution was that some of the images weren't loading even though those images existed on the server.
I have tried to add code that now adds the image to an array
design_images.push({cid:designImg});
... and then when all the images have loaded will add that to the page, but I can't get that to work.
var counter = 0;
$(design_images).load(function() { // many or just one image(w) inside body or any other container
counter += 1;
}).each(function(key, value) {
this.complete && $(this).load();
console.log(value);
});
Nothing is outputted from the .each
This is the output of the array design_images
The value of design_images.length is 0 though.
Here is the complete function:
function matte_design_change_design_type(element)
{
var element_value = null;
var mattes_selected_type = get_mattes_selected_type();
matte_design_widths[mattes_selected_type] = [];
var mattes_selected_design = get_mattes_selected_design();
var count_matte_designs = 0;
var found = false;
$(document).ready(function()
{
$.ajax(
{
type: "GET",
url: SITE_URL + "/system/components/xml/" + mattes_selected_type,
dataType: 'xml',
success: function(xml)
{
var output = [];
var design_images = [];
$('component', xml).each(function(i, el)
{
matte_design_widths[mattes_selected_type][i] = 0;
count_matte_designs++;
var thumb = $("thumb", this).text(),
cid = $("cid", this).first().text(),
name = $("name", this).first().text().replace("Collage - ", ""),
alt = name,
description = $("description", this).first().text(),
if (parseInt(cid, 10) === mattes_selected_design)
{
found = true;
$("#matte_design_name").html(name);
$("#matte_design_description").html(description);
}
var designImg = new Image();
designImg.id = 'cid_' + cid;
designImg.alt = alt;
designImg.onclick = function() {
matte_design_change(cid, mattes_selected_type);
};
designImg.onload = function() {
output.push('<span class="matte_design_image_name" id="design_' + cid + '"><img id="cid_' + cid + '" />');
output.push('<br /><span class="matte_design_name" id="matte_design_name_' + mattes_selected_type + '_' + i + '">' + name + '</span></span>');
matte_design_increase_width(mattes_selected_type, this.width, i);
$('#matte_designs_strip_wrapper').html(output.join(''));
};
designImg.src = 'https://example.com/system/components/compimg/' + thumb + '/flashthumb';
});
var counter = 0;
var size = $('img').length;
$(design_images).load(function() {
counter += 1;
}).each(function(key, value) {
this.complete && $(this).load();
console.log(value);
});
}
});
});
}
I have tried waitForImages and imagesLoaded but I couldn't get them to work for me, but I'm not opposed to using either one.
Hide all images by default using CSS
img{
display: none;
}
Use Jquery to check if all loaded, then display images
JQuery
$(window).load(function(){
$('img').fadeIn(800); //or $('img').show('slow');
});

Why is JavaScript Array Returning "Undefined"? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I've been building an app in jQuery and html 5 that reads rss feed of a blog. I wanted to show a list of titles of rss and when user clicks on the title it goes to a different page where full content is shown. I could get content using ajax and store them in an array. But when I'm clicking on the title, it shows undefined on the next page. I am using jQuery pages.
$(document).ready(function() {
load_posts();
});
function load_posts() {
var PAGINATION = $('#pagination');
var HTML1 = '<li><a href="#post" data-transition="slide" id ="';
var HTML5 = '"><h4>';
var HTML2 = '</h4>';
var HTML3 = '<p>';
var HTML4 = '</p></a></li>';
var btn = "";
var selector = "";
var i = 0;
var title = "";
var pubDate = "";
var dascription = "";
var anchorID = "";
var url = "";
var fullPost = new Array;
var link = new Array;
$.ajax({
type: 'GET',
url: 'http://smushbits.com/feed/',
dataType: 'xml',
error: function() {
alert("An error occured!");
},
success: function(xml) {
$(xml).find('item').each(function() {
title = $(this).find('title').text();
pubDate = $(this).find('pubDate').text();
pubDate = pubDate.substring(5, 16);
description = $(this).find('encoded').text();
url = $(this).find('link').text();
fullPost.push(description);
link.push(url);
anchorID = "btn" + i.toString();
$(HTML1 + anchorID + HTML5 + title + HTML2 + HTML3 + pubDate + HTML4).appendTo(PAGINATION);
i = i + 1;
});
for (var j = 0; j < fullPost.length; j++) {
btn = "#btn" + j.toString();
selector = $(btn);
$(document).on("click", selector, function() {
document.getElementById('entry').innerHTML = fullPost[j];
});
}
PAGINATION.listview("refresh");
}
});
}
It is the infamous for loop issue.
for (var j = 0; j < fullPost.length; j++) {
(function(j) {
var btn = "#btn" + j;
$(document).on("click", btn, function() {
document.getElementById('entry').innerHTML = fullPost[j];
});
}(j));
}

Categories