GithubHelp home page GithubHelp logo

marekdedic / imagelightbox Goto Github PK

View Code? Open in Web Editor NEW
127.0 8.0 37.0 116.08 MB

Image Lightbox, Responsive and Touch‑friendly

Home Page: https://marekdedic.github.io/imagelightbox/

License: MIT License

CSS 8.61% JavaScript 10.28% TypeScript 64.14% HTML 16.97%
javascript image-lightbox jquery

imagelightbox's Introduction

imagelightbox

NPM Version GitHub Actions Workflow Status Coveralls NPM Downloads NPM License RelativeCI native bundle RelativeCI jquery bundle

Image Lightbox, Responsive and Touch‑friendly.

This is a fork of the lightbox plugin created by Osvaldas Valutis.

See most of the available options at the Demo Page

Requirements and Browser support

  • All major desktop browsers and versions as well as mobile browsers on Android and iOS.

How to install

$ npm install --save imagelightbox

After that include the dist/imagelightbox.css and dist/imagelightbox.umd.cjs files. Alternatively, you can use the dist/imagelightbox.js file if you are using ES6 modules.

If you prefer to use jQuery, there are also jQuery wrappers available in dist/imagelightbox.jquery.umd.cjs or dist/imagelightbox.jquery.js. These wrappers mostly adapt the interface of the library to work with jQuery types and emit jQuery events. These are here mostly for legacy reasons and their use is discouraged.

How to use

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="node_modules/imagelightbox/dist/imagelightbox.css">
        <script src="node_modules/imagelightbox/dist/imagelightbox.umd.cjs"></script>
        <script>
            new Imagelightbox(
                document.querySelectorAll('a[data-imagelightbox="xyz"]'),
            )
        </script>
    </head>
    <body>
        <a data-imagelightbox="xyz" href="image_1.jpg">
            <img src="thumbnail_1.jpg" alt="Caption 1"/>
        </a>
        <a data-imagelightbox="xyz" href="image_2.jpg">
            <img src="thumbnail_2.jpg" alt="Caption 2"/>
        </a>
    </body>
</html>

Options

You can pass an object with options to the ImageLightbox constructor as a second argument. The available options are:

Option Type Default value Description
activity boolean false Whether to show an activity indicator when loading or changing the images
allowedTypes string png|jpg|jpeg|gif A list of allowed file types. Use an empty string to allow any type.
animationSpeed number 250 The duration (in milliseconds) of all animations
arrows boolean false Whether to show navigation arrows
button boolean false Whether to show a close button
caption boolean false Whether to show image captions, if they are available
enableKeyboard boolean true Whether to enable keyboard navigation (previous/next with arrows, Escape to exit, Enter for fullscreen)
history boolean false Whether to save the current lightbox state to the browser history and add perma-linkable URLs
fullscreen boolean false Whether to enable the availability to show the lightbox in fullscreen mode
gutter number 10 The minimum amount of free space (in % relative to the window size) to always keep around the image
navigation boolean false Whether to show a navigation (panel with clickable dots for each image)
overlay boolean false Whether to show a dark page overlay under the image
preloadNext boolean true Whether to start preloading the next image upon navigation
quitOnEnd boolean false Whether to close the lightbox when navigation past the last image. Alternatively, the lightbox just loops to the first image.
quitOnImgClick boolean false Whether to close the lightbox when the image is clicked. Alternatively, the previous/next image is shown based on the position of the click. Never quits on touch devices.
quitOnDocClick boolean true Whether to close the lightbox when clicking outside of the image.
quitOnEscKey boolean true Whether to close the lightbox when the Escape key is pressed. Requires the enableKeyboard option to be true.

Opening the lightbox with a JavaScript call

The lightbox can be opened with the open() method call.

Example:
const gallery = new ImageLightbox(
    document.querySelectorAll('a[data-imagelightbox="xyz"]'),
);
gallery.open();
Example: Open specific image
const gallery = new ImageLightbox(
    document.querySelectorAll('a[data-imagelightbox="xyz"]'),
);
gallery.open(
    document.querySelectorAll('a[href="image_1.jpg"]').item(0),
);

Adding captions to lightbox

To use captions, add an "ilb2-caption" data-attribute to the element, or as a fallback value, the alt attribute of the thumbnail image is used.

