Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent setting alt=String("undefined") when the original IMG has no alt #1049

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

jaydansand
Copy link

As mentioned in #871, when using the Image type and the <img> has no alt attribute, Magnific Popup's image.js on line 193 will erroneously replace the image with a new img where alt=String("undefined").

Problem line in Magnific Popup code (image.js:193):
img.alt = item.el.find('img').attr('alt');

Problem description:
As of jQuery version 1.6 (and Magnific Popup requires > 1.6) jQuery.attr() returns undefined if the attribute does not exist. When setting img.alt = undefined, undefined is converted to a String and the actual text "undefined" gets assigned.

Proof of Underlying Problem (in jQuery):

var img = document.createElement('img'), und = jQuery(img).attr('alt');
img.alt = und;
console.log(und, typeof und); // undefined "undefined"
console.log(img.alt, typeof img.alt); // "undefined" "string"

Solution/Fix:
Test item.el.find('img').attr('alt') before assigning img.alt, as done in this PR.

@@ -190,7 +190,11 @@ $.magnificPopup.registerModule('image', {
var img = document.createElement('img');
img.className = 'mfp-img';
if(item.el && item.el.find('img').length) {
img.alt = item.el.find('img').attr('alt');
Copy link

@dpilafian dpilafian Dec 6, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than an if statement with mostly duplicate lines, cleaner to tack on || '':

img.alt = item.el.find('img').attr('alt') || '';

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure! I guess I'm always leery of depending on truthiness in loose-typed languages. Maybe because I'm too accustomed to PHP's terrible string finagling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants