Won't Iterate Over Array In jQuery - javascript

So I can get all of the images I want into an array and pass them to $image. However when I try to loop over that array it just keeps alerting the same item 3 times.
The code I'm having trouble with.
getItem : function($image){
console.log($image)
console.log(jQuery.type($image))
var setup ='<img src="' + $($image).attr('href') + '" title="' + $($image).attr('title') + '"/>';
$.each($image, function(i){
alert( setup);
});
}
The HTML
<a href="images/slideshow/1-GW.PhillipBarnhart.ReverendMemory.jpg" title="Phillip Barnhart as:
Reverend Memory - a clergyman who stands for decorum and truth." rel="slideshow"><img src="images/view-slideshow.jpg" width="490" height="352" alt="View Slideshow"></a>
<a rel="slideshow" href="images/slideshow/2-GW.BethBrooks.POLLYTODD.jpg">fff</a>
<a rel="slideshow" href="images/slideshow/3-GW.NickHale.NOSTALGIA.jpg">test</a>
The whole script or if you like jsFiddle here is a link. http://jsfiddle.net/h3az4/
var slideShow = {
config : {
wrapper : 'body',
container : 'div',
anchor : 'a[rel="slideshow"]'
},
init : function(config) {
$.extend(slideShow.config, config);
$(slideShow.config.anchor).hide();
$(slideShow.config.wrapper).find(slideShow.config.anchor)
.eq(0)
.show()
.click(function(e){
e.preventDefault();
slideShow.getItem($(slideShow.config.anchor));
});
},
getItem : function($image){
console.log($image)
console.log(jQuery.type($image))
var setup ='<img src="' + $($image).attr('href') + '" title="' + $($image).attr('title') + '"/>';
$.each($image, function(i){
alert( setup);
});
},
createTumbnail : function($image){
}
};
$(document).ready(function() {
slideShow.init();
});

Your using the $.each loop wrong.
Your first problem is that $image.attr("x") will get the attr of the first element in the list if $image is a list. What you want is either $($image[i]) or using .get
The second issue is declaring var setup outside the loop. Which means its declared and used once rather then 3 times (since you have 3 items).
$.each($image, function(i){
var setup ='<img src="' + $(this).attr('href') + '" title="' +
$(this).attr('title') + '"/>';
alert( setup);
});
When your using $.each the this object in the function will refer to each object in the array in turn. In this case this is a DOM object so you want to use $(this) to get the jQuery image object.
Look here for a working example http://jsfiddle.net/Raynos/h3az4/3/

I assume $image is an array since you are looping through it. if that's the case, you want something similar to this...
$.each($image, function(i){
var setup ='<img src="' + i.attr('href') + '" title="' + i.attr('title') + '"/>';
alert( setup);
});

check my solution at http://jsfiddle.net/h3az4/5/
allows endless loop of your slideshow, imo you've overcomplicated it a bit and made few conceptual errors as #Dutchie432 pointed
hope this will help as well,
Tom

You can accomplish what you seem to want using map()(docs) .
getItem : function($image){
$image.map( function(i,val){
return $('<img src="' + this.href + '" title="' +this.title + '"/>')[0];
}).appendTo(slideShow.config.wrapper);
},
This will create a new jQuery object that contains the new <img> elements, then will appendTo()(docs) the slideShow.config.wrapper selector.
No need for the intermediate setup variable.
Or maybe a little nicer like this using the properties object argument:
getItem : function($image){
$image.map( function(i,val){
return $('<img>', { src:this.href, title:this.title })[0];
}).appendTo(slideShow.config.wrapper);
},

Related

Replacing <img> tags with links to their content jquery

