UserX UserX - 2 months ago 18
jQuery Question

PDF documents don't open inside fancybox in mobile devices, so I don't want to open a blank fancybox when I click to open PDFs in these devices

I'm using fancybox to open PDFs. It is working fine on desktop but in mobile and tablets fancybox is not opening PDFs.

And I already did some research and it seems that fancybox definitely does not work on mobile devices.

So I want to know if it is possible to show my "class="fancybox_pdf" in my link only when my website is accessed by a desktop or laptop.

<a class="fancybox_pdf" href="<?php echo BASE.'/documents/pdfs/test1.pdf'?>">Link for pdf</a>


On mobile devices I don't want to open my PDF documents inside fancybox, because it doesn't work, so I also don't want to open a blank fancybox that is what is happening.

Do you know if it is possible do this?

I try with CSS like:

<a class="fancybox_pdf" href="<?php echo BASE.'/documents/pdfs/test1.pdf'?>">Link for pdf</a>
<a href="<?php echo BASE.'/documents/pdfs/test1.pdf'?>">Link for pdf</a>

@media screen and (min-width:981px) { .fancybox_pdf:{display:none;}}


But it doesn't work ok, because I have this media query that gets laptops but also tablets, and I just don't want to open my PDFs inside fancybox on mobile devices, for laptops I want to open because works fine.

This is my link:

<a class="fancybox_pdf" href="<?php echo BASE.'/documents/pdfs/test1.pdf'?>">Link for pdf</a>


And my script:

$(".fancybox_pdf").fancybox({
width: '80%',
height: '80%',
autoSize: false,
type: 'iframe',
iframe: {
preload: false
},
});

JFK JFK
Answer

What I would do is to assign a different class to the link so I can manipulate it independently from the class fancybox_pdf like

<a class="pdf" href="<?php echo BASE.'/documents/pdfs/test1.pdf'?>">Link for pdf</a>

Then validate if you are using a mobile device (along with the screen width optionally) and add or remove the class fancybox_pdf accordingly like :

// detect mobile devices by features
var isTouchSupported = 'ontouchstart' in window,
isTouchSupportedIE10 = navigator.userAgent.match(/Touch/i) != null,
_isMobile = (isTouchSupported || isTouchSupportedIE10) ? true : false;

jQuery(document).ready(function ($) {
    // optionally validates screen width
    if (_isMobile && jQuery(window).innerWidth() < 768) {
        // mobile devices most likely
        if (jQuery(".pdf").hasClass("fancybox_pdf")) {
            jQuery(".pdf").removeClass("fancybox_pdf");
        };
    } else {
        // desktop devices most likely
        if (!jQuery(".pdf").hasClass("fancybox_pdf")) {
            jQuery(".pdf").addClass("fancybox_pdf");
        };
    };
}); // ready

See JSFIDDLE

Note : you still need to keep your script

$(".fancybox_pdf").fancybox();