How do I transition the changing of CSS values? - javascript

I'm using JavaScript to change CSS values to make a particular div fill the page when a button is clicked. But I would like make the change from small to filling the screen smooth. How do I do this with CSS or Javascript? This is currently how I'm changing the size of that div
function fullscreen(){ // called when button is clicked
var d = document.getElementById('viewer').style;
if(!isFullscreen){ // if not already fullscreen change values to fill screen
d.width = "100%";
d.height="100%";
d.position= "absolute";
d.left="0%";
d.top="0%";
d.margin="0 0 0 0";
isFullscreen = true;
}else{ // minimizie it
d.width="600px";
d.height="400px";
d.margin="0 auto";
d.position="relative";
isFullscreen = false;
}
}
How do I code the change from the full screen values to the minimized values to be a smooth transition instead of instantaneous?

Use jQuery'sanimate() function!
For example:
function fullscreen(){ // called when button is clicked
var o = {} // options
var speed = "fast"; // You can specify another value
if(!isFullscreen){ // if not already fullscreen change values to fill screen
o.width = "100%";
o.height="100%";
o.left="0%";
o.top="0%";
o.margin="0 0 0 0";
$("#viewer").animate(o,speed);
isFullscreen = true;
}else{ // minimize it
o.width="600px";
o.height="400px";
o.margin="0 auto";
$("#viewer").animate(o,speed);
isFullscreen = false;
}
}

You can do this by using Jquery, .animate() API see the reference .animate()
I have created a small demo using .animate() click the Demo to see the example.

What you want to do is rather complicated, first you need to get the absolute position and dimension of your element in the document, also the dimension of the document itself, there is no native cross-platform javascript functions for that but there are known techniques to find out those values, do a search. So assuming you will implement these functions yourself: getAbsoluteLeft(), getAbsoluteTop(), getWidth(), getHeight(), getDocWidth() and getDocHeight() here is the animating code (not tested):
function fullscreen(){ // called when button is clicked
var e = document.getElementById('viewer');
var d = e.style;
if(!isFullscreen){ // if not already fullscreen change values to fill screen
var duration = 1000 //milliseconds
var framesPerSecond = 24;
var beginLeft = getAbsoluteLeft( e );
var beginTop = getAbsoluteTop( e );
var beginRight = beginLeft + getWidth( e );
var beginBottom = beginTop + getHeight( e );
var endLeft = 0;
var endTop = 0;
var endRight = getDocWidth();
var endBottom = getDocHeight();
var totalFrames = duration / (1000/framesPerSecond);
var frameNo = 0;
var leftStep = (beginLeft - endLeft) / totalFrames;
var topStep = (beginTop - endTop) / totalFrames;
var rightStep = (endRight - beginRight) / totalFrames;
var bottomStep = (endBottom - beginBottom) / totalFrames;
var func = function () {
var left = beginLeft - leftStep * frameNo;
var top = beginTop - topStep * frameNo;
d.left = left+'px';
d.top = top+'px';
d.width = (beginRight + rightStep * frameNo - left)+'px';
d.height = (beginBottom + bottomStep * frameNo - top)+'px';
++frameNo;
if( frameNo == totalFrames ) {
clearInterval( timer );
d.width = "100%";
d.height="100%";
d.left="0%";
d.top="0%";
isFullscreen = true;
}
}
d.position= "absolute";
d.margin="0 0 0 0";
timer = setInterval( func, 1000 / framesPerSecond );
} else { // minimizie it
d.width="600px";
d.height="400px";
d.margin="0 auto";
d.position="relative";
isFullscreen = false;
}
}

Related

Image Sequence to Video using Javascript

