Reputation: 393
The following error TypeError: $(…).attr(…) is undefined is occuring on this line of code:
$('iframe').each(function(index,item) {
if($(item).attr('src').match(/(https?:)?\/\/www\.youtube\.com/)) {
Why can't I call the .attr()
method in this situation?
The whole function:
$(document).ready(function() {
if(typeof YOUTUBE_VIDEO_MARGIN == 'undefined') {
YOUTUBE_VIDEO_MARGIN=5;
}
$('iframe').each(function(index,item) {
if($(item).attr('src').match(/(https?:)?\/\/www\.youtube\.com/)) {
var w=$(item).attr('width');
var h=$(item).attr('height');
var ar = h/w*100;
ar=ar.toFixed(2);
//Style iframe
$(item).css('position','absolute');
$(item).css('top','0');
$(item).css('left','0');
$(item).css('width','100%');
$(item).css('height','100%');
$(item).css('max-width',w+'px');
$(item).css('max-height', h+'px');
$(item).wrap('<div style="max-width:'+w+'px;margin:0 auto; padding:'+YOUTUBE_VIDEO_MARGIN+'px;" />');
$(item).wrap('<div style="position: relative;padding-bottom: '+ar+'%; height: 0; overflow: hidden;" />');
}
});
});
And the HTML which contains the src
attribute
<iframe class="videoborder" width="680" height="382" frameborder="0"
allowfullscreen="" src="//www.youtube.com/embed/2qOYDpF24cs?rel=0&controls=0&
showinfo=0" style="position: absolute; top: 0px; left: 0px; width: 100%;
height: 100%; max-width: 680px; max-height: 382px;">
Upvotes: 2
Views: 4773
Reputation: 15875
Use prop()
instead of attr()
. There can be other iframes
in your page has no src
attribute. So using attr()
you get undefined
for $(item).prop('src')
if item have no attribute src
. Hence the error.
$(item).prop('src');
Your code
$(document).ready(function() {
if(typeof YOUTUBE_VIDEO_MARGIN == 'undefined') {
YOUTUBE_VIDEO_MARGIN=5;
}
$('iframe').each(function(index,item) {
if($(item).prop('src').match(/(https?:)?\/\/www\.youtube\.com/)) {
var w=$(item).attr('width');
var h=$(item).attr('height');
var ar = h/w*100;
ar=ar.toFixed(2);
//Style iframe
$(item).css('position','absolute');
$(item).css('top','0');
$(item).css('left','0');
$(item).css('width','100%');
$(item).css('height','100%');
$(item).css('max-width',w+'px');
$(item).css('max-height', h+'px');
$(item).wrap('<div style="max-width:'+w+'px;margin:0 auto; padding:'+YOUTUBE_VIDEO_MARGIN+'px;" />');
$(item).wrap('<div style="position: relative;padding-bottom: '+ar+'%; height: 0; overflow: hidden;" />');
}
});
});
Upvotes: 2