Loading and position image, when the another images are loaded - javascript

I have a small problem with loading and position one of my images. The smallest one. I'm using spacegallery script (http://www.eyecon.ro/spacegallery/).
It's loading good, but i want it to position it in the corner of bigger image, and when i load my page for the first time, it's not positioned, when i reload it - it's all fine, but the first loading is wrong.
Here are the screens:
It's the first load without refreshing the site:
first load http://derivativeofln.com/withoutload.png
Second and next loads:
second load http://derivativeofln.com/withload.png
My HTML:
<div id="myGallery" class="spacegallery">
<img class="imaz" src=http://derivativeofln.com/magnifier.jpg />
<img class="aaa" src=images/bw1.jpg alt="" atr1="bw1" />
<img class="aaa" src=images/bw2.jpg alt="" atr1="bw2" />
<img class="aaa" src=images/bw3.jpg alt="" atr1="bw3" />
</div>
MY CSS:
#myGallery0 {
width: 100%;
height: 300px;
}
#myGallery0 img {
border: 2px solid #52697E;
}
a.loading {
background: #fff url(../images/ajax_small.gif) no-repeat center;
}
.imaz {
z-index: 10000;
}
.imaz img{
position: absolute;
left:10px;
top:10px;
z-index: 10000;
width: 35px;
height: 35px;
}
My Jquery main script file: (the first positioning instructions are on the bottom, so feel free to scroll down : ))
(function($){
EYE.extend({
spacegallery: {
animated: false,
//position images
positionImages: function(el) {
var top = 0;
EYE.spacegallery.animated = false;
$(el)
.find('a')
.removeClass(el.spacegalleryCfg.loadingClass)
.end()
.find('img.aaa')
.removeAttr('height')
.each(function(nr){
var newWidth = this.spacegallery.origWidth - (this.spacegallery.origWidth - this.spacegallery.origWidth * el.spacegalleryCfg.minScale) * el.spacegalleryCfg.asins[nr];
$(this)
.css({
top: el.spacegalleryCfg.tops[nr] + 'px',
marginLeft: - parseInt((newWidth + el.spacegalleryCfg.border)/2, 10) + 'px',
opacity: 1 - el.spacegalleryCfg.asins[nr]
})
.attr('width', parseInt(newWidth));
this.spacegallery.next = el.spacegalleryCfg.asins[nr+1];
this.spacegallery.nextTop = el.spacegalleryCfg.tops[nr+1] - el.spacegalleryCfg.tops[nr];
this.spacegallery.origTop = el.spacegalleryCfg.tops[nr];
this.spacegallery.opacity = 1 - el.spacegalleryCfg.asins[nr];
this.spacegallery.increment = el.spacegalleryCfg.asins[nr] - this.spacegallery.next;
this.spacegallery.current = el.spacegalleryCfg.asins[nr];
this.spacegallery.width = newWidth;
})
},
//constructor
init: function(opt) {
opt = $.extend({}, EYE.spacegallery.defaults, opt||{});
return this.each(function(){
var el = this;
if ($(el).is('.spacegallery')) {
$('')
.appendTo(this)
.addClass(opt.loadingClass)
.bind('click', EYE.spacegallery.next);
el.spacegalleryCfg = opt;
var listunia, images2 = [], index;
listunia = el.getElementsByTagName("img");
for (index = 1; index < listunia.length; ++index) {
images2.push(listunia[index]);
}
el.spacegalleryCfg.images = images2.length;
el.spacegalleryCfg.loaded = 0;
el.spacegalleryCfg.asin = Math.asin(1);
el.spacegalleryCfg.asins = {};
el.spacegalleryCfg.tops = {};
el.spacegalleryCfg.increment = parseInt(el.spacegalleryCfg.perspective/el.spacegalleryCfg.images, 10);
var top = 0;
$('img.aaa', el)
.each(function(nr){
var imgEl = new Image();
var elImg = this;
el.spacegalleryCfg.asins[nr] = 1 - Math.asin((nr+1)/el.spacegalleryCfg.images)/el.spacegalleryCfg.asin;
top += el.spacegalleryCfg.increment - el.spacegalleryCfg.increment * el.spacegalleryCfg.asins[nr];
el.spacegalleryCfg.tops[nr] = top;
elImg.spacegallery = {};
imgEl.src = this.src;
if (imgEl.complete) {
el.spacegalleryCfg.loaded ++;
elImg.spacegallery.origWidth = imgEl.width;
elImg.spacegallery.origHeight = imgEl.height
} else {
imgEl.onload = function() {
el.spacegalleryCfg.loaded ++;
elImg.spacegallery.origWidth = imgEl.width;
elImg.spacegallery.origHeight = imgEl.height
if (el.spacegalleryCfg.loaded == el.spacegalleryCfg.images) {
EYE.spacegallery.positionImages(el);
}
};
}
});
el.spacegalleryCfg.asins[el.spacegalleryCfg.images] = el.spacegalleryCfg.asins[el.spacegalleryCfg.images - 1] * 1.3;
el.spacegalleryCfg.tops[el.spacegalleryCfg.images] = el.spacegalleryCfg.tops[el.spacegalleryCfg.images - 1] * 1.3;
if (el.spacegalleryCfg.loaded == el.spacegalleryCfg.images) {
if(el.spacegalleryCfg.images == 3){
$('img.imaz', this).css('top', '27px'); // HERE IS POSITIONING OF MY IMAGES, WHEN SCRIPT LOADS FOR THE FIRST TIME!
$('img.imaz', this).css('left', (($(el).find('img.aaa:last').width())/2 + 77) + 'px' );
}
else if(el.spacegalleryCfg.images==2){
$('img.imaz', this).css('top', '33px');
$('img.imaz', this).css('left', (($(el).find('img.aaa:last').width())/2 + 77) + 'px' ); // HERE IT ENDS:)
}
EYE.spacegallery.positionImages(el);
}
}
});
}
}
});
})(jQuery);