<a data-imagelightbox="xyz" data-ilb2-caption="caption text" href="image.jpg">
    <img src="thumbnail.jpg" alt="Fallback caption" />
</a>

Fullscreen

To enable fullscreen, set the fullscreen option to true. The user can then launch the fullscreen view by pressing the Enter key.

Video

Videos can be displayed in lightbox by including a data-ilb2-video attribute in the link. This attribute should contain a JSON-encoded list of parameters as they would be in an HTML5 video tag. For multiple video sources, the sources field can be added, containing a list of similarily encoded HTML5 source tags.

<a data-imagelightbox="xyz" data-ilb2-video='{"controls": "controls", "autoplay": "autoplay", "sources": [{"src": "images/video.m4v", "type": "video/mp4"}], "width": 1920, "height": 1080}'>
    <img src="images/video-thumb.jpg">
</a>

Custom events

The lightbox dispatches custom events upon opening, closing, image loading, and when either the next or previous image is requested (beware that these are not dispatched when the image is changed in other ways, such as the navigation panel). These events are, respectively, ilb:start, ilb:quit, ilb:loaded, ilb:next, and ilb:previous.

Usage example:

document.addEventListener("ilb:start", (e) => {
    console.log("The lightbox was started with element: ");
    console.log(e.target);
});
document.addEventListener("ilb:quit", () => {
    console.log("The lightbox was closed.");
});
document.addEventListener("ilb:loaded", () => {
    console.log("A new image was loaded");
});
document.addEventListener("ilb:previous", (e) => {
    console.log("Previous image: ");
    console.log(e.target);
});
document.addEventListener("ilb:next", (e) => {
    console.log("Next image: ");
    console.log(e.target);
});

Using multiple lighboxes

Imagelightbox supports multiple independent image sets on the same page, each initialized indepently.

For example:

<a data-imagelightbox="a" href="image_1.jpg">
    <img src="thumbnail_1.jpg" alt="caption"/>
</a>
<a data-imagelightbox="a" href="image_2.jpg">
    <img src="thumbnail_2.jpg" alt="caption"/>
</a>

<a data-imagelightbox="b" href="image_3.jpg">
    <img src="thumbnail_3.jpg" alt="caption"/>
</a>
<a data-imagelightbox="b" href="image_4.jpg">
    <img src="thumbnail_4.jpg" alt="caption"/>
</a>

When the user clicks any of the thumbnails with a data-imagelightbox value of "a", only those images will appear in the lightbox. The same is true when clicking an image with data-imagelightbox value of "b" and any other.

Adding images dynamically to lightbox

More images can be added to the lightbox after it has been initialized.

Example:
const lightbox = new Imagelightbox(
    document.querySelectorAll('a[data-imagelightbox="xyz"]'),
)
const newAnchor = document.createElement("a");
newAnchor.dataset.imagelightbox = "xyz";
newAnchor.href = "images/demo4.jpg";

const newImg = document.createElement("img");
newImg.src = "images/thumb4.jpg";
newAnchor.appendChild(newImg);

lightbox.addImages([newAnchor]);

Permalinks & History

When history is enabled, upon clicking on an image, the query field imageLightboxIndex=X is added to the URL, where X is the index of the currently opened image. This means that such an URL can be copied and used as a permanent link to that particular image. When somebody opens the URL, the lightbox will be open on the image in question. This also works with multiple sets, where an aditional query field imageLightboxSet=Y is used to distinguish between the sets in one page.

