How can I create an unordered list dynamically using jQuery? I read the image file path (href and src) from an XML file.
<ul>
<li><img id="imageSlide" src="images/test1.png" alt="" /></li>
<li><img id="imageSlide" src="images/test2.png" alt="" /></li>
</ul>
It should create unordered list
based on number of XML nodes in the XML file.
Well, you have to loop over your XML structure and create new LI nodes in the body of that.
var dummyXML = "<foo><dummy>element</dummy><dummy>element</dummy><dummy>element</dummy></foo>";
var HTMLmarkup = '';
$(dummyXML).find('dummy').each(function(){
HTMLmarkup += '<li>' + $(this).text() + '</li>';
});
$('ul').append(HTMLmarkup);
That of course, is just a dummy example. Infact you should consider to use more sophisticated XML traversal systems like XPath (depending on how big your XML file is).
$('ul li').text(function(index) {
return '<a href=images/test' +index +'><img id="imageSlide" src="images/test'+index+'.png" alt="" /></a>';
});
Related
I am creating a portfolio section of a website which utilizes Flickr's REST api. The list of portfolio items, however, is generated dynamically by this code:
$.ajax({
url: "https://api.flickr.com/services/rest?method=flickr.photoSets.getList&user_id=********#N04&format=json&nojsoncallback=1&api_key=***********",
context: document.body
}).done(function(results) {
results.photosets.photoset.map(function(item) {
var imgUrl = "https://farm" + item.farm + ".staticflickr.com/" + item.server + "/" + item.primary + "_" + item.secret + "" + ".jpg";
$(" #portfolio_horizontal_container ").append(
'<div class="portfolio_item interior design"> \
<img src=' + imgUrl + ' alt="" /> \
<div class="port-desc-holder"> \
<div class="port-desc"> \
<div class="grid-item"> \
<h3>Quisque non augue</h3> \
<span>Photography / Web design</span> \
</div> \
</div> \
</div> \
</div>'
)
})
});
I also have another plugin which manages the portfolio interactions and style. However when the DOM elements for the portfolio items get loaded this other plugins just doesn't work, thus the functionality it applies to the portfolio is non existent. I have tried and tried to solve this with no success. Any thoughs?
The code that attaches event handlers to your DOM elements will need to be re-run whenever new elements are added to the page.
In the same function as above, you'll need to re-invoke the plugin so that it will be aware of the new structure.
If I understood your problem, you could create a function which create the event and call it in the ajax done:
function bindEvent(id){
//initialize the plugin for the given id
}
then you can call bindEvent, after the append inside the ajax.done using the id of the newly inserted html.
or
If it's an event that you want to bind you can use
$('body').on('click', 'my-dinamic-id', function(){...})
I want to get all images src from class '.poi-reviews .poi-review'
however my code is returning only the first image src, always the same first!
what is wrong with my code ?
here it is :
jQuery('.poi-reviews .poi-review').each(function( ) {
var fotos = jQuery('.poi-reviews .author-photo-canvas img').attr('src');
var nome = jQuery('.poi-reviews .review-author-name a').text();
var divImage = "<img id="+nome+" alt="+nome+" height='150 'width='150' src="+ fotos +">" ;
inicio.after(divImage);
});
In jQuery, .each() takes the DOM selection you have made with $("#selection") and iterates over it.
The easiest way to approach this is to have a results array and to push the images' src attributes to it:
JavaScript
var results = [];
$("div > img").each(function () { // selects all img under a div tag and loops through
results.push($(this).attr("src")); // pushes the src attribute of $(this), aka the img,
}) // to the results array
$("#results").text(results.join(", "));
// could also console.log() the results;
// I appended to the DOM so you could easily see it on the fiddle
HTML
<p id="results"></p>
<div>
<img src="http://placekitten.com/200/300" />
<img src="http://placekitten.com/200/200" />
<img src="http://placekitten.com/300/300" />
<img src="http://placekitten.com/300/200" />
</div>
fiddle
That is because there are more than one element so, the attr() call will return the value of only the first element.
You need this:
var fotos = jQuery('.poi-reviews .author-photo-canvas img').map(function() {
return this.src;
}).get();
Now, fotos is a an Array containing the urls. Do what you want with them.
Have a series of images, have a variable with img URL.
Now i like to find which HTML element has that img URL as src and want to add a class to it
HTML Code
<ul id='carousel_ul'>
<li><img src="images/thumbnails/image1.jpg" /></li>
<li><img src="images/thumbnails/image2.jpg" /></li>
<li><img src="images/thumbnails/image3.jpg" /></li>
</ul>
Jquery Code
temp = images/thumbnails/image2.jpg
$("#carousel_ul").find(temp)
Trying to do the above, it is returning me an error
Error: Syntax error, unrecognized expression: images/thumbnails/image2.jpg
Thanks in advance
You may use an attribute selector :
var temp = "images/thumbnails/image2.jpg";
var $elements = $('#carousel_ul img[src="'+temp+'"]')
or filter :
var $elements = $('#carousel_ul img').filter(function(){
return this.src==temp;
});
I have the following function:
function displayResults(Items) {
$("#result").text("");
$("#result").append('<div class="car-offers">');
$("#result").append('<div class="purple"></div>');
$("#result").append('<img src="images/caroffer.jpg" alt="" title="" width="213" height="117" />');
$("#result").append('<h3>titleeee</h3>'); // ' + Items[i].Title + '
$("#result").append('<span>Year: 2003</span>');
$("#result").append('<span>Milage: 172,000 Km</span>');
$("#result").append('<span class="price">53,000 QR</span>');
$("#result").append('Link');
$("#result").append('</div>');
$("#result").append('<div class="car-offers">');
$("#result").append('<div class="purple"></div>');
$("#result").append('<img src="images/caroffer.jpg" alt="" title="" width="213" height="117" />');
$("#result").append('<h3>titlee22</h3>'); // ' + Items[i].Title + '
$("#result").append('<span>Year: 2003</span>');
$("#result").append('<span>Milage: 172,000 Km</span>');
$("#result").append('<span class="price">53,000 QR</span>');
$("#result").append('Link');
$("#result").append('</div>');
}
my problem is that at run-time the html is being displayed like: <div class="car-offers"></div> so all the page is being messed up
You cannot append incomplete fragments of HTML with .append(). Unlike document.write, jQuery's .append() method parses the passed string into elements before appending them to the DOM.
So when you do:
$("#result").append('<div class="car-offers">');
jQuery parses the given string into a div element and assigns the car-offers value to its className property, then appends the newly created element to the #result element.
Appending the whole HTML string in a single operation will fix that, so jQuery knows how to parse the given string correctly.
Personally, I wouldn't suggest putting that much HTML inside of a JS file. You can consider putting that inside of a div with display:none then simply call .show() on it. Or have it initially in the page, .detach() it storing in a variable and .append() it back when necessary.
You can use a array with join to solve this
function displayResults(Items) {
$("#result").text("");
var array = [];
array.push('<div class="car-offers">');
array.push('<div class="purple"></div>');
array
.push('<img src="images/caroffer.jpg" alt="" title="" width="213" height="117" />');
array.push('<h3>titleeee</h3>'); // ' + Items[i].Title + '
array.push('<span>Year: 2003</span>');
array.push('<span>Milage: 172,000 Km</span>');
array.push('<span class="price">53,000 QR</span>');
array.push('Link');
array.push('</div>');
array.push('<div class="car-offers">');
array.push('<div class="purple"></div>');
array
.push('<img src="images/caroffer.jpg" alt="" title="" width="213" height="117" />');
array.push('<h3>titlee22</h3>'); // ' + Items[i].Title + '
array.push('<span>Year: 2003</span>');
array.push('<span>Milage: 172,000 Km</span>');
array.push('<span class="price">53,000 QR</span>');
array.push('Link');
array.push('</div>');
$("#result").text(array.join(''));
}
This is an issue I've just come across too. An option is to create the div containers first in a loop then populate them after as you require:
for(var i = 0; i < 12; i++){
$(el).append('<li class="scene-block"></li>'); // create container li tags
//fill empty li tags with content
for(var j = 0; j < 2; j++){
$(el).find('li').last().append('<div class="select-a-scene-bg"></div>');
}
}
I'm on a .NET 4.0 environment using jQuery and Visual Studio to write everything, but neither of these facts should matter that much except how to populate the XML data.
I'm starting out with this script which has a lot of markup in it. My task is to get the markup out of the script and to populate the the XML data into the markup in its proper place. I'm trying to keep the presentation and behavior layers as separate as possible by doing this.
function addIcons(IconType) {
var li ="";
var onclickMethod="";
for (var item in hashObject) {
var thumbNail = item.split("_");
if (thumbNail[0] == IconType +"ThumbNail") {
var imagePath = baseUrlThumbNailImages + hashObject[item];
li = li + "<li onclick=IconClick('" + IconType +"',"+ thumbNail[1] + ")><img src=\"" + imagePath + "\" alt=\"" + IconType + " shape\"></li>\n";
}
}
$("#" + IconType + "ThumbNailShapes").append(li);
}
Here's example markup I want as final result:
<ul>
<li onclick="IconClick('Item',1)">
<img src="/images/image_1.png" alt="Item shape" />
</li>
<li onclick="IconClick('Item',2)">
<img src="/images/image_2.png" alt="Item shape" />
</li>
<li onclick="IconClick('Item',3)">
<img src="/images/image_3.png" alt="Item shape" />
</li>
</ul>
While I know I need to take out the line of code that starts li = li + ..., I'm also not familiar enough with OOP to understand how to write a for loop to populate the markup.
So there's two factors that I am not sure how to code:
The blank markup - does the markup need variables to populate it or should javascript do this automatically?
The javascript - I don't know how to recode the javascript to find each list item and image tag to populate the various data.
Do I need the markup to be blank like this, where all the variable data is not there yet?
<ul id="IconThumbnailShapes">
<li onclick="">
<img src="" alt="shape" />
</li>
<li onclick="">
<img src="" alt="shape" />
</li>
<li onclick="">
<img src="" alt="shape" />
</li>
</ul>
I appreciate the insight and help.
I would do it like this.
Let's suppose we have a container DIV#foo where all this code has to reside.
<div id="foo"></div>
We then do this:
$(function() {
// DOM ready
$('#foo').on('click', '#IconThumbnailShapes li', function() {
// Do whatever you have to do with icon
// Second argument there '#IconThu... li' means the event will be trigerred
// as soon as you add your icons, but they don't have to be there
// right now.
});
function addIcons(iconType) {
var s = '<ul id="IconThumbnailShapes">'
var l = '<li><img src="$SRC" alt="$ICON shape" /></li>'
var data = [{...}, {...}, {...}];
var len = data.length;
var datum;
for (var i = len; i; i--) {
datum = data[len - i];
s += l.replace('$SRC', datum.src).replace('$ICON', iconType);
}
s += '</ul>';
$('#foo').html(s);
}
});
So, we do it like this, because we don't want to fire jQuery stuff in the for loop. That kills performance. Instead we set up a deferred even handler for click on the conainer DIV#foo, and we shove the whole bunch of markup into the container as a string.