this seems to be a cache thing
try to specify image dimensions (width and height) on your html, because on first load (images not in cache) the browser only knows dimensions after the load and the positioning might not be correct.
in alternative you can run your positioning code when the document is loaded
$(document).ready(«your poisitioning function here»)
see http://api.jquery.com/ready/ for that jquery ready function

Related

How to drag images in JS

I have a large background image and some much smaller images for the user to drag around on the background. I need this to be efficient in terms of performance, so i'm trying to avoid libraries. I'm fine with drag 'n' drop if it work's well, but im trying to get drag.
Im pretty much trying to do this. But after 8 years there must be a cleaner way to do this right?
I currently have a drag 'n' drop system that almost works, but when i drop the smaller images, they are just a little off and it's very annoying. Is there a way to fix my code, or do i need to take a whole different approach?
This is my code so far:
var draggedPoint;
function dragStart(event) {
draggedPoint = event.target; // my global var
}
function drop(event) {
event.preventDefault();
let xDiff = draggedPoint.x - event.pageX;
let yDiff = draggedPoint.y - event.pageY;
let left = draggedPoint.style.marginLeft; // get margins
let top = draggedPoint.style.marginTop;
let leftNum = Number(left.substring(0, left.length - 2)); // cut off px from the end
let topNum = Number(top.substring(0, top.length - 2));
let newLeft = leftNum - xDiff + "px" // count new margins and put px back to the end
let newTop = topNum - yDiff + "px"
draggedPoint.style.marginLeft = newLeft;
draggedPoint.style.marginTop = newTop;
}
function allowDrop(event) {
event.preventDefault();
}
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.style.marginLeft = `${Math.floor(Math.random() * 900)}px`
sensor.style.marginTop = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = function() {
sensorClick(logs[i].id)
};
sensor.addEventListener("dragstart", dragStart, null);
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
<!-- my html: -->
<style>
.map {
width: 900px;
height: 500px;
align-content: center;
margin: 150px auto 150px auto;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
position: absolute;
width: 50px;
height: 50px;
}
</style>
<div class="map" onDrop="drop(event)" ondragover="allowDrop(event)">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false">
<div>
With the answers from here and some time i was able to get a smooth drag and click with pure js.
Here is a JSFiddle to see it in action.
let maxLeft;
let maxTop;
const minLeft = 0;
const minTop = 0;
let timeDelta;
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
var originalX;
var originalY;
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
function sensorClick () {
if (Date.now() - timeDelta < 150) { // check that we didn't drag
createPopup(this);
}
}
// create a popup when we click
function createPopup(parent) {
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
let popup = document.createElement("div");
popup.id = "popup";
popup.className = "popup";
popup.style.top = parent.y - 110 + "px";
popup.style.left = parent.x - 75 + "px";
let text = document.createElement("span");
text.textContent = parent.id;
popup.appendChild(text);
var map = document.getElementsByClassName("map")[0];
map.appendChild(popup);
}
// when our base is loaded
function baseOnLoad() {
var map = document.getElementsByClassName("map")[0];
let base = document.getElementsByClassName("base")[0];
maxLeft = base.width - 50;
maxTop = base.height - 50;
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.id = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.classList.add("dragme");
sensor.style.left = `${Math.floor(Math.random() * 900)}px`
sensor.style.top = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = sensorClick;
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
}
function startDrag(e) {
timeDelta = Date.now(); // get current millis
// determine event object
if (!e) var e = window.event;
// prevent default event
if(e.preventDefault) e.preventDefault();
// IE uses srcElement, others use target
targ = e.target ? e.target : e.srcElement;
originalX = targ.style.left;
originalY = targ.style.top;
// check that this is a draggable element
if (!targ.classList.contains('dragme')) return;
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// calculate integer values for top and left properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
document.onmousemove = dragDiv; // move div element
return false; // prevent default event
}
function dragDiv(e) {
if (!drag) return;
if (!e) var e = window.event;
// move div element and check for borders
let newLeft = coordX + e.clientX - offsetX;
if (newLeft < maxLeft && newLeft > minLeft) targ.style.left = newLeft + 'px'
let newTop = coordY + e.clientY - offsetY;
if (newTop < maxTop && newTop > minTop) targ.style.top = newTop + 'px'
return false; // prevent default event
}
function stopDrag() {
if (typeof drag == "undefined") return;
if (drag) {
if (Date.now() - timeDelta > 150) { // we dragged
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
} else {
targ.style.left = originalX;
targ.style.top = originalY;
}
}
drag = false;
}
.map {
width: 900px;
height: 500px;
margin: 50px
position: relative;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
display: inline-block;
position: absolute;
width: 50px;
height: 50px;
}
.dragme {
cursor: move;
left: 0px;
top: 0px;
}
.popup {
position: absolute;
display: inline-block;
width: 200px;
height: 100px;
background-color: #9FC990;
border-radius: 10%;
}
.popup::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -10px;
border-width: 10px;
border-style: solid;
border-color: #9FC990 transparent transparent transparent;
}
.popup span {
width: 90%;
margin: 10px;
display: inline-block;
text-align: center;
}
<div class="map" width="950px" height="500px">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false" onload="baseOnLoad()">
<div>