I have 7 images and each image has 25 frames. What I need to do is that wander around each image by frames and display it as a video which can be controlled by play, pause and stop buttons.
What I can do is that making a video player that I can easily import a video and play, pause, stop in it. I designed it already but do not have any idea how to make a video from a list of images.
You can view the images at these URLs:
-http://storage.googleapis.com/alyo/assignments/images/0.jpg
- http://storage.googleapis.com/alyo/assignments/images/6.jpg
Any help will be appreciated.
You can achieve it using javscript setTimeout() method and div element like that:
var left = 0;
var top = 0;
var minLeft = -512;
var minBottom = -288;
var xDecrement = 128;
var yDecrement = 72;
var myImage = document.getElementById("myImage");
var imgIndex = 0;
let imageList = ['http://storage.googleapis.com/alyo/assignments/images/0.jpg','http://storage.googleapis.com/alyo/assignments/images/6.jpg'];
var playbackStates = {"INIT":0, "RUNNING": 1 , "PAUSE":2};
var activeState = playbackStates.INIT;
myImage.style.backgroundPositionX = "0px";
myImage.style.backgroundPositionY = "0px";
var timerHandler = null;
var play = function(){
if(timerHandler){
clearTimeout(timerHandler);
if(activeState === playbackStates.PAUSE){
return;
}
}
timerHandler = setTimeout(function(){
let pos =parseFloat(myImage.style.backgroundPositionX.replace("px",""));
myImage.style.backgroundPositionX = ( pos - xDecrement) + "px";
if(pos <= -512){
myImage.style.backgroundPositionX ="0px";
pos =parseFloat(myImage.style.backgroundPositionY.replace("px",""));
myImage.style.backgroundPositionY = ( pos - yDecrement) + "px";
if(pos <= -288){
myImage.style.backgroundPositionY = "0px";
imgIndex ++;
if(imageList.length <= imgIndex) return;
myImage.style.backgroundImage = "url("+imageList[imgIndex]+")";
}
}
play();
}, 160)
};
myImage.style.backgroundImage = "url("+imageList[imgIndex]+")";
play();
activeState = playbackStates.RUNNING;
function pause(){
activeState = playbackStates.PAUSE;
}
function resume(){
activeState = playbackStates.RUNNING;
play();
}
<div style="width:128px;height:72px;" id="myImage"></div>
<input type="button" onclick="pause()" value="Pause"/>
<input type="button" onclick="resume()" value="Resume"/>
You can add all your image url's in "imageList" array, also adjust the speed by modify the timeout interval.

Javascript help, Trying to animate two different sprites at same time

