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

Implement event delegation! #330

Open
artknight opened this issue Jun 19, 2021 · 0 comments
Open

Implement event delegation! #330

artknight opened this issue Jun 19, 2021 · 0 comments
Labels

Comments

@artknight
Copy link

Issue: dynamically added elements DO NOT get picked up for zooming
Solution: Implement event delegation!

I ended up making changes to the zooming.js lib ( which in usually a bad idea ) but I am hoping by posting a solution here that it will get implemented :)

1st change: Added event delegation to the listen method

createClass(Zooming, [{
	key: 'listen',
	value: function listen$$1(el='.img-preview') {
		let selector = el,
			_handler = this.handler;
		
		document.querySelector('body').addEventListener('click', function(event){
			for (let target=event.target; target && target!=this; target=target.parentNode) {
				//loop parent nodes from the target to the delegation node
				if (target.matches(selector)){
					_handler.click(target, event);
					break;
				}
			}
		}, { passive:false });
		
		if (this.options.preloadImage) {
			loadImage(getOriginalSource(el));
		}

		return this;
	}

	/**
		* Update options or return current options if no argument is provided.
		* @param  {Object} options An Object that contains this.options.
		* @return {this|this.options}
		*/

}, {

2nd change: Updated the click method to accept two arguments ( target & event )

click: function click(target,e) {
	e.preventDefault();

	if (isPressingMetaKey(e)) {
		return window.open(this.target.srcOriginal || target.src, '_blank');
	} else {
		if (this.shown) {
			if (this.released) {
				this.close();
			} else {
				this.release();
			}
		} else {
			this.open(target);
		}
	}
},

3rd change: Added CSS to handle relevant elms

.img-preview {
	cursor: zoom-in;
}

Here you go, now all dynamically added elms get picked up !

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

No branches or pull requests

1 participant