How much of an element is visible in viewport

There's a div (brown rectangle) on the page. The page is higher than the viewport (orange rectangle) so it can be scrolled, which means that the div might only partially show up or not at all.
What's the simplest algorithm to tell how much % of the div is visible in the viewport?
(To make things easier, the div always fits into the viewport horizontally, so only the Y axis needs to be considered at the calculations.)
See one more example in fiddle:
https://jsfiddle.net/1hfxom6h/3/
/*jslint browser: true*/
/*global jQuery, window, document*/
(function ($) {
'use strict';
var results = {};
function display() {
var resultString = '';
$.each(results, function (key) {
resultString += '(' + key + ': ' + Math.round(results[key]) + '%)';
});
$('p').text(resultString);
}
function calculateVisibilityForDiv(div$) {
var windowHeight = $(window).height(),
docScroll = $(document).scrollTop(),
divPosition = div$.offset().top,
divHeight = div$.height(),
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll + windowHeight);
if ((docScroll > divPosition + divHeight) || (divPosition > docScroll + windowHeight)) {
return 0;
} else {
var result = 100;
if (hiddenBefore > 0) {
result -= (hiddenBefore * 100) / divHeight;
}
if (hiddenAfter > 0) {
result -= (hiddenAfter * 100) / divHeight;
}
return result;
}
}
function calculateAndDisplayForAllDivs() {
$('div').each(function () {
var div$ = $(this);
results[div$.attr('id')] = calculateVisibilityForDiv(div$);
});
display();
}
$(document).scroll(function () {
calculateAndDisplayForAllDivs();
});
$(document).ready(function () {
calculateAndDisplayForAllDivs();
});
}(jQuery));
div {
height:200px;
width:300px;
border-width:1px;
border-style:solid;
}
p {
position: fixed;
left:320px;
top:4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<p id="result"></p>
Here's a snippet illustrating how you can calculate this.
I've put the % values in the boxes for readability, and it even kinda "follows" the viewport ^^ :
Fiddle version
function listVisibleBoxes() {
var results = [];
$("section").each(function () {
var screenTop = document.documentElement.scrollTop;
var screenBottom = document.documentElement.scrollTop + $(window).height();
var boxTop = $(this).offset().top;
var boxHeight = $(this).height();
var boxBottom = boxTop + boxHeight;
if(boxTop > screenTop) {
if(boxBottom < screenBottom) {
//full box
results.push(this.id + "-100%");
$(this).html("100%").css({ "line-height": "50vh" });
} else if(boxTop < screenBottom) {
//partial (bottom)
var percent = Math.round((screenBottom - boxTop) / boxHeight * 100) + "%";
var lineHeight = Math.round((screenBottom - boxTop) / boxHeight * 50) + "vh";
results.push(this.id + "-" + percent);
$(this).html(percent).css({ "line-height": lineHeight });
}
} else if(boxBottom > screenTop) {
//partial (top)
var percent = Math.round((boxBottom - screenTop) / boxHeight * 100) + "%";
var lineHeight = 100 - Math.round((boxBottom - screenTop) / boxHeight * 50) + "vh";
results.push(this.id + "-" + percent);
$(this).html(percent).css({ "line-height": lineHeight });
}
});
$("#data").html(results.join(" | "));
}
$(function () {
listVisibleBoxes();
$(window).on("scroll", function() {
listVisibleBoxes();
});
});
body {
background-color: rgba(255, 191, 127, 1);
font-family: Arial, sans-serif;
}
section {
background-color: rgba(175, 153, 131, 1);
height: 50vh;
font-size: 5vh;
line-height: 50vh;
margin: 10vh auto;
overflow: hidden;
text-align: center;
width: 50vw;
}
#data {
background-color: rgba(255, 255, 255, .5);
left: 0;
padding: .5em;
position: fixed;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="one"></section>
<section id="two"></section>
<section id="three"></section>
<section id="four"></section>
<section id="five"></section>
<section id="six"></section>
<div id="data">data here</div>
After playing around a bit I think I've found perhaps the simplest way to do it: I basically determine how much the element extends over the viewport (doesn't matter in which direction) and based on this it can easily be calculated how much of it is visible.
// When the page is completely loaded.
$(document).ready(function() {
// Returns in percentages how much can be seen vertically
// of an element in the current viewport.
$.fn.pvisible = function() {
var eTop = this.offset().top;
var eBottom = eTop + this.height();
var wTop = $(window).scrollTop();
var wBottom = wTop + $(window).height();
var totalH = Math.max(eBottom, wBottom) - Math.min(eTop, wTop);
var wComp = totalH - $(window).height();
var eIn = this.height() - wComp;
return (eIn <= 0 ? 0 : eIn / this.height() * 100);
}
// If the page is scrolled.
$(window).scroll(function() {
// Setting the opacity of the divs.
$("div").each(function() {
$(this).css("opacity", Math.round($(this).pvisible()) / 100);
});
});
});
html,
body {
width: 100%;
height: 100%;
}
body {
background-color: rgba(255, 191, 127, 1);
}
div {
width: 60%;
height: 30%;
margin: 5% auto;
background-color: rgba(175, 153, 131, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
A little illustration to help understand how it works:
Chrome now supports Intersection Observer API
Example (TypeScript):
export const elementVisibleInPercent = (element: HTMLElement) => {
return new Promise((resolve, reject) => {
const observer = new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
entries.forEach((entry: IntersectionObserverEntry) => {
resolve(Math.floor(entry.intersectionRatio * 100));
clearTimeout(timeout);
observer.disconnect();
});
});
observer.observe(element);
// Probably not needed, but in case something goes wrong.
const timeout = setTimeout(() => {
reject();
}, 500);
});
};
const example = document.getElementById('example');
const percentageVisible = elementVisibleInPercent(example);
Example (JavaScript):
export const elementVisibleInPercent = (element) => {
return new Promise((resolve, reject) => {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
resolve(Math.floor(entry.intersectionRatio * 100));
clearTimeout(timeout);
observer.disconnect();
});
});
observer.observe(element);
// Probably not needed, but in case something goes wrong.
const timeout = setTimeout(() => {
reject();
}, 500);
});
};
const example = document.getElementById('example');
const percentageVisible = elementVisibleInPercent(example);
Please note that the Intersection Observer API is available since then, made specifically for this purpose.

