Reputation: 23
Excuse my lack of knowledge, but I'm fairly new to JS. I'm displaying an Instagram feed on a website and need to insert the title attribute of the images to the encasing link to display it as a lightbox caption. My solution works so far, but the problem is, that the title of the first image is inserted into every link instead of just the encasing link.
The script:
function (){
$('#instapics a').lightBox();
jQuery('#instapics a img').each(function () {
$('#instapics a').attr('title', $(this).attr('title'));
});
}
The html:
<div id="instapics">
<a href="#">
<img title="IMG title 1" src="xxx">
</a>
<a href="#">
<img title="IMG title 2" src="xxx">
</a>
...
</div>
This inserts "IMG title 2" into both links. But I need "IMG title 1" on the first, "IMG title 2" on the second, "IMG title 3" on the third and so on. What am I missing?
I'm looking forward to some useful tips.
Upvotes: 1
Views: 179
Reputation: 33870
You can use this code :
$( "#instapics a" ).attr( "title", function() { //Will loop in every a's
return $(this).find('img').attr('title'); //Return img title to change the a title.
});
Upvotes: 0
Reputation: 10994
jQuery('#instapics a img').each(function () {
$(this).parent().attr('title', $(this).attr('title'));
}); // add it to the parent of img which is a
You can also use this.title
instead of jQuery's $(this).attr('title')
.
Upvotes: 4
Reputation: 207501
It is because you are rselecting all of the anchors instead of the one you are currently dealing with.
$('#instapics a').attr(
needs to be
$(this).attr(
and you should probably be using prop()
instead of attr()
Upvotes: 1