In some cases, this could lead to a different image being opened, for example if new images have been added to the set, or if the order of the images has changed. To solve this issue, whenever the HTML attribute data-ilb2-id=X is present in the image tag, this value is used instead of the image index (this means this id has to be different for each image and mustn't change over time to keep links working).

Example:
<a href="image1.jpg" data-imagelightbox="images" data-ilb2-id="img1">
    <img src="thumb1.jpg">
</a>
<a href="image2.jpg" data-imagelightbox="images" data-ilb2-id="img2">
    <img src="thumb2.jpg">
</a>
<a href="image3.jpg" data-imagelightbox="images" data-ilb2-id="img3">
    <img src="thumb3.jpg">
</a>

<script>
    new Imagelightbox(
        document.querySelectorAll('a[data-imagelightbox="images"]'),
        {
            history: true,
        },
    )
</script>

If you want a dynamically add images after the page has loaded and still support direct links to them, you have to call lightbox.openHistory() manually on the lightbox object yourself after adding the image.

Changelog

You can find all notable changes to this project in the GitHub releases.

See also

Used by https://wordpress.org/plugins/skaut-google-drive-gallery/

imagelightbox's People

Contributors

art4 avatar balapal avatar cioddi avatar dependabot-preview[bot] avatar dependabot[bot] avatar github-actions[bot] avatar greenkeeper[bot] avatar greenkeeperio-bot avatar hanwiz avatar marekdedic avatar paxperscientiam avatar rejas avatar rwillrich avatar salon-sai avatar snyk-bot avatar tigerhawkvok avatar vasilyman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

imagelightbox's Issues

Roadmap?

hey @rejas @GenaBitu , etc,

I'm resurrecting this thread in attempt to aggregate all the ideas that we've been bouncing around. My thinking is that if we can put together a sort of "roadmap", it'll ensure that development of imagelightbox moves forward in a coherent fashion.

If you guys are down, just tell me what to add/tweak. Maybe it would be a good idea to finish this first before merging non-critical stuff?

What is a "lightbox"?
In short, it's a modal window with the background content "darkened" or obscured.

Broad questions to answer, according to Nielson Norman Group.

PRINCIPLES

  • Who is the target audience?
    Developers with graphical content to share, allowing for supplemental text
  • What action is the user supposed to take?
    ...
  • When will the overlay appear, and will it be an interruption?
    imagelightbox is not built to annoy.
  • Where will the overlay appear on the page?
    ...

Scope:

GOALS

Features

  • matrix (static)
  • matrix (rubiks)

Structure/logic: see PR #163 #184

  • Adopt "dependency injection" concept. For instance, inferring the state of the image from any give point in the code is a nightmare due to the image variable's large scope.
  • Improve handling of image loading. #22 #178 #176

Performance

  • Make better.

Accessibility

  • Adheres to ...

i18n PR ; issue #129

  • Follows semiotic standards / best practices.

Compatibility see #183 #180

  • [ ]

Maintainability

  • Auto document #106

An in-range update of gulp-clean-css is breaking the build 🚨

Version 3.1.0 of gulp-clean-css just got published.

Branch Build failing 🚨
Dependency gulp-clean-css
Current Version 3.0.4
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As gulp-clean-css is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Release Notes 3.1.0

Revisit rebasing issues. Update deps (4.1.0)

Commits

The new version differs by 1 commits0.

  • 9ca15f2 attempt to fix rebasing, update deps

false

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Add less/sass support

It would be nice to also have less and/or sass version of the stylesheet for those who work primarly with preprocessors rather than plain css.

The imagelightbox is used in the opera

I use the imagelightbox in different browsers and find the opera (mobile) not supporting quitOnDocClick. After being clicked the overlay, view will start the image which you click behind overlay. I try to test the demo in the opera(mobile) . The demo has the same problem.

Including demo functions in the source?

Hi @rejas ,

Have you given any thought into including your demo functions in the source file?

I think it would simplify things if you were to fold in captionOn(), captionOff(), navigationOn(), navigationOff, and etc into the source files.

What do you think?

HTML5 srcset and sizes

'allo!

I've added support for the above (and generic target to image-tag mapping) as on https://github.com/Buntix/imagelightbox and https://github.com/Buntix/imagelightbox#passing-parameters-to-lightbox-images Also added back the link filtering via the 'allowedTypes' config option as it became a lot simpler post the above transform.

All things being equal, it's running at: http://www.deverecars.com/vehicles.php (using a https://github.com/thephpleague/glide backend).

I've merged in yesterday's upstream changes but not tested. If it seems like something worth adding I can add a pull request :)

user-level interaction with multiple sets (matrix)

What do you think, @rejas, of allowing for the creation of a 2D imageLightbox? Basically, there is some trigger to open two or more imageLightbox sets. While the 'left' and 'right' actions will continue to work as they do now, 'up' and 'down' actions would switch user-level interaction to another imageLightbox.

This basically piggybacks off of #92
EDIT: Also piggy backs off of #91

Some thoughts on further improvements

Hey @rejas