can't achieve touch compatibility with my jQuery zoom plugin

I modified an MIT licensed Zoom Plugins to fit my needs and it works perfectly well. However, it came from a time before smartphones and tablets and I really want to support them.
I have built a jsFiddle to illustrate my case:
https://jsfiddle.net/xLr86bs8/
Neccessary code:
JavaScript:
(function($){
var defaults = {
cursorColor:'237,241,244',
cursorOpacity: 1,
//cursorBorder: '1px solid black',
//cursorBorderThickness: 1,
cursor:'pointer',
zoomviewsize: [0,0],
magnification: 5,
};
var minitraversalzoomCursor,minitraversalzoomView,minitraversalsettings,minitraversalImageWidth,minitraversalImageHeight,minitraversalOffset,minitraversalzoomimage;
var minitraversalMethods = {
init : function(options){
$this = $(this),
minitraversalzoomCursor = $('.minitraversalzoom-cursor'),
minitraversalzoomView = $('.minitraversalzoom-view'),
minitraversalzoomimage = $('#MiniTraversalZoomImage'),
// This makes the complete addon independent from the size of the zoomwindow
//defaults.zoomviewsize = [$('#RadialBox').width(),$('#RadialBox').height()];
$(document).on('mouseenter touchstart',$this.selector,function(e){
var data = $(this).data();
minitraversalsettings = $.extend({},defaults,options,data);
minitraversalOffset = $(this).offset();
minitraversalImageWidth = $(this).width();
minitraversalImageHeight = $(this).height();
minitraversalsettings.zoomviewsize = [$(this).parent().width(),$(this).parent().height()];
cursorSize = [(minitraversalsettings.zoomviewsize[0]/minitraversalsettings.magnification),(minitraversalsettings.zoomviewsize[1]/minitraversalsettings.magnification)];
$original = $(this);
minitraversalZoomSource = $(this).attr('data-minitraversalzoom');
minitraversalSource = $(this).attr('src');
var posX = e.pageX,posY = e.pageY,zoomViewPositionX;
$('body').prepend('<div class="minitraversalzoom-cursor"> </div>');
$('#MiniZoomBox').addClass('minitraversalzoom-view').prepend('<img id="MiniTraversalZoomImage" src="' + minitraversalZoomSource + '">');
$(minitraversalzoomView.selector).css({
'position':'relative',
'z-index': 7,
'overflow':'hidden',
});
$(minitraversalzoomView.selector).children('img[id="MiniTraversalZoomImage"]').css({
'position':'relative',
'width': minitraversalImageWidth*minitraversalsettings.magnification,
'height': minitraversalImageHeight*minitraversalsettings.magnification,
});
$(minitraversalzoomCursor.selector).css({
'position':'absolute',
'width':cursorSize[0],
'height':cursorSize[1],
'background-color':'rgb('+ minitraversalsettings.cursorColor +')',
'z-index': 7,
'opacity':minitraversalsettings.cursorOpacity,
'cursor':minitraversalsettings.cursor,
'border':minitraversalsettings.cursorBorder,
});
$(minitraversalzoomCursor.selector).css({'top':posY-(cursorSize[1]/2),'left':posX});
$(document).on('mousemove move',document.body,minitraversalMethods.cursorPos);
});
},
cursorPos:function(e){
var posX = e.pageX,posY = e.pageY;
if(posY < minitraversalOffset.top || posX < minitraversalOffset.left || posY > (minitraversalOffset.top+minitraversalImageHeight) || posX > (minitraversalOffset.left+minitraversalImageWidth)){
$(minitraversalzoomCursor.selector).remove();
$(minitraversalzoomimage.selector).remove();
//$(minitraversalzoomView.selector).empty();
//$('#ZoomImage').remove();
//$(this).siblings('img').remove();
//$('#RadialBox > img').remove();
//$('#MiniZoomBox > img[id!="TraversalZoomImage10x"]').remove();
$('#MiniZoomBox').removeClass('minitraversalzoom-view');//.append('<img data-minitraversalzoom="' + minitraversalZoomSource + '" src="' + minitraversalSource + '" class="minitraversalzoom">');
//$('#MiniZoomBox').empty().removeClass('minitraversalzoom-view').append('<img data-minitraversalzoom="' + minitraversalZoomSource + '" src="' + minitraversalSource + '" class="minitraversalzoom">');
//$('#RadialBox').removeClass('minitraversalzoom-view').prepend($original.prop('outerHTML'));
return;
}
if(posX-(cursorSize[0]/2) < minitraversalOffset.left){
posX = minitraversalOffset.left+(cursorSize[0]/2);
}else if(posX+(cursorSize[0]/2) > minitraversalOffset.left+minitraversalImageWidth){
posX = (minitraversalOffset.left+minitraversalImageWidth)-(cursorSize[0]/2);
}
if(posY-(cursorSize[1]/2) < minitraversalOffset.top){
posY = minitraversalOffset.top+(cursorSize[1]/2);
}else if(posY+(cursorSize[1]/2) > minitraversalOffset.top+minitraversalImageHeight){
posY = (minitraversalOffset.top+minitraversalImageHeight)-(cursorSize[1]/2);
}
$(minitraversalzoomCursor.selector).css({'top':posY-(cursorSize[1]/2),'left':posX-(cursorSize[0]/2)});
$(minitraversalzoomView.selector).children('img').css({'top':((minitraversalOffset.top-posY)+(cursorSize[1]/2))*minitraversalsettings.magnification,'left':((minitraversalOffset.left-posX)+(cursorSize[0]/2))*minitraversalsettings.magnification});
/*
$(minitraversalzoomCursor.selector).mouseleave(function(){
$(this).remove();
});*/
}
};
$.fn.minitraversalZoom = function(method){
if(minitraversalMethods[method]){
return minitraversalMethods[method].apply( this, Array.prototype.slice.call(arguments,1));
}else if( typeof method === 'object' || ! method ) {
return minitraversalMethods.init.apply(this,arguments);
}else{
$.error(method);
}
}
$(document).ready(function(){
$('[data-minitraversalzoom]').minitraversalZoom();
});
})(jQuery);
HTML:
<div class="ZoomWindow" id="MiniZoomBox"><img class="minitraversalzoom" data-minitraversalzoom="http://placekitten.com/234/351" src="http://placekitten.com/234/351"/></div>
<div class=""></div>
CSS:
.ZoomWindowContainer{
display: inline-block;
position: relative;
vertical-align: top;
}
.ZoomWindow{
/* display: inline-block;
*/ height: 351px;
width: 234px;
margin-top: 4px;
border: 1px solid #a3b7c7;
}
#MiniZoomBox > img.miniradialzoom, #MiniZoomBox > img.minitraversalzoom, #MiniZoomBox > img.minitangentialzoom{
height: 100%;
}
#MiniZoomBox{
background-color: #0072bd;
/*background: url("/css/styling/magnifier_background-gradient-right.png") repeat-y scroll 0% 0% transparent;*/
/* background: url('/css/styling/10x.png') #0072bd;
*/ background-size: 100%;
overflow: hidden;
}
Could somebody help me to tweek it, in order to make it work?
Update:
I implemented the jQuery.event.move plugin to get new options like movestart, move, etc… and with it, I could get my plugin to work correctly on touchscreens, however, scrolling does not work at all on the site now. So i solved one problem and got another one. Does anyone know, to fix either one of them?
Update Jan. 1st 2016:
I continued programming and this is still the last problem I am facing. Any help is welcomed here ;)