As the title says, I am having some issues converting images to links using jquery. My code right now is:
var all_img = $(".message .content").find("img");
$.each(all_img, function (index, value) {
var src = value.src;
value.replaceWith($("<a href='" + src +"'>Image " + index+1 + "</a>"));
});
Which results in the images being replaced with [object Object]. I have also tried:
$.each(all_img, function (index, value) {
var src = value.src;
value.replaceWith("<a href='" + src +"'>Image " + index+1 + "</a>");
});
Which results in the html I am trying to insert going in as plain unclickable text. Am I misunderstanding how .replaceWith() works?
You couldn't call the jQuery .replaceWith() method on value, you need to use a jQuery object, to target the current img in every iteration you need to use $(this) like :
all_img.each(function (index, value) {
var src = value.src;
$(this).replaceWith("<a href='" + src +"'>Image " + index+1 + "</a>");
});
I think it is better to create a new element and remove/hide the img:
$('.turnInAnchor').click(function(e){
$('img').each(function(index, el) {
$('body')
.append("<a href='"+el.src+"' target='_blank'>Image "+index+"</a>");
el.remove();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="turnInAnchor">Turn in anchor</button>
<img src="https://upload.wikimedia.org/wikipedia/it/7/75/Twin_Peaks_Episodio_Pilota_Laura_Palmer.png" />

How to pass `this` as an argument in javascript function?

I am using javascript in my project.
I have on HTML table <table id='idDocList'> and I am doing append some html on this table as below code.
But I want to hide respective <tr> when user click on Delete anchor tag.
$("#idDocList").append("<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a onclick=deleteDocument(this,'" + file.name + "')> Delete</a></td></tr>");
How can i do this using Jquery?
The following example does not work
function deleteDocument(CurAnchorTag, fileName) {
$(CurAnchorTag).closest('tr').hide();
}
I don't want to use ID for <a> tag as I have many Documents.
As a quick fix, you can use like this,
$(CurAnchorTag).closest('tr').hide();
Replaced <tr> with tr
You can remove the inline function call with jquery like this way,
$("#idDocList").on("click", "td a", function() {
$(this).closest("tr").hide();
var filename = $(this).closest("td").prev().text();
});
I would suggest you to change your code to:
var newRow = $("<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a href='#'> Delete</a></td></tr>").appendTo("#idDocList");
newRow.find( 'a' ).click( function( e ) {
e.preventDefault();
$( this ).closest('<tr>').hide();
});
You would better use event delegation and get rid of inline onclick handlers all together:
$('#idDocList').on('click', '.btn-delete', function() {
$(this).closest('tr').hide();
// read filename: $(this).data('filename')
});
And use it with HTML (the sting you append):
"<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a class="btn-delete" data-filename='" + file.name + "'>Delete</a></td></tr>"
Note the part:
<a class="btn-delete" data-filename="filename">Delete</a>
you can just use
$(".delete_link").click(function(){$(this).closest('tr').hide();}
Jquery will use the this of which ever element called it. There will be no need for the onclick on the html file.
You recommend you to use event for a class using the jquery
$("#idDocList").append("<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a class='delete_link'> Delete</a></td></tr>");
The code below will add the event and need to execute always after add a "tr", unless you use a delegate to this
$(".delete_link").click(function(){ $(this).closest("tr").hide() });
If you don't want to use a class you can use this
$("#idDocList td > a").click(function(){ $(this).closest("tr").hide() });

Jquery Javascript best way to check elements done appending

I have a list of elements that are dynamically appended after an Ajax call. I am using a plugin that creates a lightbox click event for the anchors dynamically appended. It works fine except sometimes it says that the title is undefined. I realize this is because the plugin gets initiated before the title attribute is completely done appending to the DOM. I know of several ways to do this, but what is the BEST way to check that all these elements are completely appended?
Ajax call is already made and data parsed with this function (colorbox title is the one that evaluates to 'undefined' for only some):
function pageImages(images,_q){
for(var i = 0; i < images.count; i++){
$('#pageImages').append('<div class="pageImageItem"><a href="' + images.data[i]._clickurl + '" title= "' + images.data[i]._title + '">\
<img src="' + images.data[i]._thumbnailUrl + '" alt= "' + images.data[i]._title + '"/>\
</a><div class="hoverInfo"><h2>' + images.data[i]._title + '</h2><p>' + limitCharacters(images.data[i]._clickurl,40) + '</p></div></div>');
}
$(".pageImageItem a").colorbox({maxWidth:'95%', maxHeight:'95%', title: function(){
var url = $(this).attr('href'),
title = $(this).attr('title');
console.log(title);
return '<h2>' + title + '</h2>' + limitCharacters(url,40) + '';
}});
}
And here is a picture of what is happening (anchor highlighted is the element that clearly has a title attribute but is showing undefined in lightbox):
You can wrap the jQuery element find block in a timeout without timevalue. The timeout will wait for all javascript to be finished with all processes. Example:
window.setTimeout(function() {
$(".pageImageItem a").colorbox({maxWidth:'95%', maxHeight:'95%', title: function(){
var url = $(this).attr('href'),
title = $(this).attr('title');
console.log(title);
return '<h2>' + title + '</h2>' + limitCharacters(url,40) + '';
}});
});

Add image and text to list in html from JSON

My use case is to add image and a text dynamically to list. All I have is JSON (extracted from DB as result set). The JSON structure is as mentioned below:
[{"Comment":"Test","FilePath":"\/storage\/sdcard0\/20130725153841.JPEG"},{"Comment":"Image List","FilePath":"\/storage\/sdcard0\/20130725160020.JPEG"}]
So, in my java script, I append this list to a HTML body through the following code:
<script>
$(document).ready(function(e) {
var data = [{"Comment":"Test","FilePath":"\/storage\/sdcard0\/20130725153841.JPEG"},{"Comment":"Image List","FilePath":"\/storage\/sdcard0\/20130725160020.JPEG"}]
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val.Comment + '</li>');
});
$('<ul/>', {
html: items.join('')
}).appendTo('body');
});
</script>
Here, I am trying to bring an image (whose filepath is available in the JSON) to the list. So, the list should contain image (may be a smaller one - I shall use styling for this) and the comment side by side.
Please can someone help?
EDIT:
I tried this: I am building the list runtime.. So, i tried using
before val.comment.. it doesnt seem to work. Any words on this?
In order to show image with each list item you should have to add img tag in your list item. The JS code should be like below:
items.push('<li id="' + key + '"><img src="' + val.FilePath + '" />' + val.Comment + '</li>');
Hope this will help !!
In your items.push add the <img> tag and output the value from your FilePath field:
items.push('<li id="' + key + '">' + val.Comment + '<img src="' + val.FilePath +'" alt="" />' + '</li>');

WHy Doesnt This Javascript Function Work

What I'm trying to do here is make one function that does all the functionality for a custom select element. So I made a function that accepts three parameters which are defined in the function itself (see code below for more detail). I'm trying to accomplish the following: I want the parameters to be the IDs of the various elements (the wrapper div for example), and I want those parameters to be dropped in the function. My Code is below. Thanks so much
function createList(ParentDivID,SelectMenuID,ListMenuID) {
$('#' + ParentDivID + "'");
$('#' + SelectMenuID + "'");
$('#' + ListMenuID + "'");
var options = $("#" + SelectMenuID +'"' ).find("option");
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + "></ul>";
$('#' + ParentDivID + "'").append(ul).end().children('#' + ListMenuID + "'").hide().click(function(){$(ul).slideToggle();});
$("#" + SelectMenuID + '"').hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi);
At a guess, it is probably because your ids don't end in quote characters (which aren't allowed in ids in HTML 4), but you are appending them to the strings you are searching for with jQuery.
You only need to do your selectors like this
$('#' + ParentDivID);
Also you need to stop interchanging 's and "s because it is causing you to miss some closing quotes
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $('#' + SelectMenuID).find('option');
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + '"></ul>';
$('#' + ParentDivID).append(ul).end().children('#' + ListMenuID).hide().click(function(){$(ul).slideToggle();});
$('#' + SelectMenuID).hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi); `
You are messing up all of your string concatenations like:
$('#' + ParentDivID + "'"); should be $('#' + ParentDivID);
It's generally a bit of a mess but I've tried to fix as much as possible.
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $("#" + SelectMenuID).find("option");
var ul = $('<ul>', {id: ListMenuID});
$(options).each(function(){
ul.append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
$('#' + ParentDivID)
.append(ul)
.end()
.children('#' + ListMenuID)
.hide()
.click(function() { ul.slideToggle(); });
$("#" + SelectMenuID).hide();
}
When you call the function, are the three parameters already variables assigned elsewhere in your code? If not, and the are actually the string id attributes, you need to enclose them in quotes.
createList("fancySelectLarge", "selectWalkerType", "walkerTypeLi");
Note: See other valuable responses about the incorrect quoting in $('#' + ParentDivID + "'");
$(ul) is undefined when execution reaches it, because var ul is only declared a few lines later on. You will also need to use document.body.createElement('ul') instead of putting '<ul ...>' in a string.
Also, the lines $('#' + ParentDivID + "'"); don't do anything.
You need to define ul before using it. Also, define it as $('<ul.../>') not just '<ul.../>', so that you can create a jQuery element from that definition.
and you want also try to create the dom element like this
$('<span class="value">') instead of a string value '<span class="value">'.

Categories

Resources