I don't think captions should fade away when switching from image to the next: it seems like an unnecessary distraction. If instead the caption box remained when changing over images, I think it would be better.

On the UX side of things, the ability to slide over to the next image via trackpad or mobile screen, would be great. Is this something you've thought about? If interested, I could probably lend a hand.

EDIT:
I forgot to mention another feature that I think would be pretty darn awesome. For large screens, particularly in portrait orientation, it could be very useful to have option to show two lightbox galleries simultaneously.

EDIT 2:
Deeplinking

Add DeepLinking functionality

From "paxperscientiam": I actually started tinkering with deeplinking (linking to image X so that the imagebox opens directly with it) and it's going well so far. I hope to put up a rough draft soon. You can expect something on this end.

Possibility to add 'onLoadEnd' hook (when popup has completely loaded.)

Possibility to add 'onLoadEnd' hook similar to original repo.

I ran into the issue where I wanted to obtain width, height and position attributes of popup element ('#archive_lightbox') in order to add an overlay. Although when using 'loaded.ilb2', the element had not been created yet, leading to an undefined.

Multiple Instances?

I cannot safely "destroy" the plugin if i am trying to use it and it gets called multiple times? It will append "n" number of plugins depending on how many times it has been initialised. Can we make it that only one instance of the plugin can run for any single selector?

e.g.
var selectorF = 'a[data-imagelightbox="f"]';
var instanceF = $(selectorF).imageLightbox();

Calling this twice would only setup one instance...maybe destory the previous one would be useful or have / follow a "destroy" model ?

thanks for the fork :)

Minor interesting bug

Hi there @rejas

While working on the fork, I discovered an interesting bug that causes "alt" values to be recycled when reusing image links despite unique alt values. To clarify, I'm referring to the "href" values from "" and not the "src" values from "".

Here's a minimal example:

<div class="column" >
      <a href="http://placehold.it/500x300" data-imagelightbox="LD">
       <img src="http://placehold.it/500x300" class="center-light thumbnail" alt="Hi" />
      </a>
     </div>
     <div class="column" >
      <a href="http://placehold.it/500x300" data-imagelightbox="LD">
       <img src="http://placehold.it/500x300" class="center-light thumbnail" alt="Bye" />
      </a>
     </div>
 <div class="column" >
      <a href="http://placehold.it/500x300" data-imagelightbox="LD">
       <img src="http://placehold.it/500x300" class="center-light thumbnail" alt="Hello" />
      </a>
     </div>

As you've likely surmised, this bug is relevant to the creation of HTML templates where it is typical to link to the same image file multiple times. I'm assuming it doesn't matter if the image file is server local or remote (as above).

The simple gallery above should -- with captions on and assuming you click on the first image -- display "Hi", "Hi", and "Hello" for each image, respectively.

image load error handler

hey! first, i really like your plugin, thank you for sharing...
i was wondering, if there is any error handling callback in your options.
i tried replacing the src element of the #imagelightbox by a default error image (with the onLoadStart option), but the img#imagelightbox element will not be created if the loading process of the image src fails, right?

i would like to replace the img src of the lightbox image by a default image, if the src cannot be loaded.

Remove fading from captions

From "paxperscientiam": I don't think captions should fade away when switching from image to the next: it seems like an unnecessary distraction. If instead the caption box remained when changing over images, I think it would be better.

How to overlay to Image Lightbox

Firstly, thanks for this awesome plugin.

In your Script Tag (from View Page Source Demo Page) you have defined a variable of OverlayOn, where is appends a div to the body element with the transparent overlay styling applied.

How would I go about activating OverlayOn?

Thanks

AlvSovereign

EDIT: So I have figured out from the JS that I'll need to replace the boolean values for the options onStart, onEnd etc... to true, as the variables are 'bound' to the options (if I'm correct).

I am getting some JS errors from Chrome which I'll need to debug first.

EDIT 2: Solved my issue.

I added the data-lightbox"b" to my anchor tag and made sure the onStart, onEnd etc.. options were on false.

Compatibility with bootstrap

When I include imagelightbox.min.js to my project, the collapse-Button of the Navigation-Bar created with bootstrap does not work anymore. Is this a known issue?

How to contact?

This is unrelated to the project, but how do I contact you? I checked your website, but couldn't find an email.