Jquery word for word fade in effect

ive been looking in about for this exact script for a while and i cant get it to work. Im looking to use a fade in effect from left to right word by word.
For example
<div class="box5">
<h1>Lorem ipsum dolor sit amet, ne mel vero impetus voluptatibus
</h1>
</div>
I want this to fade in then enough line to fade in word by word slightly later using a delay.
My current fade in works but it does it by the full container it looks like this
.reveal {
position: relative;
overflow: hidden;
}
/*initial - hidden*/
.reveal .reveal__cover {
position: absolute;
top: 0;
left: -250px;
height: 100%;
margin: 2px;
width: calc(100% + 250px);
}
.reveal .reveal__cover.reveal__uncovered {
position: absolute;
top: 0;
left: 100%;
height: 100%;
width: calc(100% + 250px);
margin: 2px;
transition: left 2500ms ease-out 0ms;
}
.reveal__cover-section {
height: 100%;
float: right;
/* NOTE: Background must match existing background */
/*background: #000;*/
background: #fff;
width: 2%;
}
.reveal__10 {
opacity: 0.1;
}
.reveal__20 {
opacity: 0.2;
}
.reveal__30 {
opacity: 0.3;
}
.reveal__40 {
opacity: 0.4;
}
.reveal__50 {
opacity: 0.5;
}
.reveal__60 {
opacity: 0.6;
}
.reveal__70 {
opacity: 0.7;
}
.reveal__80 {
opacity: 0.8;
}
.reveal__90 {
opacity: 0.9;
}
.reveal__100 {
opacity: 1;
width: 82%;
}
Then JS
function replaceAllInstances(source, search, replacement) {
var regex = new RegExp(search, "g");
var result = source.replace(regex, replacement);
return result;
}
$.fn.isOnScreen = function (x, y) {
if (x == null || typeof x == 'undefined')
x = 1;
if (y == null || typeof y == 'undefined')
y = 1;
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var height = this.outerHeight();
var width = this.outerWidth();
if (!width || !height) {
return false;
}
var bounds = this.offset();
bounds.right = bounds.left + width;
bounds.bottom = bounds.top + height;
var visible = (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
if (!visible) {
return false;
}
var deltas = {
top: Math.min(1, (bounds.bottom - viewport.top) / height),
bottom: Math.min(1, (viewport.bottom - bounds.top) / height),
left: Math.min(1, (bounds.right - viewport.left) / width),
right: Math.min(1, (viewport.right - bounds.left) / width)
};
return (deltas.left * deltas.right) >= x && (deltas.top * deltas.bottom) >= y;
};
/*
* Init specified element so it can be gradually revealed.
*
* Limitations:
* Only works on backgrounds with a solid color.
*
* #param options = {
* id:'box3'
* ,background='#ffffff' //default
* ,delay='0' //default
* }
*
*/
$.fn.initReveal = function (options) {
console.log('-------------');
console.log('selector:' + this.selector);
var parent = $(this).parent();
//grab a copy of the contents, then remove it from DOM
var contents = $(this).clone();
$(this).empty();
var revealHtmlBlock = "<div class='reveal'> <div class='text reveal__inner reveal__inner-{class}'> </div> <div class='reveal__cover reveal__cover-{class}'> <div class='reveal__cover-section reveal__100'></div> <div class='reveal__cover-section reveal__90'></div> <div class='reveal__cover-section reveal__80'></div> <div class='reveal__cover-section reveal__70'></div> <div class='reveal__cover-section reveal__60'></div> <div class='reveal__cover-section reveal__50'></div> <div class='reveal__cover-section reveal__40'></div> <div class='reveal__cover-section reveal__30'></div> <div class='reveal__cover-section reveal__20'></div> <div class='reveal__cover-section reveal__10'></div> </div> </div>";
revealHtmlBlock = replaceAllInstances(revealHtmlBlock, "{class}", options.id);
$(revealHtmlBlock).appendTo(parent);
contents.appendTo($('.reveal__inner-' + options.id));
//handle options
//delay
if (options.delay === undefined) {
console.log('delay set to 0');
options.delay = 0; //set default
} else {
console.log('delay set to:' + options.delay);
}
var revealElementFunction = function (options) {
$(this).performReveal(options);
};
//background
if (options.background !== undefined) {
$('.reveal__cover-' + options.id + ' .reveal__cover-section').css({'background-color': options.background});
}
//trigger the reveal at the specified time, unless auto is present and set to false
if (options.auto === undefined || (options.auto !== undefined && options.auto)) {
setTimeout(function () {
console.log('call');
revealElementFunction(options);
}, options.delay);
}
//trigger on-visible
if (options.trigger !== undefined) {
var revealOnScreenIntervalIdMap = {};
function uncoverText() {
var onscreen = $('.reveal__inner-box4').isOnScreen();
if ($('.reveal__inner-' + options.id).isOnScreen()) {
$('.reveal__cover-' + options.id).addClass('reveal__uncovered');
revealOnScreenIntervalIdMap[options.id] = window.clearInterval(revealOnScreenIntervalIdMap[options.id]);
}
}
function showTextWhenVisible() {
revealOnScreenIntervalIdMap[options.id] = setInterval(uncoverText, 800);
}
showTextWhenVisible();
}
};
//--------------------
/*
* trigger options:
* immediately (on page load)
* on event, eg. onclick
* on becoming visible, after it scrolls into view, or is displayed after bein ghidden
*
* #param options = {
* id:'box3'
* }
*
*/
$.fn.performReveal = function (options) {
var _performReveal = function () {
$('.reveal__cover-' + options.id).addClass('reveal__uncovered');
};
//allow time for init code to complete
setTimeout(_performReveal, 250);
};
Main JS
jQuery(function () {
//Box 1: reveal immediately - on page load
//NOTE: id does refer to an element id, It is used to
// uniquely refer to the element to be revealed.
var options1 = {
id: 'box1',
background: '#008d35'
};
$('.box1').initReveal(options1);
//------------------------
//Box 2: reveal after specified delay
var options2 = {
id: 'box2'
, delay: 3000
, background: '#008d35'
};
$('.box2').initReveal(options2);
//------------------------
//Box 3: reveal on event - eg. onclick
var options3 = {
id: 'box3'
, auto: false
};
var box3 = $('.box3');
box3.initReveal(options3);
$('.btn-reveal').on('click', function () {
box3.performReveal(options3);
});
//------------------------
//Box 4: Reveal when element scrolls into the viewport
var options4 = {
id: 'box4'
, auto: false
, trigger: 'on-visible'
};
$('.box4').initReveal(options4);
});
//------------------------
//Box 5 reveal
var options5 = {
id: 'box5'
, delay: 2500 ,
background: '#008d35'
};
$('.box5').initReveal(options5);
does anyone have any idea how to make it work word by word and not line by line
Here's a simple approach that you can build on. It creates the needed spans and fades them in based on interval value you set.
var fadeInterval = 300
$('h1').html(function(_, txt){
var words= $.trim(txt).split(' ');
return '<span>' + words.join('</span> <span>') + '</span>';
}).find('span').each(function(idx, elem){
$(elem).delay(idx * fadeInterval).fadeIn();
});
DEMO

How to make my script affects only it's own image in jquery?

i'm trying to implement SpaceGallery script. WWW: http://www.eyecon.ro/spacegallery/. It takes the images from #div and make the slide like on online demo.
Part of my HTML file:
<div id="myGallery0" class="spacegallery">
<img class="imaz" src="ADDITIONAL.jpg" alt="" atr1="lupa" />
<img class="aaa" src=images/bw1.jpg alt="" atr1="bw1" />
<img class="aaa" src=images/bw2.jpg alt="" atr1="bw2" />
<img class="aaa" src=images/bw3.jpg alt="" atr1="bw3" />
</div>
<div id="myGallery1" class="spacegallery">
<img class="imaz" src="ADDITIONAL.jpg" alt="" atr1="lupa" />
<img class="aaa" src=images3/bw1.jpg alt="" atr1="bw1" />
<img class="aaa" src=images3/bw2.jpg alt="" atr1="bw2" />
<img class="aaa" src=images3/lights2.jpg alt="" atr1="bw3" />
</div>
<script>
var initLayout = function() {
$('#myGallery0').spacegallery({loadingClass: 'loading'});
$('#myGallery1').spacegallery({loadingClass: 'loading'});
};
EYE.register(initLayout, 'init');
</script>
And now, the script works good when I'm calling $('img.aaa')! The script slides only images from it's own ID (mygallery0 or mygallery1). Let's say I have the following .onclick thing in my main .js file.
$('img.imaz').fadeOut();
And when i'm sliding the images in one of my galleries (mygaller0 or mygallery1), the img "ADDITIONAL.jpg" (it's class = imaz) fadeOuts in all of my galleries! Why is that? How to fix it?
Spacegallery.js
(function($){
EYE.extend({
spacegallery: {
//default options (many options are controled via CSS)
defaults: {
border: 6, // border arround the image
perspective: 100, // perpective height
minScale: 0.1, // minimum scale for the image in the back
duration: 800, // aimation duration
loadingClass: null, // CSS class applied to the element while looading images
before: function(){
$('img.imaz').fadeOut();
return false
},
after: function(el){
$('img.imaz').fadeIn();
return false
}
},
animated: false,
//position images
positionImages: function(el) {
var top = 0;
EYE.spacegallery.animated = false;
$(el)
.find('a')
.removeClass(el.spacegalleryCfg.loadingClass)
.end()
.find('img.aaa')
.each(function(nr){
console.log('WYSOKOSC ' + $(this).attr('height'));
var newWidth = this.spacegallery.origWidth - (this.spacegallery.origWidth - this.spacegallery.origWidth * el.spacegalleryCfg.minScale) * el.spacegalleryCfg.asins[nr];
$(this)
.css({
top: el.spacegalleryCfg.tops[nr] + 'px',
marginLeft: - parseInt((newWidth + el.spacegalleryCfg.border)/2, 10) + 'px',
opacity: 1 - el.spacegalleryCfg.asins[nr]
})
.attr('width', parseInt(newWidth));
this.spacegallery.next = el.spacegalleryCfg.asins[nr+1];
this.spacegallery.nextTop = el.spacegalleryCfg.tops[nr+1] - el.spacegalleryCfg.tops[nr];
this.spacegallery.origTop = el.spacegalleryCfg.tops[nr];
this.spacegallery.opacity = 1 - el.spacegalleryCfg.asins[nr];
this.spacegallery.increment = el.spacegalleryCfg.asins[nr] - this.spacegallery.next;
this.spacegallery.current = el.spacegalleryCfg.asins[nr];
this.spacegallery.width = newWidth;
})
},
//animate to nex image
next: function(e) {
if (EYE.spacegallery.animated === false) {
EYE.spacegallery.animated = true;
var el = this.parentNode;
el.spacegalleryCfg.before.apply(el);
$(el)
.css('spacegallery', 0)
.animate({
spacegallery: 100
},{
easing: 'easeOut',
duration: el.spacegalleryCfg.duration,
complete: function() {
$(el)
.find('img.aaa:last')
.prependTo(el);
EYE.spacegallery.positionImages(el);
el.spacegalleryCfg.after.apply(el);
},
step: function(now) {
$('img.aaa', this)
.each(function(nr){
console.log('step: ' + $(this).attr('atr1'));
var newWidth, top, next;
if (nr + 1 == el.spacegalleryCfg.images) {
top = this.spacegallery.origTop + this.spacegallery.nextTop * 4 * now /100;
newWidth = this.spacegallery.width * top / this.spacegallery.origTop;
$(this)
.css({
top: top + 'px',
opacity: 0.7 - now/100,
marginLeft: - parseInt((newWidth + el.spacegalleryCfg.border)/2, 10) + 'px'
})
.attr('width', newWidth);
}
else {
next = this.spacegallery.current - this.spacegallery.increment * now /100;
newWidth = this.spacegallery.origWidth - (this.spacegallery.origWidth - this.spacegallery.origWidth * el.spacegalleryCfg.minScale) * next;
$(this).css({
top: this.spacegallery.origTop + this.spacegallery.nextTop * now /100 + 'px',
opacity: 1 - next,
marginLeft: - parseInt((newWidth + el.spacegalleryCfg.border)/2, 10) + 'px'
})
.attr('width', newWidth);
}
});
}
});
}
this.blur();
return false;
},
//constructor
init: function(opt) {
opt = $.extend({}, EYE.spacegallery.defaults, opt||{});
return this.each(function(){
var el = this;
if ($(el).is('.spacegallery')) {
$('')
.appendTo(this)
.addClass(opt.loadingClass)
.bind('click', EYE.spacegallery.next);
el.spacegalleryCfg = opt;
el.spacegalleryCfg.images = 3;
el.spacegalleryCfg.loaded = 0;
el.spacegalleryCfg.asin = Math.asin(1);
el.spacegalleryCfg.asins = {};
el.spacegalleryCfg.tops = {};
el.spacegalleryCfg.increment = parseInt(el.spacegalleryCfg.perspective/el.spacegalleryCfg.images, 10);
var top = 0;
$('img.aaa', el)
.each(function(nr){
var imgEl = new Image();
var elImg = this;
el.spacegalleryCfg.asins[nr] = 1 - Math.asin((nr+1)/el.spacegalleryCfg.images)/el.spacegalleryCfg.asin;
top += el.spacegalleryCfg.increment - el.spacegalleryCfg.increment * el.spacegalleryCfg.asins[nr];
el.spacegalleryCfg.tops[nr] = top;
elImg.spacegallery = {};
imgEl.src = this.src;
if (imgEl.complete) {
el.spacegalleryCfg.loaded ++;
elImg.spacegallery.origWidth = imgEl.width;
elImg.spacegallery.origHeight = imgEl.height
} else {
imgEl.onload = function() {
el.spacegalleryCfg.loaded ++;
elImg.spacegallery.origWidth = imgEl.width;
elImg.spacegallery.origHeight = imgEl.height
if (el.spacegalleryCfg.loaded == el.spacegalleryCfg.images) {
EYE.spacegallery.positionImages(el);
}
};
}
});
el.spacegalleryCfg.asins[el.spacegalleryCfg.images] = el.spacegalleryCfg.asins[el.spacegalleryCfg.images - 1] * 1.3;
el.spacegalleryCfg.tops[el.spacegalleryCfg.images] = el.spacegalleryCfg.tops[el.spacegalleryCfg.images - 1] * 1.3;
if (el.spacegalleryCfg.loaded == el.spacegalleryCfg.images) {
EYE.spacegallery.positionImages(el);
}
}
});
}
}
});
$.fn.extend({
/**
* Create a space gallery
* #name spacegallery
* #description create a space gallery
* #option int border Images' border. Default: 6
* #option int perspective Perpective height. Default: 140
* #option float minScale Minimum scale for the image in the back. Default: 0.2
* #option int duration Animation duration. Default: 800
* #option string loadingClass CSS class applied to the element while looading images. Default: null
* #option function before Callback function triggered before going to the next image
* #option function after Callback function triggered after going to the next image
*/
spacegallery: EYE.spacegallery.init
});
$.extend($.easing,{
easeOut:function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
}
});
})(jQuery);
You can try to limit the matched image to the context of the current element by passing in this as the second argument tot he selector.
defaults: {
/* options */
before: function(){
$('img.imaz', this).fadeOut();
},
after: function(el){
$('img.imaz', this).fadeIn();
}
}
Whe we pass in this, as the second argument in the selector, we're telling jQuery to target "img.imaz", but only when it's found within this, meaning the current element being handled. In your project, this will be either #myGallery0, or #myGallery1.
You can learn more about the context argument online at http://api.jquery.com/jQuery/

Categories