Hello I have changed the flip card element from w3schools and added javascript that they will rotate 60px if they are in viewport with that user can understand that there is a textt behind card. It works well on scroll but now I release that hover effekt is not working.Can you please help me?
https://www.w3schools.com/howto/howto_css_flip_card.asp
https://jsfiddle.net/mqbkzLy2/
var x = 0;
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).scroll(function() {
if ($(".flip-card-inner").isInViewport() && x == 0) {
setTimeout(function() {
$(".flip-card-inner").css('transform', 'rotateY(80deg)');
}, 400);
setTimeout(function() {
$(".flip-card-inner").css('transform', 'rotateY(0)');
}, 800);
x++;
console.log(x);
console.log("in");
}
if (!$(".flip-card-inner").isInViewport() && x != 0) {
x = 0;
console.log('No success.');
console.log(x);
console.log("out");
}
});
body {
font-family: Arial, Helvetica, sans-serif;
}
.flip-card {
background-color: transparent;
width: 300px;
height: 300px;
perspective: 1000px;
}
.flip-card-inner {
position: relative;
width: 100%;
height: 100%;
text-align: center;
transition: transform 0.6s;
transform-style: preserve-3d;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
}
.flip-card:hover .flip-card-inner {
transform: rotateY(180deg);
}
.flip-card-front,
.flip-card-back {
position: absolute;
width: 100%;
height: 100%;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.flip-card-front {
background-color: #bbb;
color: black;
}
.flip-card-back {
background-color: #2980b9;
color: white;
transform: rotateY(180deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height:120vh;background-color:yellow;"></div>
<h1>Card Flip with Text</h1>
<h3>Hover over the image below:</h3>
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img src="https://upload.wikimedia.org/wikipedia/commons/d/de/Windows_live_square.JPG" alt="Avatar" style="width:300px;height:300px;">
</div>
<div class="flip-card-back">
<h1>John Doe</h1>
<p>Architect & Engineer</p>
<p>We love that guy</p>
</div>
</div>
</div>
that they will rotate 60px if they are in viewport with that user can understand that there is a textt behind card.
Don't use scroll event listener for this, use Intersection Observer (IO) for this.
IO was designed for such problems. With IO you can react whenever an HTML element intersects with another one (or with the viewport)
Check this page, it shows you how to animate an element once it comes into viewport (scroll all the way down). Of course, you can use any animation you want, this is then handled by CSS. This is just an really visible example.
Short recap on what you have to do to get IO to work:
First you have to create a new observer:
var options = {
rootMargin: '0px',
threshold: 1.0
}
var observer = new IntersectionObserver(callback, options);
Here we define that once your target Element is 100% visible in the viewport (threshold of 1) your callback Function is getting executed. Here you can define another percentage, 0.5 would mean that the function would be executed once your element is 50% visible.
Then you have to define which elements to watch
var target = document.querySelector('.flip-card');
observer.observe(target);
Last you need to specify what should happen once the element is visible in your viewport by defining the callback function:
var callback = function(entries, observer) {
entries.forEach(entry => {
// Each entry describes an intersection change for one observed
// here you animate another element and do whatever you like
});
};
If you need to support older browsers, use the official polyfill from w3c.
If you don't want to trigger the animation again when the elements are scrolled again into view a second time then you can also unobserve an element once it's animated.
Related
hello everyone hope you guys are having a great day!
so, i am building a simple game where I use a custom-made cursor as the aim for shooting div elements moving around the screen as the enemies and when i apply the "pointerdown" event i want the enemy to change its color. however, every time i hover over the enemy the cursor falls behind witch i don't understand why, and when i use the z-index property it will prevent the "pointerdown" event from firing. if some cool OG programmer can help me, it would mean a lot to me.
style
* {
margin: 0;
padding: 0;
cursor: none;
}
.aim {
position: absolute;
background: black;
width: 10px;
height: 10px;
border-radius: 50%;
transform: translate(-50%, -50%);
}
.enemy {
position: absolute;
border: 3px solid black;
background-color: blue;
width: 50px;
height: 50px;
}
javascript
const body = document.body;
const aim = document.createElement("div");
const enemy = document.createElement("div");
body.appendChild(aim);
body.appendChild(enemy);
aim.classList.add("aim");
enemy.classList.add("enemy");
let enemy_X_position = 0;
let enemy_Y_position = 0;
let enemy_X_distance = 1;
let enemy_Y_distance = 1;
function Flight()
{
enemy.style.left = enemy_X_position + "px";
enemy.style.top = enemy_Y_position + "px";
}
setInterval(function()
{
enemy_X_position += enemy_X_distance;
enemy_Y_position += enemy_Y_distance;
if ((enemy_X_position + enemy.offsetWidth) >= window.innerWidth || enemy_X_position <= 0)
enemy_X_distance = -enemy_X_distance;
if ((enemy_Y_position + enemy.offsetHeight) >= window.innerHeight || enemy_Y_position <= 0)
enemy_Y_distance = -enemy_Y_distance;
Flight();
},1000/60)
window.onmousemove = function()
{
aim.style.left = event.pageX + "px";
aim.style.top = event.pageY + "px";
}
enemy.onpointerdown = function()
{
event.target.style.background = "red";
}
enemy.onpointerup = function()
{
event.target.style.background = null;
}
Update
The event is not triggering because pointerdown was received by aim when it sits on top of enemy.
To solve this, add pointer-events: none on aim class to prevent it from being the target of a pointer event.
More about pointer-events
Hope this will help!
.aim {
position: absolute;
background: black;
width: 10px;
height: 10px;
border-radius: 50%;
transform: translate(-50%, -50%);
pointer-events: none;
}
Original
Perhaps an over simplified solution, but it seems that if you reverse the order of appendChild, the aim should be stacked over enemy without additional styling.
Example:
body.appendChild(enemy);
body.appendChild(aim);
Because both elements are child of body, Unless there is other styling that override this stacking, the later one should be on top.
I would like to change the position of a circle when it's parent section is scrolled into view.
While scrolling down after the parent is in view, it should move to the right and when scrolling up, it should move back to where it was originally. (-200px to the left) It should only be moved while the user is actively scrolling.
If the user scrolls all the way down to the very bottom of the circle's parent section, or if they have already scrolled down to the bottom and reload the page, the circle should appear in it's fully-revealed position.
My current code partially works, but I'm having trouble with getting the entire element to appear based on how much of the parent element is visible and also getting it to display in it's final position when reloading the page after having scrolled to the very bottom.
JSFiddle: https://jsfiddle.net/thebluehorse/gu2rvnsw/
var $window = $(window),
$sectionFour = $('.section-four'),
$circle = $sectionFour.find('.circle'),
lastScrollTop = 0,
position = -200;
function revealCircle() {
var isVisible,
st = $window.scrollTop();
isVisible = isInView($sectionFour);
if (isVisible) {
// console.log('section four is in view, so lets do stuff!');
if (st > lastScrollTop) {
if (position === 0) {
return false
}
$circle.css('transform', 'translateX(' + position + 'px')
position++;
} else {
if (position === -200) {
return false
}
$circle.css('transform', 'translateX(' + position + 'px')
position--;
}
}
}
function isInView(node) {
var rect;
if (typeof jQuery === 'function' && node instanceof jQuery) {
node = node[0];
}
rect = node.getBoundingClientRect();
return (
(rect.height > 0 || rect.width > 0) &&
rect.bottom >= 0 &&
rect.right >= 0 &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.left <= (window.innerWidth || document.documentElement.clientWidth)
);
}
$window.on('scroll', revealCircle);
.circle {
width: 400px;
height: 400px;
background: #fff;
-webkit-border-radius: 200px;
-moz-border-radius: 200px;
border-radius: 200px;
transform: translateX(-200px); }
.section {
min-height: 400px; }
.section-one {
background-color: red; }
.section-two {
background-color: orange; }
.section-three {
background-color: yellow; }
.section-four {
background-color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="section section-one"></section>
<section class="section section-two"></section>
<section class="section section-three"></section>
<section class="section section-four">
<div class="circle"></div>
</section>
Your code can be simplified a bit. The only value you need to keep track of as the page is scrolled is scrollTop(). Because the geometry of $sectionFour never changes, you can cache its getBoundingClientRect() right away.
Once you know that $sectionFour is in view, you want to figure out how many pixels of its total height are in view, convert that to a percentage, and then apply that percentage to the initial position of -200. Essentially, when only a few pixels are showing, that's a small percentage, such as 10% and -200 becomes -180. When the element is fully in view, the percentage should be near 100%, and -200 becomes 0. This means you're not keeping track of the last position or which direction the scroll was, you're just computing what the value should be based on the current viewport (scrollTop).
var $window = $(window),
$sectionFour = $('.section-four'),
$circle = $sectionFour.find('.circle');
rect = $sectionFour[0].getBoundingClientRect();
function revealCircle() {
var scrollTop = $window.scrollTop();
var windowHeight = $window[0].innerHeight;
if (scrollTop + windowHeight > rect.top) {
var percentVisible = (scrollTop - (rect.top - windowHeight)) / rect.height;
var position = 200 - (percentVisible * 200);
$circle.css('transform', 'translateX(-' + position + 'px');
}
}
$window.on('scroll', revealCircle);
body { margin:0;}
.circle {
width: 400px;
height: 400px;
background: #fff;
-webkit-border-radius: 200px;
-moz-border-radius: 200px;
border-radius: 200px;
transform: translateX(-200px); }
.section {
min-height: 400px; }
.section-one {
background-color: red; }
.section-two {
background-color: orange; }
.section-three {
background-color: yellow; }
.section-four {
background-color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="section section-one"></section>
<section class="section section-two"></section>
<section class="section section-three"></section>
<section class="section section-four">
<div class="circle"></div>
</section>
It could be more simpler to use css variables for pure JS solution :
const sectFour = document.querySelector('#section-four')
, divCircle = sectFour.querySelector('.circle')
function percentVisible(elm)
{
let rect = elm.getBoundingClientRect()
, viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight)
, visu = viewHeight-rect.top
return (visu<0) ? -1 : Math.min( 100, (visu/rect.height*100))
// return !(rect.bottom < 0 || rect.top - viewHeight >= 0) => checkVisible
}
window.onscroll=_=>
{
let circlePos = percentVisible(sectFour) *2
if (circlePos>=0)
{
divCircle.style.setProperty('--circle-pos', `-${200-circlePos}px`)
// IE 11 : // divCircle.style=('transform:translateX(-'+(200-circlePos)+'px')
}
}
* { margin: 0 }
.circle {
--circle-pos :-200px;
width : 400px;
height : 400px;
background-color : #fff;
-webkit-border-radius: 200px;
-moz-border-radius: 200px;
border-radius: 200px;
transform : translateX(var(--circle-pos));
/* IE 11 ........... : translateX(-200px); */
}
section { min-height: 400px; }
section:nth-of-type(1) { background-color: red; }
section:nth-of-type(2) { background-color: orange; }
section:nth-of-type(3) { background-color: yellow; }
section:nth-of-type(4) { background-color: green; }
<section></section>
<section></section>
<section></section>
<section id="section-four"> <div class="circle"></div> </section>
You should have a look at Intersection Observer (IO), this was designed to solve problems like yours. Listening to scroll event and calculating the position can result in bad performance.
First, you have to define the options for the IO:
let options = {
root: document.querySelectorAll('.section-four'),
rootMargin: '0px',
threshold: 1.0
}
let observer = new IntersectionObserver(callback, options);
After defining the options you have to tell the observer which elements to observe, I guess in your case this would be .section-four:
let targets = document.querySelectorAll('.section-four');
targets.forEach(target => {
observer.observe(target) }
)
Final step is to define the callback function that should be executed once .section-four is getting into view:
let callback = (entries, observer) => {
entries.forEach(entry => {
// Each entry describes an intersection change for one observed
// target element
// here you can do something like $(entry.target).find('circle') to get your circle
});
};
Have a look at this demo, depending on how much the element is visible the background-color changes. I think this comes close to your problem, you just don't change the bg-color you animate the circle inside the element.
There is also another demo on the site that displays how much of an element is visible on the screen, maybe this suits you better.
You can also use this polyfill from w3c to support older browsers.
I have been trying using jquery animate to do a running text. But I can't seems to get it run in an endless loop. It always runs one time only..
/* js: */
$(document).ready(function(){
function scroll() {
$('.scroll').animate({
right: $(document).width()
}, 8000, scroll);
}
scroll();
});
/* css: */
.scroll {
position: absolute;
right: -200px;
width: 200px;
}
<!-- html: -->
<div class="scroll">This text be scrollin'!</div>
This is the demo:
https://jsfiddle.net/y9hvr9fa/1/
Do you guys know how to fix it?
So this is what I did:
Precalculate $(document).width() as if a horizontal scroll appears, the width will change in the next iteration
Remove the width you have set for scroll so that the width is only as long as the content - and you would have to give white-space:nowrap to keep the text in a line.
In the animate use the width of the scroll text using $('.scroll').outerWidth()
See demo below and update fiddle here
$(document).ready(function() {
// initialize
var $width = $(document).width();
var $scrollWidth = $('.scroll').outerWidth();
$('.scroll').css({'right': -$scrollWidth + 'px'});
// animate
function scroll() {
$('.scroll').animate({
right: $width
}, 8000, 'linear', function() {
$('.scroll').css({'right': -$scrollWidth + 'px'});
scroll();
});
}
scroll();
});
body {
overflow: hidden;
}
.scroll {
position: absolute;
white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroll">This text be scrollin'!</div>
Let me know your feedback on this, thanks!
CSS Alternative:
Alternatively you could use a CSS transition like in this CodePen:
https://codepen.io/jamesbarnett/pen/kfmKa
More advanced:
$(document).ready(function(){
var scroller = $('#scroller'); // scroller $(Element)
var scrollerWidth = scroller.width(); // get its width
var scrollerXPos = window.innerWidth; // init position from window width
var speed = 1.5;
scroller.css('left', scrollerXPos); // set initial position
function moveLeft() {
if(scrollerXPos <= 0 - scrollerWidth) scrollerXPos = window.innerWidth;
scrollerXPos -= speed;
scroller.css('left', scrollerXPos);
window.requestAnimationFrame(moveLeft);
}
window.requestAnimationFrame(moveLeft);
});
.scroll {
display: block;
position: absolute;
overflow: visible;
white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scroller" class="scroll">This text be scrollin'!</div>
Dirty solution (my original answer):
In this example this would be a quick fix:
The text is running to the left without ever stopping. Here you will tell the text to always start at that position. (After the time has run up - meaning not necessarily just when it has left the screen)
$(document).ready(function(){
function scroll() {
$('.scroll').css('right', '-200px').animate({
right: $(document).width()
}, 8000, scroll);
}
scroll();
});
I have been trying using jquery animate to do a running text.
You know that the <marquee> HTML element works, right?
Which means you don't need CSS, Javascript or jQuery.
Pure HTML Solution:
<marquee>This text be scrollin'!</marquee>
The <marquee> element includes a large number of optional declarative attributes which control the behaviour of the scrolling text:
behavior
bgcolor
direction
height
hspace
loop
scrollamount
scrolldelay
truespeed
vspace
width
Further Reading:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/marquee
Note 1:
The resource above correctly notes that:
This feature is no longer recommended. Though some browsers might
still support it, it may have already been removed from the relevant
web standards, may be in the process of being dropped, or may only be
kept for compatibility purposes.
Note 2
The same resource also recommends:
see the compatibility table at the bottom of this page to guide your decision
And... a cursory look at that compatibility table shows that the <marquee> element is as browser-compatible as the most established, most browser-compatible elements which exist today.
I hope it is useful :)
function start() {
new mq('latest-news');
mqRotate(mqr);
}
window.onload = start;
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
var mqr = [];
function mq(id) {
this.mqo = document.getElementById(id);
var wid = objWidth(this.mqo.getElementsByTagName("span")[0]) + 5;
var fulwid = objWidth(this.mqo);
var txt = this.mqo.getElementsByTagName("span")[0].innerHTML;
this.mqo.innerHTML = "";
var heit = this.mqo.style.height;
this.mqo.onmouseout = function () {
mqRotate(mqr);
};
this.mqo.onmouseover = function () {
clearTimeout(mqr[0].TO);
};
this.mqo.ary = [];
var maxw = Math.ceil(fulwid / wid) + 1;
for (var i = 0; i < maxw; i++) {
this.mqo.ary[i] = document.createElement("div");
this.mqo.ary[i].innerHTML = txt;
this.mqo.ary[i].style.position = "absolute";
this.mqo.ary[i].style.left = wid * i + "px";
this.mqo.ary[i].style.width = wid + "px";
this.mqo.ary[i].style.height = heit;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j = mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i = 0; i < maxa; i++) {
var x = mqr[j].ary[i].style;
x.left = parseInt(x.left, 10) - 1 + "px";
}
var y = mqr[j].ary[0].style;
if (parseInt(y.left, 10) + parseInt(y.width, 10) < 0) {
var z = mqr[j].ary.shift();
z.style.left = parseInt(z.style.left) + parseInt(z.style.width) * maxa + "px";
mqr[j].ary.push(z);
}
}
mqr[0].TO = setTimeout("mqRotate(mqr)", 20);
}
.marquee {
position: relative;
overflow: hidden;
text-align: center;
margin: 0 auto;
width: 100%;
height: 30px;
display: flex;
align-items: center;
white-space: nowrap;
}
#latest-news {
line-height: 32px;
a {
color: #555555;
font-size: 13px;
font-weight: 300;
&:hover {
color: #000000;
}
}
span {
font-size: 18px;
position: relative;
top: 4px;
color: #999999;
}
}
<div id="latest-news" class="marquee">
<span style="white-space:nowrap;">
<span> •</span>
one Lorem ipsum dolor sit amet
<span> •</span>
two In publishing and graphic design
<span> •</span>
three Lorem ipsum is a placeholder text commonly
</span>
</div>
How is this?
.scroll {
height: 50px;
overflow: hidden;
position: relative;
}
.scroll p{
position: absolute;
width: 100%;
height: 100%;
margin: 0;
line-height: 50px;
text-align: center;
-moz-transform:translateX(100%);
-webkit-transform:translateX(100%);
transform:translateX(100%);
-moz-animation: scroll 8s linear infinite;
-webkit-animation: scroll 8s linear infinite;
animation: scroll 8s linear infinite;
}
#-moz-keyframes scroll {
0% { -moz-transform: translateX(100%); }
100% { -moz-transform: translateX(-100%); }
}
#-webkit-keyframes scroll {
0% { -webkit-transform: translateX(100%); }
100% { -webkit-transform: translateX(-100%); }
}
#keyframes scroll {
0% {
-moz-transform: translateX(100%);
-webkit-transform: translateX(100%);
transform: translateX(100%);
}
100% {
-moz-transform: translateX(-100%);
-webkit-transform: translateX(-100%);
transform: translateX(-100%);
}
}
<div class="scroll"><p>This text be scrollin'!</p></div>
Live example: https://jsfiddle.net/b8vLg0ny/
It's possible to use the CSS scale and translate functions to zoom into element.
Take this example, of 4 boxes in a 2x2 grid.
HTML:
<div id="container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
</div>
</div>
CSS:
* { margin: 0; }
body, html { height: 100%; }
#container {
height: 100%;
width: 50%;
margin: 0 auto;
}
#zoom-container {
height: 100%;
width: 100%;
transition: all 0.2s ease-in-out;
}
.box {
float: left;
width: 50%;
height: 50%;
color: white;
text-align: center;
display: block;
}
.red { background: red; }
.blue { background: blue; }
.green { background: green; }
.black { background: black; }
JavaScript:
window.zoomedIn = false;
$(".box").click(function(event) {
var el = this;
var zoomContainer = $("#zoom-container");
if (window.zoomedIn) {
console.log("resetting zoom");
zoomContainer.css("transform", "");
$("#container").css("overflow", "auto");
window.zoomedIn = false;
} else {
console.log("applying zoom");
var top = el.offsetTop;
var left = el.offsetLeft - 0.25*zoomContainer[0].clientWidth;
var translateY = 0.5*zoomContainer[0].clientHeight - top;
var translateX = 0.5*zoomContainer[0].clientWidth - left;
$("#container").css("overflow", "scroll");
zoomContainer.css("transform", "translate(" + 2 * translateX + "px, " + 2 * translateY + "px) scale(2)");
window.zoomedIn = true;
}
});
By controlling the value of translateX and translateY, you can change how the zooming works.
The initial rendered view looks something like this:
Clicking on the A box will zoom you in appropriately:
(Note that clicking D at the end is just showing the reset by zooming back out.)
The problem is: zooming to box D will scale the zoom container such that scrolling to the top and left doesn't work, because the contents overflow. The same happens when zooming to boxes B (the left half is cropped) and C (the top half is cropped). Only with A does the content not overflow outside the container.
In similar situations related to scaling (see CSS3 Transform Scale and Container with Overflow), one possible solution is to specify transform-origin: top left (or 0 0). Because of the way the scaling works relative to the top left, the scrolling functionality stays. That doesn't seem to work here though, because it means you're no longer repositioning the contents to be focused on the clicked box (A, B, C or D).
Another possible solution is to add a margin-left and a margin-top to the zoom container, which adds enough space to make up for the overflowed contents. But again: the translate values no longer line up.
So: is there a way to both zoom in on a given element, and overflow with a scroll so that contents aren't cropped?
Update: There's a rough almost-solution by animating scrollTop and scrollLeft, similar to https://stackoverflow.com/a/31406704/528044 (see the jsfiddle example), but it's not quite a proper solution because it first zooms to the top left, not the intended target. I'm beginning to suspect this isn't actually possible, because it's probably equivalent to asking for scrollLeft to be negative.
Why not just to reposition the TransformOrigin to 0 0 and to use proper scrollTop/scrollLeft after the animation?
https://jsfiddle.net/b8vLg0ny/7/
Updated: https://jsfiddle.net/b8vLg0ny/13/
If you do not need the animation, the TransformOrigin can always stays 0 0 and only the scrolling is used to show the box.
To make the animation less jumpy use transition only for transform porperty, otherwise the transform-origin gets animated also. I have edited the example with 4x4 elements, but I think it makes sense to zoom a box completely into view, thats why I changed the zoom level. But if you stay by zoom level 2 and the grid size 15x15 for instance, then with this approach really precise origin should be calculated for transform, and then also the correct scrolling.
Anyway I don't know, if you find this approach useful.
Stack snippet
var zoomedIn = false;
var zoomContainer = $("#zoom-container");
$(".box").click(function(event) {
var el = this;
if (zoomedIn) {
zoomContainer.css({
transform: "scale(1)",
transformOrigin: "0 0"
});
zoomContainer.parent().scrollTop(0).scrollLeft(0);
zoomedIn = false;
return;
}
zoomedIn = true;
var $el = $(el);
animate($el);
zoomContainer.on('transitionend', function(){
zoomContainer.off('transitionend');
reposition($el);
})
});
var COLS = 4, ROWS = 4,
COLS_STEP = 100 / (COLS - 1), ROWS_STEP = 100 / (ROWS - 1),
ZOOM = 4;
function animate($box) {
var cell = getCell($box);
var col = cell.col * COLS_STEP + '%',
row = cell.row * ROWS_STEP + '%';
zoomContainer.parent().css('overflow', 'hidden');
zoomContainer.css({
transition: 'transform 0.2s ease-in-out',
transform: "scale(" + ZOOM + ")",
transformOrigin: col + " " + row
});
}
function reposition($box) {
zoomContainer.css({
transition: 'none',
transform: "scale(" + ZOOM + ")",
transformOrigin: '0 0'
});
zoomContainer.parent().css('overflow', 'auto');
$box.get(0).scrollIntoView();
}
function getCell ($box) {
var idx = $box.index();
var col = idx % COLS,
row = (idx / ROWS) | 0;
return { col: col, row: row };
}
* { margin: 0; }
body, html { height: 100%; }
#container {
height: 100%;
width: 50%;
margin: 0 auto;
overflow: hidden;
}
#zoom-container {
height: 100%;
width: 100%;
will-change: transform;
}
.box {
float: left;
width: 25%;
height: 25%;
color: white;
text-align: center;
}
.red { background: red; }
.blue { background: blue; }
.green { background: green; }
.black { background: black; }
.l { opacity: .3 }
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
<div class="box red l">E</div>
<div class="box blue l">F</div>
<div class="box green l">G</div>
<div class="box black l">H</div>
<div class="box red">I</div>
<div class="box blue">J</div>
<div class="box green">K</div>
<div class="box black">L</div>
<div class="box red l">M</div>
<div class="box blue l">N</div>
<div class="box green l">O</div>
<div class="box black l">P</div>
</div>
</div>
I'm answering my own question, since I'm fairly confident that it's actually not possible with the given requirements. At least not without some hackery that would cause problems visually, e.g., jumpy scrolling by animating scrollTop after switching transform-origin to 0, 0 (which removes the cropping by bringing everything back into the container).
I'd love for someone to prove me wrong, but it seems equivalent to asking for scrollLeft = -10, something that MDN will tell you is not possible. ("If set to a value less than 0 [...], scrollLeft is set to 0.")
If, however, it's acceptable to change the UI from scrolling, to zooming and dragging/panning, then it's achievable: https://jsfiddle.net/jegn4x0f/5/
Here's the solution with the same context as my original problem:
HTML:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<button id="zoom-out">Zoom out</button>
<div id="container">
<div id="inner-container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
</div>
</div>
</div>
JavaScript:
//
// credit for the approach goes to
//
// https://stackoverflow.com/questions/35252249/move-drag-pan-and-zoom-object-image-or-div-in-pure-js#comment58224460_35253567
//
// and the corresponding example:
//
// https://jsfiddle.net/j8kLz6wm/1/
//
// in a real-world setting, you
// wouldn't keep this information
// on window. this is just for
// the demonstration.
window.zoomedIn = false;
// stores the initial translate values after clicking on a box
window.translateY = null;
window.translateX = null;
// stores the incremental translate values based on
// applying the initial translate values + delta
window.lastTranslateY = null;
window.lastTranslateX = null;
// cursor position relative to the container, at
// the time the drag started
window.dragStartX = null;
window.dragStartY = null;
var handleDragStart = function(element, xCursor, yCursor) {
window.dragStartX = xCursor - element.offsetLeft;
window.dragStartY = yCursor - element.offsetTop;
// disable transition animations, since we're starting a drag
$("#zoom-container").css("transition", "none");
};
var handleDragEnd = function() {
window.dragStartX = null;
window.dragStartY = null;
// remove the individual element's styling for transitions
// which brings back the stylesheet's default of animating.
$("#zoom-container").css("transition", "");
// keep track of the translate values we arrived at
window.translateY = window.lastTranslateY;
window.translateX = window.lastTranslateX;
};
var handleDragMove = function(xCursor, yCursor) {
var deltaX = xCursor - window.dragStartX;
var deltaY = yCursor - window.dragStartY;
var translateY = window.translateY + (deltaY / 2);
// the subtracted value here is to keep the letter in the center
var translateX = window.translateX + (deltaX / 2) - (0.25 * $("#inner-container")[0].clientWidth);
// fudge factor, probably because of percentage
// width/height problems. couldn't really trace down
// the underlying cause. hopefully the general approach
// is clear, though.
translateY -= 9;
translateX -= 4;
var innerContainer = $("#inner-container")[0];
// cap all values to prevent infinity scrolling off the page
if (translateY > 0.5 * innerContainer.clientHeight) {
translateY = 0.5 * innerContainer.clientHeight;
}
if (translateX > 0.5 * innerContainer.clientWidth) {
translateX = 0.5 * innerContainer.clientWidth;
}
if (translateY < -0.5 * innerContainer.clientHeight) {
translateY = -0.5 * innerContainer.clientHeight;
}
if (translateX < -0.5 * innerContainer.clientWidth) {
translateX = -0.5 * innerContainer.clientWidth;
}
// update the zoom container's translate values
// based on the original + delta, capped to the
// container's width and height.
$("#zoom-container").css("transform", "translate(" + (2*translateX) + "px, " + (2*translateY) + "px) scale(2)");
// keep track of the updated values for the next
// touchmove event.
window.lastTranslateX = translateX;
window.lastTranslateY = translateY;
};
// Drag start -- touch version
$("#container").on("touchstart", function(event) {
if (!window.zoomedIn) {
return true;
}
var xCursor = event.originalEvent.changedTouches[0].clientX;
var yCursor = event.originalEvent.changedTouches[0].clientY;
handleDragStart(this, xCursor, yCursor);
});
// Drag start -- mouse version
$("#container").on("mousedown", function(event) {
if (!window.zoomedIn) {
return true;
}
var xCursor = event.clientX;
var yCursor = event.clientY;
handleDragStart(this, xCursor, yCursor);
});
// Drag end -- touch version
$("#inner-container").on("touchend", function(event) {
if (!window.zoomedIn) {
return true;
}
handleDragEnd();
});
// Drag end -- mouse version
$("#inner-container").on("mouseup", function(event) {
if (!window.zoomedIn) {
return true;
}
handleDragEnd();
});
// Drag move -- touch version
$("#inner-container").on("touchmove", function(event) {
// prevent pull-to-refresh. could be smarter by checking
// if the page's scroll y-offset is 0, and even smarter
// by checking if we're pulling down, not up.
event.preventDefault();
if (!window.zoomedIn) {
return true;
}
var xCursor = event.originalEvent.changedTouches[0].clientX;
var yCursor = event.originalEvent.changedTouches[0].clientY;
handleDragMove(xCursor, yCursor);
});
// Drag move -- click version
$("#inner-container").on("mousemove", function(event) {
// prevent pull-to-refresh. could be smarter by checking
// if the page's scroll y-offset is 0, and even smarter
// by checking if we're pulling down, not up.
event.preventDefault();
// if we aren't dragging from anywhere, don't move
if (!window.zoomedIn || !window.dragStartX) {
return true;
}
var xCursor = event.clientX;
var yCursor = event.clientY;
handleDragMove(xCursor, yCursor);
});
var zoomInTo = function(element) {
console.log("applying zoom");
var top = element.offsetTop;
// the subtracted value here is to keep the letter in the center
var left = element.offsetLeft - (0.25 * $("#inner-container")[0].clientWidth);
var translateY = 0.5 * $("#zoom-container")[0].clientHeight - top;
var translateX = 0.5 * $("#zoom-container")[0].clientWidth - left;
$("#container").css("overflow", "scroll");
$("#zoom-container").css("transform", "translate(" + (2*translateX) + "px, " + (2*translateY) + "px) scale(2)");
window.translateY = translateY;
window.translateX = translateX;
window.zoomedIn = true;
}
var zoomOut = function() {
console.log("resetting zoom");
window.zoomedIn = false;
$("#zoom-container").css("transform", "");
$("#zoom-container").css("transition", "");
window.dragStartX = null;
window.dragStartY = null;
window.dragMoveJustHappened = null;
window.translateY = window.lastTranslateY;
window.translateX = window.lastTranslateX;
window.lastTranslateX = null;
window.lastTranslateY = null;
}
$(".box").click(function(event) {
var element = this;
var zoomContainer = $("#zoom-container");
if (!window.zoomedIn) {
zoomInTo(element);
}
});
$("#zoom-out").click(function(event) {
zoomOut();
});
CSS:
* {
margin: 0;
}
body,
html {
height: 100%;
}
#container {
height: 100%;
width: 50%;
margin: 0 auto;
}
#inner-container {
width: 100%;
height: 100%;
}
#zoom-container {
height: 100%;
width: 100%;
transition: transform 0.2s ease-in-out;
}
.box {
float: left;
width: 50%;
height: 50%;
color: white;
text-align: center;
display: block;
}
.red {
background: red;
}
.blue {
background: blue;
}
.green {
background: green;
}
.black {
background: black;
}
I pieced this together from another question (Move (drag/pan) and zoom object (image or div) in pure js), where the width and height are being changed. That doesn't quite apply in my case, because I need to zoom into a specific element on the page (with a lot boxes than in a 2x2 grid). The solution from that question (https://jsfiddle.net/j8kLz6wm/1/) shows the basic approach in pure JavaScript. If you have jQuery available, you can probably just use jquery.panzoom.
Update
I got stuck on scroll bars not showing all the time, so I need to investigating that part, so that code is commented out and instead I use a delay to move the clicked box into view.
Here is my fiddle demo, which I use to play with, to figure out how to solve the scroll bar issue.
Side note: In a comment made by #AVAVT, I would like to link to his post here, as that might help someone else, which I find as an interesting alternative in some cases.
(function(zoomed) {
$(".box").click(function(event) {
var el = this, elp = el.parentElement;
if (zoomed) {
zoomed = false;
$("#zoom-container").css({'transform': ''});
} else {
zoomed = true;
/* this zooms correct but show 1 or none scroll for B,C,D so need to figure out why
var tro = (Math.abs(elp.offsetTop - el.offsetTop) > 0) ? 'bottom' : 'top';
tro += (Math.abs(elp.offsetLeft - el.offsetLeft) > 0) ? ' right' : ' left';
$("#zoom-container").css({'transform-origin': tro, 'transform': 'scale(2)'});
*/
$("#zoom-container").css({'transform-origin': '0 0', 'transform': 'scale(2)'});
/* delay needed before scroll into view */
setTimeout(function() {
el.scrollIntoView();
},250);
}
});
})();
* { margin: 0; }
body, html { height: 100%; }
#container {
height: 100%;
width: 50%;
overflow: auto;
margin: 0 auto;
}
#zoom-container {
height: 100%;
width: 100%;
transition: all 0.2s ease-in-out;
}
.box {
float: left;
width: 50%;
height: 50%;
color: white;
text-align: center;
display: block;
}
.red {
background: red;
}
.blue {
background: blue;
}
.green {
background: green;
}
.black {
background: black;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
</div>
</div>
Here is my JsFiddle
I want to apply background-color change property to circle when the window slides. Like in the beginning only first circle will have background-color. and when the images slides to second screen the second circle will have only color.
Can anybody guide me how to achieve that.
JQuery:
$(document).ready(function () {
setInterval(function () {
var A = $('.gallery').scrollLeft();
if (A < 993) {
$('.gallery').animate({
scrollLeft: '+=331px'
}, 300);
}
if (A >= 993) {
$('.gallery').delay(400).animate({
scrollLeft: 0
}, 300);
}
}, 3000);
});
Here's a simple solution of your problem: http://jsfiddle.net/pjvCw/44/ but....
The way you're doing galleries is quite wrong.
You have a really sensitive CSS full of margin bugs (see in CSS code),
you calculate all by hand, which will just complicate your life one day if you'll get to add images, change widths etc...
Your buttons are positioned really wrongly, and again you don't even need to manually add them in your HTML. Let jQuery do all the job for you:
Calculate margins, widths,
Get the number of slides
generate buttons,
Make your buttons clickable
Pause gallery on mouseenter (loop again on mouseleave)
LIVE DEMO
This is the way you should go with your slider:
HTML:
<div class="galleryContainer"> <!-- Note this main 'wrapper' -->
<div class="gallery">
<div class="row">
<!-- ..your images.. -->
</div>
<div class="row">
<!-- ..your images.. -->
</div>
</div>
<div class="content-nav-control"></div> <!-- Let jQ create the buttons -->
</div>
Note the general gallery wrapper, it allows you with this CSS to make your buttons parent not move with the gallery.
CSS:
In your code, using display:inline-block; adds 4px margin to your elements, ruining your math. So you just need to apply font-size:0; to remove that inconvenience.
As soon I did that the math was working and the right width was than 340px, having 5px border for your images and 20px margin.
.galleryContainer{
/* you need that one
// to prevent the navigation move */
position:relative; /* cause .content-nav-control is absolute */
background-color: #abcdef;
width:340px; /* (instead of 350) now the math will work */
height: 265px;
}
.gallery{
position:relative;
overflow: hidden; /* "overflow" is enough */
width:340px; /* (instead of 350) now the math will work */
height: 265px;
}
.gallery .row {
white-space: nowrap;
font-size:0; /* prevent inline-block 4px margin issue */
}
.gallery img {
display: inline-block;
margin-left: 20px;
margin-top: 20px;
}
.normalimage {
height: 80px;
width: 50px;
border: 5px solid black;
}
.wideimage {
height: 80px;
width: 130px;
border: 5px solid black;
}
img:last-of-type {
margin-right:20px;
}
.content-nav-control {
position: absolute;
width:100%; /* cause it's absolute */
bottom:10px;
text-align:center; /* cause of inline-block buttons inside*/
font-size:0; /* same trick as above */
}
.content-nav-control > span {
cursor:pointer;
width: 20px;
height: 20px;
display: inline-block;
border-radius: 50%;
border:1px solid #000;
box-shadow: inset 0 0 6px 2px rgba(0,0,0,.75);
margin: 0 2px; /* BOTH MARGINS LEFT AND RIGHT */
}
.content-nav-control > span.active{
background:blue;
}
And finally:
$(function () { // DOM ready shorty
var $gal = $('.gallery'),
$nav = $('.content-nav-control'),
galSW = $gal[0].scrollWidth, // scrollable width
imgM = parseInt($gal.find('img').css('marginLeft'), 10), // 20px
galW = $gal.width() - imgM, // - one Margin
n = Math.round(galSW/galW), // n of slides
c = 0, // counter
galIntv; // the interval
for(var i=0; i<n; i++){
$nav.append('<span />'); // Create circles
}
var $btn = $nav.find('span');
$btn.eq(c).addClass('active');
function anim(){
$btn.removeClass('active').eq(c).addClass('active');
$gal.stop().animate({scrollLeft: galW*c }, 400);
}
function loop(){
galIntv = setInterval(function(){
c = ++c%n;
anim();
}, 3000);
}
loop(); // first start kick
// MAKE BUTTONS CLICKABLE
$nav.on('click', 'span', function(){
c = $(this).index();
anim();
});
// PAUSE ON GALLERY MOUSEENTER
$gal.parent('.galleryContainer').hover(function( e ){
return e.type=='mouseenter' ? clearInterval(galIntv) : loop() ;
});
});
"- With this solution, What can I do now and in the future? -"
Nothing! just freely add images into your HTML and play, and never again have to take a look at your backyard :)
Try this: http://jsfiddle.net/yerdW/1/
I added a line that gets the scrollLeft and divides it by your width (331px) to get the position and use that to select the 'active' circle:
$(".circle").removeClass("coloured");
position = Math.ceil($(".gallery").scrollLeft()/331 + 2);
if(position > $(".circle").length){
position = 1; // yes...
}
$(".content-nav-control div:nth-child("+position+")").addClass("coloured");
Red background for active circle:
.coloured {
background : red;
}
Note that you should initialise with the first circle already having the .coloured class applied.
Here you go: http://jsfiddle.net/pjvCw/41/
i added new class
.selected
{
background-color: red;
}
and modified some js code
Here is your jsfiddle edited http://jsfiddle.net/pjvCw/45/
var scrolled = 0;
var circles = $(".circle");
var colorCircle = function(index) {
for(var i=0; i<circles.length; i++) {
if(i == index) {
circles.eq(i).css("background-color", "rgba(255, 0, 0, 1)");
} else {
circles.eq(i).css("background-color", "rgba(255, 0, 0, 0)");
}
}
}
$(document).ready(function () {
setInterval(function () {
var A = $('.gallery').scrollLeft();
if (A < 993) {
$('.gallery').animate({
scrollLeft: '+=331px'
}, 300);
colorCircle(++scrolled);
}
if (A >= 993) {
$('.gallery').delay(400).animate({
scrollLeft: 0
}, 300);
colorCircle(scrolled = 0);
}
}, 3000);
colorCircle(0);
});
I added a transition to the .circle class, so it looks a little bit better:
.circle {
width: 20px;
height: 20px;
display: inline-block;
border-radius: 50%;
border:1px solid #000;
box-shadow: inset 0 0 6px 2px rgba(0,0,0,.75);
margin-right: 5px;
transition: background-color 700ms;
-webkit-transition: background-color 700ms;
}