I need some javascript help. I am trying to set up two sprite animations with different frame rates in two separate div.
Here is a fiddle I started and i am very much stuck.
How do I combine the two div IDs into one statement? OR Should I be using ClassName in the statement to run on both divs?
http://jsfiddle.net/akwilinski/3t7d6qbL/1/
<div id="animate" class="animation"></div>
<div id="animate2" class="animation2"></div>
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Thank you for any assistance!
Simplest way to do this using the method you have already started using is to define 2 new variables, 1 for the second div and one for the second frame count. Then you can just add the call to your function.
Updated js:
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
var frameOffset2 = (++frame % frames) * -frameHeight - 10;
div.style.backgroundPosition = "0px " + frameOffset + "px";
div2.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Fiddle
http://jsfiddle.net/f4v1vy7x/5/
I made a Can object to store the configuration for each can (so you can have different frameHeights, frames and frameRates.
I used window.requestAnimationFrame because it's far more efficient than setInterval. On each available frame I check whether it's time to animate based on each Can's set frame rate:
var Can = function( selector, frameHeight, frames, frameRate )
{
this.domCan = document.getElementById( selector );
this.frameHeight = frameHeight;
this.frames = frames;
this.frameRate = frameRate;
this.frame = 0;
};
onload = function startAnimation() {
var can1 = new Can( 'animate', 400, 27, 20 );
var can2 = new Can( 'animate2', 400, 27, 100 );
var cans = [ can1, can2 ];
window.requestAnimationFrame( function() {
can1.start = can2.start = new Date();
animate( cans );
} );
};
var animate = function( cans ) {
for( var i = 0; i < cans.length; i++ ) {
var now = new Date();
var can = cans[i];
if( now - can.start >= 1000 / can.frameRate ) {
can.start = now;
var frameOffset = (++can.frame % can.frames) * -can.frameHeight;
can.domCan.style.backgroundPosition = "0px " + frameOffset + "px";
}
}
window.requestAnimationFrame( function() {
animate( cans );
} );
}
You could do something like this:
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
function anim(div) {
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
anim(div);
anim(div2);
You could then pass in additional parameters like frameHeight, frame, and frames to further customize each animation.

Javascript edit to loop images automatically

I downloaded picture 360 rotation and it works well. It is currently using the mouse to spin through images which make a 360 rotation. Source link https://code.google.com/p/picture-360-rotation/
I want the 360 spin to automatically start without the mouse. But I still want the mouse to be able to spin the images.
How do I get the script to spin it slowly?
JS:
var start = false;
(function($) {
$.fn.pic360 = function() {
var first_img = this.find('img:first');
var all_img = this.find('img');
var img_count = all_img.length;
if(img_count==0) return;
var img_width = first_img.width();
var chg_width = parseInt(img_width/img_count);/* 感应区宽度*/
var div_left = this.position().left;
var imgs_left = first_img.offset().left;
this.toggle();
all_img.toggle();
first_img.toggle();
this.width(img_width);/* 设置容器宽度 */
this.height(first_img.height());/* 设置容器高度 */
var mouseX = 0;
var step = 0;
var curr_step = 0;/* 当前感应区 */
var curr_img = 0;/* 当前图片 */
this.mousedown(function(e){/*鼠标移到本DIV*/
start = true;
if(start){
mouseX = e.screenX;
/* 获取当前感应区 */
curr_step=parseInt((mouseX-imgs_left)/chg_width);
step = curr_step;
}
})
this.mousemove(function(e){
if(start){
curr_step=parseInt((e.screenX-imgs_left)/chg_width);
if(curr_step!=step){
$(all_img[curr_img]).toggle();/* 隐藏当前图片 */
if(curr_step>step){
curr_img = curr_img+1;
if(curr_img>=img_count) curr_img=0;
}else{
curr_img = curr_img-1;
if(curr_img<0) curr_img=img_count-1;
}
$(all_img[curr_img]).toggle();
step=curr_step;
}
}
return false;
})
this.mouseup(function(e){/*鼠标移出本DIV*/
start = false;
})
return this;
};
})(jQuery);
/**
* 初始化所有Pic360对象
*/
$(document).ready(function(){
$(".PIC360").pic360().show();
$("body").mousemove(function(e){
start = false;
})
})
The div class="PIC360" and the images are img's.
Can you make a jsfiddle example of how it works now.
Atm i can guess you could use setInterval to make it rotate automatically
var curr_img = 0;
var loopTimer = setInterval( function() {
if (curr_img > (all_img.length - 1) ) {curr_img = 0;}
curr_img++:
$(all_img[curr_img]).toggle();
}, 200);
/* stop when mouse is pressed */
this.mousedown(function(e){ clearInterval(loopTimer);});

jQuery: change class after conditional is met

I created this site where you have multiple sliders moving vertically using this example on stackoverflow > here < along with this fiddle.
The site when loaded has an overflow: hidden on the body and position fixed on my main content div(div class="content-fs row"). The idea is that when you first arrive on the page, you scroll through each slide and once you hit the last one, the position changes on the main content div(div class="content-fs row") from fixed to static and the overflow: hidden is removed from the body. I'm having trouble writing the conditional statement that says "if its the last slider, change the position." The jquery below is the code i'm using for the site along with the conditional statement that doesn't work.
Any pointers/advice would be greatly appreciated!
jquery:
function scrollLax(){
/*
initialize
*/
var scrollDown = false;
var scrollUp = false;
var scroll = 0;
var $view = $('#portfolio');
var t = 0;
var h = $view.height() - 250;
$view.find('.portfolio-sliders').each(function() {
var $moving = $(this);
// position the next moving correctly
if($moving.hasClass('from-bottom')) {
$moving.css('top', h); // subtract t so that a portion of the other slider is showing
}
// make sure moving is visible
$moving.css('z-index', 10);
});
var $moving = $view.find('.portfolio-sliders:first-child');
$moving.css('z-index', 10);
/*
event handlers
*/
var mousew = function(e) {
var d = 0;
if(!e) e = event;
if (e.wheelDelta) {
d = -e.wheelDelta/3;
} else if (e.detail) {
d = e.detail/120;
}
parallaxScroll(d);
}
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', mousew, false);
}
window.onmousewheel = document.onmousewheel = mousew;
/*
parallax loop display loop
*/
window.setInterval(function() {
if(scrollDown)
parallaxScroll(4);
else if(scrollUp)
parallaxScroll(-4);
}, 50);
function parallaxScroll(scroll) {
// current moving object
var ml = $moving.position().left;
var mt = $moving.position().top;
var mw = $moving.width();
var mh = $moving.height();
// calc velocity
var fromBottom = false;
var vLeft = 0;
var vTop = 0;
if($moving.hasClass('from-bottom')) {
vTop = -scroll;
fromBottom = true;
}
// calc new position
var newLeft = ml + vLeft;
var newTop = mt + vTop;
// check bounds
var finished = false;
if(fromBottom && (newTop < t || newTop > h)) {
finished = true;
newTop = (scroll > 0 ? t : t + h);
}
// set new position
$moving.css('left', newLeft);
$moving.css('top', newTop);
// if finished change moving object
if(finished) {
// get the next moving
if(scroll > 0) {
$moving = $moving.next('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:last');
//this is where I am trying to add the if conditional statement.
if ('.portfolio-sliders:last')
$('.content-fs.row').css({'position': 'static'});
if('.portfolio-sliders:last' && (mt == 0))
$('html, body').removeClass('overflow');
} else {
$moving = $moving.prev('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:first-child');
//reverse the logic and if last slide change position
if('.portfolio-sliders:first-child')
$('.content-fs.row').css({'position': 'fixed'});
}
}
// for debug
//$('#direction').text(scroll + "/" + t + " " + ml + "/" + mt + " " + finished + " " + $moving.text());
}
}
Your code as it is simply asks whether .portfolio-sliders:last exists. Seems you should be doing:
if ($moving == $('.portfolio-sliders:last') )
or something along those lines, instead checking whether the active slide is the last.

How to add scroll background effect to multiple elements with different settings?

In this demo http://www.htmldrive.net/items/demo/527/Animated-background-image-with-jQuery
This code is for one background only. I want to add multiple background with different direction and speed.
var scrollSpeed = 70;
var step = 1;
var current = 0;
var imageWidth = 2247;
var headerWidth = 800;
var restartPosition = -(imageWidth - headerWidth);
function scrollBg(){
current -= step;
if (current == restartPosition){
current = 0;
}
$('#header').css("background-position",current+"px 0");
}
var init = setInterval("scrollBg()", scrollSpeed);
Currently it has settings for
$('#header').css("background-position",current+"px 0");
In a website I want to use this effect on #footer or #content background also. but with different speed and direction.
And is there any better and more optimized jquery method to achieve same effect?
And can we get same effect using CSS 3, without javascript?
Just saw the OP's answer, but decided to post anyway:
I've created a jQuery plugin to do this:
(function($) {
$.fn.scrollingBackground = function(options) {
// settings and defaults.
var settings = options || {};
var speed = settings.speed || 1;
var step = settings.step || 1;
var direction = settings.direction || 'rtl';
var animStep;
// build up a string to pass to animate:
if (direction === 'rtl') {
animStep = "-=" + step + "px";
}
else if (direction === 'ltr') {
animStep = '+=' + step + "px";
}
var element = this;
// perform the animation forever:
var animate = function() {
element.animate({
backgroundPosition: animStep + " 0px"
}, speed, animate);
};
animate();
};
})(jQuery);
Usage:
$("#header").scrollingBackground({
speed: 50,
step: 50,
direction: 'ltr'
});
This is pretty basic, and assumes that you're background-repeat is 'repeat-x' on the element you call it on. This way, there's no need to reset the background position every so often.
Working example: http://jsfiddle.net/andrewwhitaker/xmtpr/
I could work out the following solution. Am not sure if it is efficient. Will wait for anyone to comment or provide a better option.
Till then...:
var scrollSpeed = 70;
var step = 1;
var current = 0;
var images =
[
{
imageWidth:2247,
imagePath:"images/image1"
},
{
imageWidth:1200,
imagePath:"images/image2"
}
]
var headerWidth = 800;
var imageRotateCount = 0;
var imagesLength = images.length;
$('#header').css("background-image", images[0].imagePath);
function scrollBg(){
var curIndex = imageRotateCount%imagesLength;
var curImage = images[curIndex];
current -= step;
var restartPosition = -(curImage.imageWidth - headerWidth);
if (current == restartPosition){
current = 0;
imageRotateCount++;
curIndex = imageRotateCount%imagesLength;
curImage = images[curIndex];
$('#header').css("background-image", curImage.imagePath);
}
$('#header').css("background-position",current+"px 0");
}
var init = setInterval("scrollBg()", scrollSpeed);

Categories

Resources