How to switch between transform-origin and scrollbars - javascript

I have this code above who switch between CSS transform-origin and scale to CSS width and scrollbars.
I need to make this switch because I am having a pinch to zoom for a DIV wrap I'm using in my website.
I'm using CSS translateX and translateY and Scale for a smoother pinch zoom, but after the zoom take place, I need to return back to width and scrollbar so the user can move across the layout.
I have here an example of how I'm doing the switch and there is a bit margin on top that I can't really set mind my on.
what is the correct way to do so?
var isOrigin = false;
var originX = 500;
var originY = 200;
var scale = 1.5;
var deltaX = 0;
var deltaY = 0;
var from_origin_to_scroll = function () {
if (isOrigin) { from_scroll_to_origin(); return; }
var wrap = $('.containter .wrap');
//reset scroll
const el = document.scrollingElement || document.documentElement;
$('.containter')[0].scrollLeft = 0;
el.scrollTop = 0;
wrap.css({
transformOrigin: originX + "px " + originY + "px",
transform: "translate3d(" + deltaX + "px," + deltaY + "px, 0) " +
"scale3d(" + scale + "," + scale + ", 1) ",
width: 100 + '%'
});
isOrigin = true;
$('.info').html('layout set by origin and scale');
}
var from_scroll_to_origin = function () {
var wrap = $('.containter .wrap');
wrap.css({
transformOrigin: originX + "px " + originY + "px",
transform: "translate3d(" + 0 + "px," + 0 + "px, 0) " +
"scale3d(" + 1 + "," + 1 + ", 1) ",
width: (100 * scale) + '%'
});
$('.containter')[0].scrollLeft = originX * (scale - 1);
const el = document.scrollingElement || document.documentElement;
el.scrollTop = originY * (scale - 1);
isOrigin = false;
$('.info').html('layout set by width and scroll');
}
body {
margin: 0;
padding: 0;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
width:100vw;
}
.top{
position: fixed;
width: 100%;
background-color: #333;
line-height: 40pt;
text-align: center;
color: #f1f1f1;
font-size: 20pt;
left: 0;
top: 0;
z-index: 10;
}
.top .info{
}
.header_content
{
background-color: #e1e1e1;
line-height:130pt;
}
.containter {
width:100%;
box-sizing: border-box;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
.containter .wrap {
display: flex;
flex-direction: column;
width: 100%;
}
.containter .wrap img {
width: 100%;
margin-top: 30pt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top">
<div class="info" onclick="from_origin_to_scroll()">click to switch</div>
</div>
<div class="header_content">
this is a header content - needs to be added to overall calculation
</div>
<div class="containter">
<div class="wrap">
<img src="https://thumb7.shutterstock.com/display_pic_with_logo/91858/594887747/stock-photo-dreams-of-travel-child-flying-on-a-suitcase-against-the-backdrop-of-sunset-594887747.jpg" />
<img src="https://thumb9.shutterstock.com/display_pic_with_logo/1020994/556702975/stock-photo-portrait-of-a-happy-and-proud-pregnant-woman-looking-at-her-belly-in-a-park-at-sunrise-with-a-warm-556702975.jpg" />
<img src="https://thumb7.shutterstock.com/display_pic_with_logo/234100/599187701/stock-photo-funny-little-girl-plays-super-hero-over-blue-sky-background-superhero-concept-599187701.jpg" />
<img src="https://thumb1.shutterstock.com/display_pic_with_logo/1316512/661476343/stock-photo-funny-pineapple-in-sunglasses-near-swimming-pool-661476343.jpg" />
<img src="https://thumb1.shutterstock.com/display_pic_with_logo/2114402/689953639/stock-photo-adult-son-hugging-his-old-father-against-cloudy-sky-with-sunshine-689953639.jpg" />
<img src="https://thumb7.shutterstock.com/display_pic_with_logo/172762/705978841/stock-photo-businessman-looking-to-the-future-for-new-business-opportunity-705978841.jpg" />
</div>
</div>

In your case the possible solution is to detect when the user is trying to zoom, and when just to scroll.
const $container = $(".container");
$container.on('touchstart', function (e) {
if (e.touches.length > 1){
//more than one finger is detected on the screen,
//change mode to transform-origin
from_scroll_to_origin()
}
});
$container.on('touchend', function (e) {
//change mode to scrollbars
from_origin_to_scroll()
});

Related

Slider handle needs to restricted inside the container, should not go beyond the container

In the custom slider i have created, the handle is moving beyond the container. But i want it to stay within the container limits. We could just do it simple by setting margin-left as offset in CSS. But My requirement is when the handle right end detect the container's end the handle should not be allowed to move anymore. Any help is appreciated. Thanks.
Demo Link: https://jsfiddle.net/mohanravi/1pbzdyyd/30/
document.getElementsByClassName('contain')[0].addEventListener("mousedown", downHandle);
function downHandle() {
document.addEventListener("mousemove", moveHandle);
document.addEventListener("mouseup", upHandle);
}
function moveHandle(e) {
var left = e.clientX - document.getElementsByClassName('contain')[0].getBoundingClientRect().left;
var num = document.getElementsByClassName('contain')[0].offsetWidth / 100;
var val = (left / num);
if (val < 0) {
val = 0;
} else if (val > 100) {
val = 100;
}
var pos = document.getElementsByClassName('contain')[0].getBoundingClientRect().width * (val / 100);
document.getElementsByClassName('bar')[0].style.left = pos + 'px';
}
function upHandle() {
document.removeEventListener("mousemove", moveHandle);
document.removeEventListener("mouseup", upHandle);
}
.contain {
height: 4px;
width: 450px;
background: grey;
position: relative;
top: 50px;
left: 40px;
}
.bar {
width: 90px;
height: 12px;
background: transparent;
border: 1px solid red;
position: absolute;
top: calc(50% - 7px);
left: 0px;
cursor: ew-resize;
}
<div class='contain'>
<div class='bar'></div>
</div>
You need to change
this
document.getElementsByClassName('bar')[0].style.left = pos + 'px';
to this
if(pos > 90){
document.getElementsByClassName('bar')[0].style.left = pos - 90 + 'px';
}
else{
document.getElementsByClassName('bar')[0].style.left = 0 + 'px';
}
since width of your bar is 90px I am subtracting 90.
See this updated fiddle

Add span to page at the cursor position

I have the following JavaScript, I am trying to insert the span at where ever the cursor position is in the div.
var appendPlaceHolder = function (field) {
var e = document.getElementById("t");
e.innerHTML += (' <span class="nonEditable tags">{' + field + '} <span onclick=removePlaceholder(this) class="testing"></span>x</span> ');
}
<div id="t" contenteditable="true">
Hello
</div>
How do I go about doing it?
Here is an old script I've written.Hope it helps.
continent is the mouse entered div, tooltipOutput
function continentTooltip(continent, tooltipOutput) {
var tooltip = $('.map__tooltip');
$(continent).mouseenter(function() {
$(document).off('mousemove').bind('mousemove', function(e){
var positionX = (e.pageX + 20) + 'px';
var positionY = e.pageY + 'px';
$('.map__tooltip').css(
"transform" , 'translate(' + positionX + ', ' + positionY + ')'
);
});
tooltip.addClass('map__tooltip--show');
tooltip.text(tooltipOutput)
})
$(continent).mouseleave(function() {
tooltip.removeClass('map__tooltip--show');
});
}
//call script
continentTooltip(africa, 'Vacations in Africa');
HTML:
<div class="map__tooltip"></div>
CSS:
.map__tooltip {
display: none;
background-color: #FFF;
border-radius: $radius;
padding: 4px;
position: absolute;
top: 0;
left: 0;
}
.map__tooltip--show {
display: block;
}
#media screen and (max-width: 1300px) {
.map__tooltip--show {
display: none;
}
}

Center div Vertical/Horizontal without flexbox

/**
* tiltfx.js
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2015, Codrops
* http://www.codrops.com
*/
;
(function(window) {
'use strict';
/**
* **************************************************************************
* utils
* **************************************************************************
*/
// from https://gist.github.com/desandro/1866474
var lastTime = 0;
var prefixes = 'webkit moz ms o'.split(' ');
// get unprefixed rAF and cAF, if present
var requestAnimationFrame = window.requestAnimationFrame;
var cancelAnimationFrame = window.cancelAnimationFrame;
// loop through vendor prefixes and get prefixed rAF and cAF
var prefix;
for (var i = 0; i < prefixes.length; i++) {
if (requestAnimationFrame && cancelAnimationFrame) {
break;
}
prefix = prefixes[i];
requestAnimationFrame = requestAnimationFrame || window[prefix + 'RequestAnimationFrame'];
cancelAnimationFrame = cancelAnimationFrame || window[prefix + 'CancelAnimationFrame'] ||
window[prefix + 'CancelRequestAnimationFrame'];
}
// fallback to setTimeout and clearTimeout if either request/cancel is not supported
if (!requestAnimationFrame || !cancelAnimationFrame) {
requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
cancelAnimationFrame = function(id) {
window.clearTimeout(id);
};
}
function extend(a, b) {
for (var key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
}
}
return a;
}
// from http://www.quirksmode.org/js/events_properties.html#position
function getMousePos(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
} else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
return {
x: posx,
y: posy
}
}
// from http://www.sberry.me/articles/javascript-event-throttling-debouncing
function throttle(fn, delay) {
var allowSample = true;
return function(e) {
if (allowSample) {
allowSample = false;
setTimeout(function() {
allowSample = true;
}, delay);
fn(e);
}
};
}
/***************************************************************************/
/**
* TiltFx fn
*/
function TiltFx(el, options) {
this.el = el;
this.options = extend({}, this.options);
extend(this.options, options);
this._init();
this._initEvents();
}
/**
* TiltFx options.
*/
TiltFx.prototype.options = {
// number of extra image elements (div with background-image) to add to the DOM - min:1, max:5 (for a higher number, it's recommended to remove the transitions of .tilt__front in the stylesheet.
extraImgs: 2,
// the opacity value for all the image elements.
opacity: 0.7,
// by default the first layer does not move.
bgfixed: true,
// image element's movement configuration
movement: {
perspective: 1000, // perspective value
translateX: -10, // a relative movement of -10px to 10px on the x-axis (setting a negative value reverses the direction)
translateY: -10, // a relative movement of -10px to 10px on the y-axis
translateZ: 20, // a relative movement of -20px to 20px on the z-axis (perspective value must be set). Also, this specific translation is done when the mouse moves vertically.
rotateX: 2, // a relative rotation of -2deg to 2deg on the x-axis (perspective value must be set)
rotateY: 2, // a relative rotation of -2deg to 2deg on the y-axis (perspective value must be set)
rotateZ: 0 // z-axis rotation; by default there's no rotation on the z-axis (perspective value must be set)
}
}
/**
* Initialize: build the necessary structure for the image elements and replace it with the HTML img element.
*/
TiltFx.prototype._init = function() {
this.tiltWrapper = document.createElement('div');
this.tiltWrapper.className = 'tilt';
// main image element.
this.tiltImgBack = document.createElement('div');
this.tiltImgBack.className = 'tilt__back';
this.tiltImgBack.style.backgroundImage = 'url(' + this.el.src + ')';
this.tiltWrapper.appendChild(this.tiltImgBack);
// image elements limit.
if (this.options.extraImgs < 1) {
this.options.extraImgs = 1;
} else if (this.options.extraImgs > 5) {
this.options.extraImgs = 5;
}
if (!this.options.movement.perspective) {
this.options.movement.perspective = 0;
}
// add the extra image elements.
this.imgElems = [];
for (var i = 0; i < this.options.extraImgs; ++i) {
var el = document.createElement('div');
el.className = 'tilt__front';
el.style.backgroundImage = 'url(' + this.el.src + ')';
el.style.opacity = this.options.opacity;
this.tiltWrapper.appendChild(el);
this.imgElems.push(el);
}
if (!this.options.bgfixed) {
this.imgElems.push(this.tiltImgBack);
++this.options.extraImgs;
}
// add it to the DOM and remove original img element.
this.el.parentNode.insertBefore(this.tiltWrapper, this.el);
this.el.parentNode.removeChild(this.el);
// tiltWrapper properties: width/height/left/top
this.view = {
width: this.tiltWrapper.offsetWidth,
height: this.tiltWrapper.offsetHeight
};
};
/**
* Initialize the events on the main wrapper.
*/
TiltFx.prototype._initEvents = function() {
var self = this,
moveOpts = self.options.movement;
// mousemove event..
this.tiltWrapper.addEventListener('mousemove', function(ev) {
requestAnimationFrame(function() {
// mouse position relative to the document.
var mousepos = getMousePos(ev),
// document scrolls.
docScrolls = {
left: document.body.scrollLeft + document.documentElement.scrollLeft,
top: document.body.scrollTop + document.documentElement.scrollTop
},
bounds = self.tiltWrapper.getBoundingClientRect(),
// mouse position relative to the main element (tiltWrapper).
relmousepos = {
x: mousepos.x - bounds.left - docScrolls.left,
y: mousepos.y - bounds.top - docScrolls.top
};
// configure the movement for each image element.
for (var i = 0, len = self.imgElems.length; i < len; ++i) {
var el = self.imgElems[i],
rotX = moveOpts.rotateX ? 2 * ((i + 1) * moveOpts.rotateX / self.options.extraImgs) / self.view.height * relmousepos.y - ((i + 1) * moveOpts.rotateX / self.options.extraImgs) : 0,
rotY = moveOpts.rotateY ? 2 * ((i + 1) * moveOpts.rotateY / self.options.extraImgs) / self.view.width * relmousepos.x - ((i + 1) * moveOpts.rotateY / self.options.extraImgs) : 0,
rotZ = moveOpts.rotateZ ? 2 * ((i + 1) * moveOpts.rotateZ / self.options.extraImgs) / self.view.width * relmousepos.x - ((i + 1) * moveOpts.rotateZ / self.options.extraImgs) : 0,
transX = moveOpts.translateX ? 2 * ((i + 1) * moveOpts.translateX / self.options.extraImgs) / self.view.width * relmousepos.x - ((i + 1) * moveOpts.translateX / self.options.extraImgs) : 0,
transY = moveOpts.translateY ? 2 * ((i + 1) * moveOpts.translateY / self.options.extraImgs) / self.view.height * relmousepos.y - ((i + 1) * moveOpts.translateY / self.options.extraImgs) : 0,
transZ = moveOpts.translateZ ? 2 * ((i + 1) * moveOpts.translateZ / self.options.extraImgs) / self.view.height * relmousepos.y - ((i + 1) * moveOpts.translateZ / self.options.extraImgs) : 0;
el.style.WebkitTransform = 'perspective(' + moveOpts.perspective + 'px) translate3d(' + transX + 'px,' + transY + 'px,' + transZ + 'px) rotate3d(1,0,0,' + rotX + 'deg) rotate3d(0,1,0,' + rotY + 'deg) rotate3d(0,0,1,' + rotZ + 'deg)';
el.style.transform = 'perspective(' + moveOpts.perspective + 'px) translate3d(' + transX + 'px,' + transY + 'px,' + transZ + 'px) rotate3d(1,0,0,' + rotX + 'deg) rotate3d(0,1,0,' + rotY + 'deg) rotate3d(0,0,1,' + rotZ + 'deg)';
}
});
});
// reset all when mouse leaves the main wrapper.
this.tiltWrapper.addEventListener('mouseleave', function(ev) {
setTimeout(function() {
for (var i = 0, len = self.imgElems.length; i < len; ++i) {
var el = self.imgElems[i];
el.style.WebkitTransform = 'perspective(' + moveOpts.perspective + 'px) translate3d(0,0,0) rotate3d(1,1,1,0deg)';
el.style.transform = 'perspective(' + moveOpts.perspective + 'px) translate3d(0,0,0) rotate3d(1,1,1,0deg)';
}
}, 60);
});
// window resize
window.addEventListener('resize', throttle(function(ev) {
// recalculate tiltWrapper properties: width/height/left/top
self.view = {
width: self.tiltWrapper.offsetWidth,
height: self.tiltWrapper.offsetHeight
};
}, 50));
};
function init() {
// search for imgs with the class "tilt-effect"
[].slice.call(document.querySelectorAll('img.tilt-effect')).forEach(function(img) {
new TiltFx(img, JSON.parse(img.getAttribute('data-tilt-options')));
});
}
init();
window.TiltFx = TiltFx;
})(window);
.tilt {
overflow: hidden;
position: relative;
width: 100%;
height: 100%;
margin: 0 auto;
}
.tilt__back {
position: relative;
}
.tilt__front {
position: absolute;
top: 0;
left: 0;
}
.tilt__back,
.tilt__front {
width: 100%;
height: 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
<div class="megawrapper">
<div class="w-section home-page" style="transform: translateX(0px) translateY(0px);">
<div class="home_logo" style="pointer-events:none;"></div>
<div class="home_centralarea" data-ix="home-darkfield" style="opacity: 1; transition: opacity 500ms;">
<div class="home_parallaxpic_wrapper">
<div class="home_parallaxpic" data-ix="home-parallaxpic" style="opacity: 0.4; transition: opacity 1000ms;">
<img class="hero__img tilt-effect" data-tilt-options='{ "extraImgs":3, "bgfixed":false, "opacity" : 0.5, "movement": { "perspective" : 1200, "translateX" : -5, "translateY" : -5, "rotateX" : -5, "rotateY" : -5 } }' src="<?php echo get_template_directory_uri(); ?>/images/road.jpeg"
/>
</div>
</div>
</div>
</div>
</div>
I want to replicate HTML structure of this website (www.danielspatzek.com/). But I cant get my divs to center properly. The website has two main divs, .home-page which contains the fully stretched background image and .tilt which injects the tiltfx effect on the background image. The div .tilt has a scaled down height/width due to a padding of 60px applied on it by its parent div .home-page
I replicated the HTML structure but when I apply the 60px padding in .home-page all divs get pushed right/down and is no longer centered.
The original website html is:
<div class="megawrapper">
<div class="w-section home-page" style="transform: translateX(0px) translateY(0px);">
<div class="home_logo" style="pointer-events:none;"></div>
<div class="home_centralarea" data-ix="home-darkfield" style="opacity: 1; transition: opacity 500ms;">
<div class="home_parallaxpic_wrapper">
<div class="home_parallaxpic" data-ix="home-parallaxpic" style="opacity: 0.4; transition: opacity 1000ms;">
<img class="hero__img tilt-effect" data-tilt-options='{ "extraImgs":3, "bgfixed":false, "opacity" : 0.5, "movement": { "perspective" : 1200, "translateX" : -5, "translateY" : -5, "rotateX" : -5, "rotateY" : -5 } }' src="<?php echo get_template_directory_uri(); ?>/images/road.jpeg" />
</div>
</div>
</div>
</div>
</div>
The javascript file tiltfx.js removes .tilt-effect and replaces it with .tilt so the HTML is:
<div class="megawrapper">
<div class="w-section home-page" style="transform: translateX(0px) translateY(0px);">
<div class="home_logo" style="pointer-events:none;"></div>
<div class="home_centralarea" data-ix="home-darkfield" style="opacity: 1; transition: opacity 0ms;">
<div class="home_parallaxpic_wrapper">
<div class="home_parallaxpic" data-ix="home-parallaxpic" style="opacity: 0.4; transition: opacity 0ms;">
<div class="tilt"><div class="tilt__back" style="background-image: url("http://www.danielspatzek.com/themes/Theme/images/bg_home_street.jpg"); transform: perspective(1200px) translate3d(0.787151px, -0.0129973px, 0px) rotate3d(1, 0, 0, -0.0129973deg) rotate3d(0, 1, 0, 0.787151deg) rotate3d(0, 0, 1, 0deg);"></div>
</div>
</div>
</div>
</div>
My recreation HTML and CSS looks like this:
<div class="megawrapper">
<div class="home-page" style="transform: translateX(0px) translateY(0px);">
<img class="tilt-effect" data-tilt-options='{ "extraImgs":3, "bgfixed":false, "opacity" : 0.5, "movement": { "perspective" : 1200, "translateX" : -5, "translateY" : -5, "rotateX" : -5, "rotateY" : -5 } }' src="<?php echo get_template_directory_uri(); ?>/images/road.jpeg" />
</div>
.megawrapper {
position: absolute;
overflow-x: hidden;
overflow-y: hidden;
width: 100%;
height: 100%;
}
.home-page {
position: absolute;
z-index: 0;
width: 100%;
height: 100%;
background-color: #3c3c3e;
background-image: url(images/road.jpeg);
background-position: 50% 50%;
background-size: cover;
background-repeat: no-repeat;
}
.tilt {
overflow: hidden;
position: relative;
width: 100%;
height: 100%;
margin: 0 auto;
}
.tilt__back {
position: relative;
}
.tilt__front {
position: absolute;
top: 0;
left: 0;
}
.tilt__back, .tilt__front {
width: 100%;
height: 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
I cant seem to get the same layout as the website. I dont know why .tilt would not center properly when I apply padding of 60 px on .home-page. I dont want to use flexbox to achieve the same result
use box-sizing:border-box; on your .home_page it will work fine.I'm added the snippet below.
html,body{
width:100%;
height:100%;
}
.home_page{
width:100%;
height:100%;
background-color:#3c3c3e;
background-image: url(https://i.stack.imgur.com/wwy2w.jpg);
background-position: 50% 50%;
background-size: cover;
background-repeat: no-repeat;
padding:60px;
box-sizing:border-box;
}
.tilt {
overflow: hidden;
position: relative;
width: 100%;
height: 100%;
margin: 0 auto;
background-color:yellow;
}
<div class="home_page">
<div class="tilt"></div>
</div>
Here is a good way.
<div class="divToCenterStuffIn">
<div class="vertCenter">
Vertical Center
</div>
</div>
<div class="divToCenterStuffIn">
<div class="horzCenter">
Horizontal Center
</div>
</div>
<div class="divToCenterStuffIn">
<div class="trueCenter">
True Center
</div>
</div>
.divToCenterStuffIn {
position: relative;
display: block;
width: 10rem;
height: 10rem;
}
.vertCenter
{
position: absolute;
display: block;
top:50%;
-ms-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
.horzCenter
{
position: absolute;
display: block;
left: 50%;
-ms-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
}
.trueCenter {
position: absolute;
display: block;
left: 50%;
top: 50%;
-ms-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

Rotating an image when user scrolls up and down the screen

I am fairly new to writing in html, css, and coding in javascript.
I digress; i am trying to have an image of a gear rotate when the a user scrolls up and down the screen (i am hoping to give it an elevator effect when i add a belt).
I am using the jquery $(window).scroll(function(). I know it is working because when i use console.log("hi") it writes every time i scroll. My problem is the .animate() function that doesn't seem to work. I even tried downloading "http://jqueryrotate.com/" and using that to rotate.
Any help would be much appreciated!
## HTML ##
<div class="left_pulley">
<img src="gear2.png" />
</div>
<div class="right_pulley">
<img src="gear2.png" />
</div>
## CSS ##
.left_pulley
{
position: absolute;
margin: 0;
padding: 0;
top: 263px;
left: 87%;
height: 35px;
width: 35px;
}
.left_pulley img
{
width: 100%;
}
.right_pulley
{
position: absolute;
margin: 0;
padding: 0;
top: 263px;
left: 94.2%;
height: 35px;
width: 35px;
}
.right_pulley img
{
width: 100%;
}
## JS ##
First using .rotate({})
$(".left_pulley").rotate({bind:
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
$(.left_pulley).rotate({
angle: 0,
animateTo: 180,
})
})
})
})
Now using .animate({}) to try and just move it at all.
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
var scott = $('img');
scott.animate({
left: 180
}
}
});
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
var scott = $('img');
scott.animate({
left: 180
}
function() {
console.log("hi");
}
});
console.log("hi2");
}
});
.left_pulley {
position: absolute;
margin: 0;
padding: 0;
top: 263px;
left: 87%;
height: 35px;
width: 35px;
}
.left_pulley img {
width: 100%;
}
.right_pulley {
position: absolute;
margin: 0;
padding: 0;
top: 263px;
left: 94.2%;
height: 35px;
width: 35px;
}
.right_pulley img {
width: 100%;
}
<div class="left_pulley">
<img src="gear2.png" />
</div>
<div class="right_pulley">
<img src="gear2.png" />
</div>
[
picture of gears i want to rotate.
]1
You should look into the CSS3 transform property, more specifically the rotate() function. Here
It would also be beneficial to add a transistion property to create an animated 'tween' between rotation values. Here. Make sure to add this transition to the transition property (as this is where rotation is set).\
You can then change the rotation of the gear (with automatic animation!) using jquery by setting the css value of the transition property, for example:
#gear{
transition: transform 300ms;
transform: rotate(7deg);
transform-origin:90% 90%;
position:absolute;
left:100px;
top:100px;
font-size:10rem;
width:100px;
height:100px;
}
You can test it out here by hitting run.
https://jsfiddle.net/oc4hhons/
Borrowing heavily from https://stackoverflow.com/a/17348698/2026508
You could do something like this:
var degrees = 0;
var prevScroll = 0;
$(window).scroll(function() {
if ($(window).scrollTop() > 0) {
if (prevScroll > $(window).scrollTop()) {
$('.woo').css({
'-webkit-transform': 'rotate(' + degrees+++'deg)',
'-moz-transform': 'rotate(' + degrees+++'deg)',
'-ms-transform': 'rotate(' + degrees+++'deg)',
'transform': 'rotate(' + degrees+++'deg)'
});
console.log('prevScroll greater:', prevScroll)
} else if (prevScroll < $(window).scrollTop()) {
$('.woo').css({
'-webkit-transform': 'rotate(' + degrees--+'deg)',
'-moz-transform': 'rotate(' + degrees--+'deg)',
'-ms-transform': 'rotate(' + degrees--+'deg)',
'transform': 'rotate(' + degrees--+'deg)'
});
console.log('prevScroll less:', prevScroll)
}
prevScroll = $(window).scrollTop()
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height: 40px; width: 100px;background-image: url(' gear2.png ');background-color:blue;" class="woo">turn</div>
JS Fiddle-Updated, now they rotate together same direction but the rotation is depending on whether the scroll is up or down:
JS:
var $gears = $('.gear'),
$i = 0,
$scrollBefore = 0;
$(window).scroll(function () {
if($(this).scrollTop() > $scrollBefore){
$scrollBefore = $(this).scrollTop();
$gears.css("transform", "rotate(" + ($i+=4) + "deg)");
}else if($(this).scrollTop() < $scrollBefore){
$scrollBefore = $(this).scrollTop();
$gears.css("transform", "rotate(" + ($i-=4) + "deg)");
}
});
this JS Fiddle 2, makes them rotate in opposite directions, and each gear direction switches depending if the scrolling is up or down:
JS:
var $gearLeft = $('.left_pulley'),
$gearRight = $('.right_pulley'),
$i = 0,
$j = 0,
$scrollBefore = 0;
$(window).scroll(function() {
if ($(this).scrollTop() > $scrollBefore) {
$scrollBefore = $(this).scrollTop();
$gearLeft.css("transform", "rotate(" + ($i += 4) + "deg)");
$gearRight.css("transform", "rotate(" + ($j -= 4) + "deg)");
} else if ($(this).scrollTop() < $scrollBefore) {
$scrollBefore = $(this).scrollTop();
$gearLeft.css("transform", "rotate(" + ($i -= 4) + "deg)");
$gearRight.css("transform", "rotate(" + ($j += 4) + "deg)");
}
});
Thanks for all the help everyone!
Just want to post my finial code in case anyone else needs help in the future.
/* Scott Louzon 11/24/15
This code is used to rotate two images of a gears when user scrolls */
/*This function see's when user scrolls then calls rotate_right & rotate_left
accordingly */
var scroll_at = 0; //variable to keep track of
//scroll postion
$(window).scroll(function() {
if ($(this).scrollTop() > 0) //if scroll postion is not at
{ //top do this
if ($(this).scrollTop() > scroll_at) //if scroll postion is > than b4
{
rotate_down();
}
else if ($(this).scrollTop() < scroll_at) //if scroll postion is < than b4
{
rotate_up();
}
scroll_at = $(this).scrollTop(); //set varible to were scroll
//postion is at now
}
})
//Both these functions call css to rotate the image of a gear
var rotation = 0;
function rotate_down()
{
rotation+= 8;
$(".left_pulley").css("transform","rotate("+ rotation +"deg)");
$(".right_pulley").css("transform","rotate("+ (-1 * rotation) +"deg)");
}
function rotate_up()
{
rotation += 8;
$(".left_pulley").css("transform","rotate("+ (-1 * rotation)+"deg)");
$(".right_pulley").css("transform","rotate("+ rotation +"deg)");
}
.left_pulley
{
position: absolute;
margin: 0;
padding: 0;
/*Used for gear rotation */
transition: transform 1ms;
transform-origin:50% 50%;
top: 263px;
left: 87%;
height: 35px;
width: 35px;
}
.left_pulley img
{
width: 100%;
}
.right_pulley
{
position: absolute;
margin: 0;
padding: 0;
/* Used for gear rotation */
transition: transform 1ms;
transform-origin:50% 50%;
top: 263px;
left: 94.2%;
height: 35px;
width: 35px;
}
.right_pulley img
{
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left_pulley">
<img src="gear2.png" />
</div>
<div class="right_pulley">
<img src="gear2.png" />
</div>

How to show height on a div while resizing it dynamically

I want to know how the Javascript code below is working.
I tried this one on javascript but it shows me error. I got this code from : http://interactjs.io/ (Resizing).
I just want to show height on div while resizing vertically. The code is below:
interact('.resize-drag')
.draggable({
onmove: window.dragMoveListener
})
.resizable({
edges: {
left: true,
right: true,
bottom: true,
top: true
}
})
.on('resizemove', function(event) {
var target = event.target,
x = (parseFloat(target.getAttribute('data-x')) || 0),
y = (parseFloat(target.getAttribute('data-y')) || 0);
// update the element's style
target.style.width = event.rect.width + 'px';
target.style.height = event.rect.height + 'px';
// translate when resizing from top or left edges
x += event.deltaRect.left;
y += event.deltaRect.top;
target.style.webkitTransform = target.style.transform =
'translate(' + x + 'px,' + y + 'px)';
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
target.textContent = event.rect.width + '×' + event.rect.height;
});
.resize-drag {
background-color: #29e;
color: white;
font-size: 20px;
font-family: sans-serif;
border-radius: 8px;
padding: 20px;
margin: 30px 20px;
width: 120px;
/* This makes things *much* easier */
box-sizing: border-box;
}
.resize-container {
width: 100%;
height: 240px;
}
<div class="resize-container">
<div class="resize-drag">
Resize from any edge or corner
</div>
</div>
Include this on top:
<script src="http://code.interactjs.io/interact-1.2.5.min.js" type="text/javascript"></script>

Categories

Resources