Coder Social home page Coder Social logo

zoom.js's Introduction

zoom.js

An image zooming plugin, as seen on older versions of medium.com. This project is a port of fat/zoom.js but has no jQuery or Bootstrap dependencies.

Version 4 is written in TypeScript, has a new API, includes typings, and has no dependencies.

npm package: https://www.npmjs.com/package/@nishanths/zoom.js

Branches

  • v4: The default branch. It contains code for version 4, which is the current major version.
  • master: Frozen and no longer maintained. The final version on this branch is 3.1.0.

No API backwards compatibility guarantees even within the same major version, so, if necessary, pin an exact version and upgrade manually.

Demo

https://nishanths.github.io/zoom.js

Zoom on an image by clicking on it.

Dismiss the zoom by either clicking again on the image, clicking the overlay around the image, scrolling away, or hitting the esc key.

Usage

Install the package:

npm i @nishanths/zoom.js

Link the src/zoom.css file in your application:

<link href="zoom.css" rel="stylesheet">

Import and use symbols from the package:

import { zoom } from "@nishanths/zoom.js"

The js files in the dist directory are ES modules.

Note that the package.json for the package specifies the module property but not the main property. You may need a module-aware tool to correctly include the package in your bundle. For further reading, see this Stack Overflow answer as a starting point.

Building locally

To build the package locally, clone the repo, then run the following from the root directory:

% make deps
% make build

This should write files into the dist directory.

Documentation

API

// Config is the configuration provided to the zoom function.
export type Config = {
	// padding defines the horizontal space and the vertical space around
	// the zoomed image.
	padding: number

	// paddingNarrow is similar to the padding property, except that it is
	// used if the viewport width is too narrow, such that the use of the
	// larger padding property may produce poor results.
	//
	// paddingNarrow should be <= padding, however this is not validated.
	paddingNarrow: number

	// dismissScrollDelta defines the vertical scrolling threshold at which
	// the zoomed image is dismissed by user interaction. The value is the
	// pixel difference between the original vertical scroll position and
	// the subsequent vertical scroll positions.
	dismissScrollDelta: number

	// dismissTouchDelta defines the vertical touch movement threshold at
	// which the zoomed image is dismissed by user interaction. The value is
	// the pixel difference between the initial vertical touch position and
	// subsequent vertical touch movements.
	dismissTouchDelta: number
}

// zoom zooms the specified image.
//
// The image will not be zoomed if its naturalWidth or naturalHeight property
// is 0 (usually because the values are unavailable).
export function zoom(img: HTMLImageElement, cfg: Config = defaultConfig): void

// dismissZoom programmatically dismisses the presently active zoom. It is a
// no-op if there is no zoom active at the time of the call.
export function dismissZoom(): void

Examples

The following TypeScript program makes all existing <img> elements on the page zoomable. Images are zoomed when they are clicked.

import { zoom } from "@nishanths/zoom.js"

function setup(img: HTMLImageElement) {
	img.classList.add("zoom-cursor") // use "cursor: zoom-in" style on hover
	img.addEventListener("click", () => { zoom(img) })
}

const imgs = [...document.querySelectorAll("img")]
imgs.forEach(img => { setup(img) })

The following TypeScript program customizes only certain properties of a Config, keeping the defaults for the other properties.

import { Config, defaultConfig } from "@nishanths/zoom.js"

const customConfig: Config = {
	...defaultConfig,
	padding: 30,
}

Notes

All CSS class names used by the package are prefixed with zoom-.

Add the class name zoom-cursor to a zoomable <img> element to use an zoom-in cursor instead of the default cursor for the image.

The program appends the DOM node for the overlay element, which appears when an image is zoomed, to the end of document.body.

While an image is zoomed, the program listens for click events on document.body with useCapture set to true, and the handler function calls e.stopPropagation(). This may interfere with other click event handlers on the page. The event listener is removed when the zoom is dismissed.

When an image is zoomed, its transform style is replaced with a new value that is necessary for zooming. The old transform is restored when the zoom is dismissed.

Browser compatibility

Popular web browser versions released after 2016 should be supported by this package. Please read the source code for exact details.

License

The software in this repository is based on the original fat/zoom.js project. The copyright notices and license notices from the original project are present in the LICENSE.original file at the root of this repository.

New source code and modifications in this repository are licensed under an MIT license. See the LICENSE file at the root of the repository.

zoom.js's People

Contributors

nishanths avatar

Stargazers