In case you're on linkedin, here's me.

Sizing does not properly account for caption space

So, by default, I think the caption should not ever overlap the image; as well, there should be minimum margin (spacing between caption and image).

Here is an example that shows a shortcoming on one of the iPhones (one of the narrower ones, I suppose).

portrait
landscape

Altering the resizing math should be no problem as the caption height is fixed, though maybe not. It is possible for captions to be two lines (do we need to worry about that?).

What do you think? Is there an alternative solution that comes to mind?

edit

Come to think of it, methinks the caption height should conform to the image size.

Use CSS to hide links that don't wrap images

It seems that sometimes the default display property for anchor elements can clash with flex stuff. I haven't quite nailed down the specifics. That said, setting anchor elements without dependents to display:none seems like the safer bet.

I will do this.

Mouse click on touchscreen laptop broken

With the default settings the lightbox opens fine on desktop and you can navigate by clicking on the left and right of the image or close by clicking outside the image. However on my laptop which has a touchscreen (perhaps the reason) it opens fine but then does not respond to any mouse input. I must use the touchscreen to get any response from it.

Multiple gallery auto

This is code for unlimited gallerys:

var attrs = {};
var classes = $("a[data-imagelightbox]").map(function(indx, element){  
  var key = $(element).attr("data-imagelightbox");
  attrs[key] = true;
  return attrs;
});
var attrsName = Object.keys(attrs);

attrsName.forEach(function(entry) {
    $( "[data-imagelightbox='"+entry+"']" ).imageLightbox({
        overlay: true
    });
});

it automatically searches attr's data-imagelightbox and sorting by separate albums! =)

feature request: dynamically generated imagelightbox

To extend the dynamic image addition concept, allow for provision of an image directory that can be used for dynamically generating imagelightbox sets. This is where extension filter would come in handy.

This would be for...like... v1.0?

Combining efforts

I have found a few forks/initiatives/repositories based on http://osvaldas.info/image-lightbox-responsive-touch-friendly
Namely:
https://github.com/felipearosemena/imageLightbox
https://github.com/rejas/imagelightbox
https://github.com/mrchimp/imagelightbox
https://github.com/jeremydouglas/imagelightbox

I was wondering if you would be open combining those efforts?
I am raising this topic as a new issue with all of the above repos (not sure if there is any better way getting in touch with the authors).

questions about testing suite

Hi @rejas

I think the testing server is really cool and useful. There are a few minor issues though.

  • Can you set the index page so that it only shows files/dirs meant to be tested? If you check out this screenshot, you'll see that a lot of cruft winds up getting listed.
  • Not sure if this should be handled by you, but is there something you can do so that changes to the dist/ directory do not clog up git diff results?

EDIT

Maybe webroot should just be the docs directory?

Auto document?

I think it would be a good idea to programmatically generate documentation from the comments.

Incorrect nav element counting on some user-agents

This was reported by a client using iOS and Chrome on OSX.

It seems that in certain cases, the nav elements are double counted. This might be related to a counter not being reset or something not being properly destroyed.

Publish on npm?

Any change you could do this? So we can use it in our js stack.

Some of the defaults don't match the readme

Activity, button, caption, navigation and overlay are all true in readme but false in the code.

Also, arrows is missing on the readme.

I'd submit a pull request but I'm in the middle of something right now.

Easy way to disable on small screens?

In my case the thumbnail images of 300px are already filling a phone screen, so the popup function is no advantage and probably a worse user experience.

Lightbox bugs out with captions if any images lack "alt" attribute.

It's all there in the comments, though I'm unsure if it's also caused by an interaction with other functions. Basically, if any image is missing the "alt" attribute, the images will begin to "stack" as you move from one to the next.

EDIT: The above does NOT happen if the image has an empty alt attribute; however, the caption text persists rather than be replaced with an empty caption.

Extend overlay effects?

Extending is more work and probably beyond scope; however, I like the idea of improving the aesthetic of the overlay with a soft blur.

What do you think?

Here's a WIP.

Add swipe/slide/zoom functionality

From "paxperscientiam": On the UX side of things, the ability to slide over to the next image via trackpad or mobile screen, would be great. To this end, I think we want a sliding motion to be equivalent to pressing left/right buttons, correct?"

Correct :-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.