dong.huo avatar  avatar  avatar Gavin Luo avatar Tobias Röder avatar Blake Watson avatar oeyoews avatar  avatar Shoora avatar 杨祖攀 avatar Mol avatar zhaomeicheng avatar Ryan Rubush avatar Arpit Agrawal avatar  avatar Daniel Wirtz avatar Justin Peacock avatar soger avatar Bryan Smith avatar  avatar Ahmet Abdulrahman . Señor developer avatar Patrick G avatar Daniel Meier avatar  avatar Simon Duff avatar Matt Daniel Brown avatar Dao avatar Sohaib Sherif avatar Ahmed Mansour avatar  avatar pedoc avatar netop://ウエハ avatar Jacky Alciné avatar Joelthorner avatar Baoshuo Ren avatar  avatar  avatar Bohdan Stefaniuk avatar  avatar Aris avatar Kofi Ramos avatar Mr. Abdolhosseini avatar Ramon Meffert avatar Priya Ranjan Dubey avatar  avatar  avatar Sina Khalili avatar Gizmo avatar Dmitry Filippov avatar Zhao avatar Zoran Pesic avatar Andreas Cederholm avatar Max Davitt avatar Programming is fun avatar  avatar BadCat Design avatar Igor Putina avatar  avatar  avatar  avatar TokunagaX avatar cheng avatar  avatar Lee Peterson avatar Jagroop Singh avatar Dinh Quoc Han avatar Christopher Geary avatar Vincent Talbot avatar Alan Bondarchuk avatar Jack McDade avatar Rodrigo Fernandes avatar Waldemir Francisco avatar Julaine Scott avatar gaoryrt avatar Janssens Gaëtan avatar  avatar haigeno1 avatar  avatar BeatBastic avatar İlker Kurtel avatar Grigorii Horos avatar  avatar Hiroaki Shuto avatar Md. Jamal Uddin avatar Anindya Sundar Paul avatar  avatar  avatar  avatar Ruslan Namanov avatar paintedbicycle avatar Hipponensis avatar Emyr Thomas avatar ZhangZhiheng avatar Maple avatar Wu.East avatar  avatar s.u avatar Anton Panov avatar unipota avatar Alex Pryshchepa avatar

Watchers

Patrick LEFEVRE avatar  avatar Christian Hochfilzer avatar Francesco Fienga avatar Mike Sozanski avatar Alexandru Năstase avatar Jay OWL Farand avatar James Cloos avatar Krister Kari avatar David Bruchmann avatar Vitor Casadei avatar Jon Swanson avatar jQueryScript avatar rene404 avatar Alex Leko avatar  avatar  avatar  avatar Ivar Johnson avatar Sylwia Calka avatar Nikola Kostov avatar  avatar  avatar

zoom.js's Issues

Adding image description

If you could please add a data-description or like field to describe and show the users what the image is about. Thanks

Copyright

If this is ported from @fat, shouldn't you include his copyright line in your MIT license?

Build UMD version

It would be easier to work with webpack and single page app, and init it manually:

import zoom from 'zoom.js'

zoom.setup(document.querySelectorAll('.my-els'))

Enhance to function as a lightbox

I like the simplicity of this library and was considering using it. But it is not the same technique that medium uses to zoom images. They use the lightbox technique which requires 2 versions of the same image; a scaled-down version which is loaded by default and zoomed to the full-size version that is loaded upon click. Like this:

    <a href="full.jpg">
        <img src="thumb.jpg" />
    </a>

In fact, a webpage using zoom.js will be penalized by google's search ranking algorithm for inefficiently formatting images.

https://developers.google.com/speed/pagespeed/insights/?url=https://nishanths.github.io/zoom.js/

Do you have plans to further develop this? I think it would be great it if had the ability to zoom from a scaled-down image to a full-size image. The API could stay the same:

    zoom.setup(elem);

Where elem is either a normal img element, or it could be an anchor element wrapping an img element, as above. If an img element, it functions exactly as it does now. If an anchor element, it functions as a lightbox.

CSS opacity transition onClose is missing

to get the opacity transition to work at the end, it should read smtg like:

.zoom-overlay {
  opacity: 0;
  -webkit-transition:      opacity 300ms ease-in-out;
       -o-transition:      opacity 300ms ease-in-out;
          transition:      opacity 300ms ease-in-out;
}
.zoom-overlay-open .zoom-overlay {
  opacity: 1;
}
.zoom-overlay-transitioning .zoom-overlay {
  opacity: 0;
}

.zoom-overlay-open is remove at transitionEnd.

Use a larger image

@nishanths Have you been thinking about using another image to zoom?

When the original image is very small it make no sense to zoom it.

Edge compability

I set up a minimum page, and it seems to work fine in all major browsers...except edge. When clicking an image, it zooms in correctly, but when zooming out all other content is gone from the webpage.

docs: add example of how to simulate fat/zoom.js default behavior

import { Config, zoom } from "@nishanths/zoom.js"

const cfg: Config = {
		padding: 80,
		paddingNarrow: 80,
		dismissScrollDelta: 40,
		dismissTouchDelta: 40,
}

for (const img of document.querySelectorAll<HTMLImageElement>(`img[data-action="zoom"]`)) {
	img.classList.add("zoom-cursor")
	img.addEventListener("click", (e) => {
		if (e.metaKey || e.ctrlKey) {
			window.open(img.src, "_blank")
			return
		}
		img.dataset.action = "zoom-out"
		zoom(img, cfg)
		img.dataset.action = "zoom"
	})
}

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.