Using sprite to create a rotation with Javascript - javascript

I'm creating an animation of a ring rotating.
On hover the right rotates 180 degrees, pauses and rotates back to the starting position. If the user removes the cursor off the ring while its animating it needs to reverse from the frame its currently on.
I haven't had much extensive experience with animation in my career as a front end developer so any advice on tech to use would be appreciated.
Currently I'm using CSS Animation with a sprite, as below but it lacks the ability to reverse from the frame it was on when the user leaves the ring.
Here is my working example, It's inspired by http://renren.com/
Example using CSS
$('body').on('mouseenter', '.item', function() {
$(this).removeClass('unactive').addClass('active');
});
$('body').on('mouseleave', '.item', function() {
$(this).removeClass('active').addClass('unactive');
});
.content {
width: 150px;
height: 150px;
background-color: #EBEBEB;
}
.content.ring {
background: url(http://a.xnimg.cn/nx/apps/login/cssimg/qrcode1-t.jpg) 0 0 no-repeat
}
.active .content {
background-position: 0 -1800px;
-moz-animation: movedown 2000ms steps(12) forwards;
-webkit-animation: movedown 2000ms steps(12) forwards
}
.unactive .content {
-moz-animation: moveup 2000ms steps(7) forwards;
-webkit-animation: moveup 2000ms steps(7) forwards
}
#-moz-keyframes movedown {
0% {
background-position: 0 0
}
100% {
background-position: 0 -1800px
}
}
#-moz-keyframes moveup {
0% {
background-position: 0 -1800px
}
100% {
background-position: 0 -2850px
}
}
#-webkit-keyframes movedown {
0% {
background-position: 0 0
}
100% {
background-position: 0 -1800px
}
}
#-webkit-keyframes moveup {
0% {
background-position: 0 -1800px
}
100% {
background-position: 0 -2850px
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML
<div class="item active">
<div class="content ring">
</div>
</div>
I've also found plugins like:
motio
So my question is, is CSS able to have this much control or would a CANVAS or other jQuery plugin be better suited?
EDIT
I'm still having difficulties figuring this one out although I started writing a script to help control the animation.
I'm trying to control the background position to gain control of the sprite rotating.
Example using Javascript
;(function($) {
var Ring = function (options) {
// context
var self = this;
// defaults
var currFrame = 1, totalFrames, width, height, timeout;
// default frame array
var framesObj = {};
// option defaults
self.class = "";
self.spriteHeight = "";
//properties based on options
if (typeof options != 'undefined' && options != undefined && options != null)
{
self.class = options.class;
self.spriteHeight = options.spriteHeight;
self.speed = options.speed;
}
// fire off everything you need
self.init = function ()
{
self.buildArr();
}
// check for the container dimentions
self.frameDimentions = function ()
{
// double check we have a class to select the container with
var container = self.class ? true : false;
// I know I could just write self.class in the if..
if ( container )
{
var container = $("." + self.class + "");
var containerHeight = container.outerHeight();
var containerWidth = container.outerWidth();
return [containerHeight,containerWidth];
}
console.log("Please provide a class");
}
// calculate frames e.g. 3000 into 150 per frame is 20..
self.calcFrames = function()
{
var totalFrames = parseInt(self.spriteHeight) / self.frameDimentions()[0];
return totalFrames;
}
self.buildArr = function()
{
// these values need to be pushed in to the arr
for (var i = 0; i < self.calcFrames(); i++) {
framesObj[(i+1)] = self.frameDimentions()[0]*i;
}
}
self.startForwardAnimation = function(){
// to stop manic clicking../hover..
if( currFrame <= 1 )
{
timeout = setInterval( updateFrameForward, self.speed);
}
}
self.startBackwardAnimation = function(){
// to stop manic clicking../hover..
console.log("start backward animation");
if( currFrame != 1 )
{
backTimeout = setInterval( updateFrameBackward, self.speed);
}
}
self.stopAnimation = function(){
//currFrame = 1;
clearTimeout(timeout);
}
self.reset = function(){
clearTimeout(timeout);
clearTimeout(backTimeout);
currFrame = 1;
}
self.info = function(){
$('.info').html(currFrame);
}
// if currFrame less than total frames
// add one to it
// update the current frame variable
// stop and clear timer when reach the end
function updateFrameForward(){
//check if we are in available frames..
if ( currFrame == self.calcFrames() )
{
self.stopAnimation();
self.reset();
}
$("." + self.class + "").css({
'background-position-y': "-" + framesObj[currFrame] + "px"
});
self.info();
currFrame = currFrame + 1;
}
function updateFrameBackward(){
if( currFrame <= 1 )
{
self.stopAnimation();
self.reset();
}
$("." + self.class + "").css({
'background-position-y': framesObj[currFrame] + "px"
});
self.info();
console.log(currFrame);
currFrame = currFrame - 1;
}
}
var ringAniamtion = new Ring({
class: "animate",
spriteHeight: "3000",
speed: "20"
});
$('body').on('mouseenter', '.animate', function(event){
event.preventDefault();
console.log("mouse enter");
ringAniamtion.buildArr();
ringAniamtion.startForwardAnimation();
});
$('body').on('mouseleave', '.animate', function(event){
event.preventDefault();
console.log("mouse leave");
ringAniamtion.stopAnimation();
ringAniamtion.startBackwardAnimation();
});
$('body').on('click', '.stop', function(event){
event.preventDefault();
ringAniamtion.reset();
});
})( jQuery );
// timeout = setTimeout('timeout_trigger()', 3000);
// clearTimeout(timeout);
.content
{
width: 150px;
height: 150px;
background: url(http://a.xnimg.cn/nx/apps/login/cssimg/qrcode1-t.jpg) 0 0 no-repeat;
cursor: pointer;
}
<div class="content animate">
</div>
<div class="info">
</div>
stop

I figured out how to do it in the second code snippet..
;(function($) {
var Ring = function (options) {
// context
var self = this;
// defaults
var currFrame = 1, totalFrames, width, height, timeout;
// default frame array
var framesObj = {};
// option defaults
self.class = "";
self.spriteHeight = "";
//properties based on options
if (typeof options != 'undefined' && options != undefined && options != null)
{
self.class = options.class;
self.spriteHeight = options.spriteHeight;
self.speed = options.speed;
}
// fire off everything you need
self.init = function ()
{
self.buildArr();
}
// check for the container dimentions
self.frameDimentions = function ()
{
// double check we have a class to select the container with
var container = self.class ? true : false;
// I know I could just write self.class in the if..
if ( container )
{
var container = $("." + self.class + "");
var containerHeight = container.outerHeight();
var containerWidth = container.outerWidth();
return [containerHeight,containerWidth];
}
console.log("Please provide a class");
}
// calculate frames e.g. 3000 into 150 per frame is 20..
self.calcFrames = function()
{
var totalFrames = parseInt(self.spriteHeight) / self.frameDimentions()[0];
return totalFrames;
}
self.buildArr = function()
{
// these values need to be pushed in to the arr
for (var i = 0; i < self.calcFrames(); i++) {
framesObj[(i+1)] = self.frameDimentions()[0]*i;
}
}
self.startForwardAnimation = function(){
// to stop manic clicking../hover..
if( currFrame <= 1 )
{
timeout = setInterval( updateFrameForward, self.speed);
}
}
self.startBackwardAnimation = function(){
// to stop manic clicking../hover..
console.log("start backward animation");
if( currFrame != 1 )
{
backTimeout = setInterval( updateFrameBackward, self.speed);
}
}
self.stopAnimation = function(){
//currFrame = 1;
clearTimeout(timeout);
}
self.reset = function(){
clearTimeout(timeout);
clearTimeout(backTimeout);
currFrame = 1;
}
self.info = function(){
$('.info').html(currFrame);
}
// if currFrame less than total frames
// add one to it
// update the current frame variable
// stop and clear timer when reach the end
function updateFrameForward(){
//check if we are in available frames..
if ( currFrame == self.calcFrames() )
{
self.stopAnimation();
self.reset();
}
$("." + self.class + "").css({
'background-position-y': "-" + framesObj[currFrame] + "px"
});
self.info();
currFrame = currFrame + 1;
}
function updateFrameBackward(){
if( currFrame <= 1 )
{
self.stopAnimation();
self.reset();
}
$("." + self.class + "").css({
'background-position-y': framesObj[currFrame] + "px"
});
self.info();
console.log(currFrame);
currFrame = currFrame - 1;
}
}
var ringAniamtion = new Ring({
class: "animate",
spriteHeight: "3000",
speed: "20"
});
$('body').on('mouseenter', '.animate', function(event){
event.preventDefault();
console.log("mouse enter");
ringAniamtion.buildArr();
ringAniamtion.startForwardAnimation();
});
$('body').on('mouseleave', '.animate', function(event){
event.preventDefault();
console.log("mouse leave");
ringAniamtion.stopAnimation();
ringAniamtion.startBackwardAnimation();
});
$('body').on('click', '.stop', function(event){
event.preventDefault();
ringAniamtion.reset();
});
})( jQuery );

Related

How to disable JavaScript Function when other function is running

Hi,
I'm learning/practicing to make my custom slider in JS/JQuery, and I've written below code. Its almost running well but little issues. What I'm doing is I'm running it two types,
Auto running after each 5 seconds with autoRun() Function
On every click to slider indicator run to relevant slide with click event.
In below code, I'm facing couple of issues, and will be very thankful to you if you help me.
Issues I'm facing are:
When I click to slider indicator, I want to disable auto Run function for a specific time like 5 second so my slider look more professional.
When it goes to last slide or come back to first slide, console is showing an error below, and it also take double time eg: 10 seconds to go next slide.
"Uncaught TypeError: Cannot read property 'left' of undefined"
$(function () {
var $mainSliderWrap = $('#slider_main_wrapper')
, $sliderMain = $mainSliderWrap.find('.main-slider')
, $sliderchildren = $sliderMain.children('li')
, $sliderIndicator = $mainSliderWrap.find('.slider-main-indicator');
// Slider Setup
window.addEventListener('resize', initMainSlider);
initMainSlider();
// Slider SetUp function
function initMainSlider() {
var wWidth = window.outerWidth
, sliderMainWidth = wWidth * $sliderchildren.length
$sliderMain.css('width', sliderMainWidth + 'px');
$sliderMain.children('li').first().addClass('visible');
$sliderIndicator.children('li').first().addClass('active');
}
// Want to Run Slider on Click event
$sliderIndicator.on('click', 'li', updateMainSlider);
// If Click Event Not happenening then I want to auto run Slider after 5 seconds
autoRun()
function autoRun() {
var mainSliderChildLenght = $sliderchildren.length;
var i = 0;
var next = true;
var dir;
setInterval(function () {
if (mainSliderChildLenght == i || i < 0) {
next = !next;
if (i < 0) {
i = 0;
}
}
if (next) {
dir = 'next';
i++;
}
else {
dir = 'prev';
i--;
if(i < 0) {
return
}
}
updateMainSlider(dir);
$('#result').text(i)
}, 5000);
}
// Here is the function for Updating the Slider
function updateMainSlider(a) {
var visibleSlide = $sliderchildren.filter('.visible')
, actualTranslate = getTranslateValue($sliderMain, 'X');
if (a == 'next' || a == 'prev') { // inside this if is running when function is called from autoRun()
console.log(a)
var newSlide = (a == 'next') ? visibleSlide.next() : visibleSlide.prev()
, newSlideOffsetLeft = newSlide.offset().left
, valueToTranslte = -newSlideOffsetLeft + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
visibleSlide.removeClass('visible');
newSlide.addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq(newSlide.index()).addClass('active');
}
else { // inside this if is running when function is called from click event
console.log(a)
var newSlide = $(a.target)
, $newSlideIndicatorIndex = newSlide.index()
, $visibleSlideIndex = visibleSlide.index();
if ($newSlideIndicatorIndex !== $visibleSlideIndex && !$($sliderIndicator).hasClass('disable-click')) {
$($sliderIndicator).addClass('disable-click');
setTimeout(function () {
$($sliderIndicator).removeClass('disable-click');
}, 1000);
var diff = $newSlideIndicatorIndex - $visibleSlideIndex
, valueToTranslte = -(diff * window.outerWidth) + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
$($sliderchildren[$visibleSlideIndex]).removeClass('visible');
$($sliderchildren[$newSlideIndicatorIndex]).addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq($newSlideIndicatorIndex).addClass('active');
} // end if
} // end else
} // end function
// SetTranslate Value Fucntion
function setTranslateValue(element, property, value) {
$(element).css({
'transform': property + '(' + value + 'px)'
});
}
// Get Translate Value function
function getTranslateValue(element, axis) {
var trValue = $(element).css('transform');
if (trValue !== 'none') {
trValue = trValue.split(')')[0];
trValue = trValue.split(',');
trValue = (axis == 'X') ? trValue[4] : trValue[5];
}
else {
trValue = 0;
}
return Number(trValue);
}
})
ol {
list-style: none;
margin: 0;
padding: 0;
}
body {
margin: 0;
padding: 0;
}
.slider-main-wrapper {
box-shadow: inset 0 0 20px orange;
min-height: 100vh;
}
ol.main-slider {
height: 85vh;
box-shadow: inset 0 0 20px green;
transition: transform 500ms ease;
}
ol.main-slider > li {
float: left;
}
ol.main-slider > li .silder-main-content {
width: 100vw;
height: 85vh;
display: flex;
justify-content: center;
align-items: center;
}
ol.main-slider > li.visible .silder-main-content {
box-shadow: inset 0 0 140px green;
}
ol.slider-main-indicator {
height: 15vh;
display: flex;
}
ol.slider-main-indicator li {
box-shadow: inset 0 0 2px green;
flex: 1;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
ol.slider-main-indicator li.active {
box-shadow: inset 0 0 80px green;
cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result" style="font-size: 30px; position: absolute;
top: 0; left: 0"></div>
<div class="slider-main-wrapper" id="slider_main_wrapper">
<ol class="main-slider">
<li>
<div class="silder-main-content">
<h1>First Slide</h1>
</div>
</li>
<li>
<div class="silder-main-content">
<h2>Second Slide</h2>
</div>
</li>
<li>
<div class="silder-main-content">
<h1>Third Slide</h1>
</div>
</li>
<li>
<div class="silder-main-content">
<h1>Fourth Slide</h1>
</div>
</li>
</ol>
<!--end slides-->
<ol class="slider-main-indicator">
<li> <span class="text">First Slide</span> </li>
<li> <span class="text">Second Slide</span> </li>
<li> <span class="text">Third Slide</span> </li>
<li> <span class="text">Fourth Slide</span> </li>
</ol>
<!--end slide indicator-->
</div>
you'll want to clearInterval when you click, the setInterval again once the processing due to the "click" event completes - so, for a start, you'll need to save the returned value of setInterval to use in clearInterval
autoRun in this code returns a function which starts the interval
this is just "part" of your code, not the whole thing - trying to keep it readable regarding the changes I have implemented
$sliderIndicator.on('click', 'li', updateMainSlider);
// save the function returned by autoRun
var go = autoRun();
// start autoRun
go();
// add a variable to store interval identifier
var interval;
function autoRun() {
var mainSliderChildLenght = $sliderchildren.length;
var i = 0;
var next = true;
var dir;
// return a function to begin autoRun for real
return function() {
// save interval identifier
interval = setInterval(function () {
// your code unchanged
}, 5000);
};
}
function updateMainSlider(a) {
var visibleSlide = $sliderchildren.filter('.visible')
, actualTranslate = getTranslateValue($sliderMain, 'X');
if (a == 'next' || a == 'prev') {
// your code - unchanged
} else {
// clear interval
clearInterval(interval);
// your code - unchanged
// now add this to restart the interval
go();
}
}
You may still need to tweak some things, I haven't gone through your code in depth
as requested
$(function () {
var $mainSliderWrap = $('#slider_main_wrapper')
, $sliderMain = $mainSliderWrap.find('.main-slider')
, $sliderchildren = $sliderMain.children('li')
, $sliderIndicator = $mainSliderWrap.find('.slider-main-indicator');
// Slider Setup
window.addEventListener('resize', initMainSlider);
initMainSlider();
// Slider SetUp function
function initMainSlider() {
var wWidth = window.outerWidth
, sliderMainWidth = wWidth * $sliderchildren.length
$sliderMain.css('width', sliderMainWidth + 'px');
$sliderMain.children('li').first().addClass('visible');
$sliderIndicator.children('li').first().addClass('active');
}
// Want to Run Slider on Click event
$sliderIndicator.on('click', 'li', updateMainSlider);
// If Click Event Not happenening then I want to auto run Slider after 5 seconds
var go = autoRun();
// start autoRun
go();
var interval;
function autoRun() {
var mainSliderChildLenght = $sliderchildren.length;
var i = 0;
var next = true;
var dir;
return function() {
setInterval(function () {
if (mainSliderChildLenght == i || i < 0) {
next = !next;
if (i < 0) {
i = 0;
}
}
if (next) {
dir = 'next';
i++;
}
else {
dir = 'prev';
i--;
if(i < 0) {
return
}
}
updateMainSlider(dir);
$('#result').text(i)
}, 5000);
});
}
// Here is the function for Updating the Slider
function updateMainSlider(a) {
var visibleSlide = $sliderchildren.filter('.visible')
, actualTranslate = getTranslateValue($sliderMain, 'X');
if (a == 'next' || a == 'prev') { // inside this if is running when function is called from autoRun()
console.log(a)
var newSlide = (a == 'next') ? visibleSlide.next() : visibleSlide.prev()
, newSlideOffsetLeft = newSlide.offset().left
, valueToTranslte = -newSlideOffsetLeft + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
visibleSlide.removeClass('visible');
newSlide.addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq(newSlide.index()).addClass('active');
}
else { // inside this if is running when function is called from click event
clearInterval(interval);
console.log(a)
var newSlide = $(a.target)
, $newSlideIndicatorIndex = newSlide.index()
, $visibleSlideIndex = visibleSlide.index();
if ($newSlideIndicatorIndex !== $visibleSlideIndex && !$($sliderIndicator).hasClass('disable-click')) {
$($sliderIndicator).addClass('disable-click');
setTimeout(function () {
$($sliderIndicator).removeClass('disable-click');
}, 1000);
var diff = $newSlideIndicatorIndex - $visibleSlideIndex
, valueToTranslte = -(diff * window.outerWidth) + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
$($sliderchildren[$visibleSlideIndex]).removeClass('visible');
$($sliderchildren[$newSlideIndicatorIndex]).addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq($newSlideIndicatorIndex).addClass('active');
} // end if
go();
} // end else
} // end function
// SetTranslate Value Fucntion
function setTranslateValue(element, property, value) {
$(element).css({
'transform': property + '(' + value + 'px)'
});
}
// Get Translate Value function
function getTranslateValue(element, axis) {
var trValue = $(element).css('transform');
if (trValue !== 'none') {
trValue = trValue.split(')')[0];
trValue = trValue.split(',');
trValue = (axis == 'X') ? trValue[4] : trValue[5];
}
else {
trValue = 0;
}
return Number(trValue);
}
})

Making a panorama move from side to side with jquery

For a photographic website and want to display panoramic photos moving side to side within a viewport. At the moment it goes left to right when the page loads but stops when it runs out of image. Instead of stopping I want it to reverse direction and go right to left, and then left to right, right to left infintum.
It is probable something very simple but I'm a complete newbie to jquery (sorry).
This is the code which I've adapted from Arnault PACHOT:
Any help would be greatly appreciated. Thanks in advance.
/* =========================================================
// jquery.panorama.js
// Author: OpenStudio (Arnault PACHOT)
// Mail: apachot#openstudio.fr
// Web: http://www.openstudio.fr
// Copyright (c) 2008 Arnault Pachot
// licence : GPL
========================================================= */
(function($) {
$.fn.panorama = function(options) {
this.each(function(){
var settings = {
viewport_width: 669,
speed: 20000,
direction: 'left',
control_display: 'auto',
start_position: 0,
auto_start: true,
mode_360: false
};
if(options) $.extend(settings, options);
var elemWidth = parseInt($(this).attr('width'));
var elemHeight = parseInt($(this).attr('height'));
var currentElement = this;
var panoramaViewport, panoramaContainer;
var bMouseMove = false;
var mouseMoveStart = 0;
var mouseMoveMarginStart = 0;
$(this).attr('unselectable','on')
.css('position', 'relative')
.css('-moz-user-select','none')
.css('-webkit-user-select','none')
.css('margin', '0')
.css('padding', '0')
.css('border', 'none')
.wrap("<div class='panorama-container'></div>");
if (settings.mode_360)
$(this).clone().insertAfter(this);
panoramaContainer = $(this).parent();
panoramaContainer.css('height', elemHeight+'px').css('overflow', 'hidden').wrap("<div class='panorama-viewport'></div>").parent().css('width',settings.viewport_width+'px')
.append("<div class='panorama-control'><a href='#' class='panorama-control-left'><<</a> <a href='#' class='panorama-control-pause'>x</a> <a href='#' class='panorama-control-right'>>></a> </div>");
panoramaViewport = panoramaContainer.parent();
panoramaViewport.mousedown(function(e){
if (!bMouseMove) {
bMouseMove = true;
mouseMoveStart = e.clientX;
}
return false;
}).mouseup(function(){
bMouseMove = false;
mouseMoveStart = 0;
return false;
}).mousemove(function(e){
if (bMouseMove){
var delta = parseInt((mouseMoveStart - e.clientX)/30);
if ((delta>10) || (delta<10)) {
var newMarginLeft = parseInt(panoramaContainer.css('marginLeft')) + (delta);
if (settings.mode_360) {
if (newMarginLeft > 0) {newMarginLeft = -elemWidth;}
if (newMarginLeft < -elemWidth) {newMarginLeft = 0;}
} else {
if (newMarginLeft > 0) {newMarginLeft = 0;}
if (newMarginLeft < -elemWidth) {newMarginLeft = -elemWidth;}
}
panoramaContainer.css('marginLeft', newMarginLeft+'px');
}
}
}).bind('contextmenu',function(){return false;});
panoramaViewport.css('height', elemHeight+'px').css('overflow', 'hidden').find('a.panorama-control-left').bind('click', function() {
$(panoramaContainer).stop();
settings.direction = 'right';
panorama_animate(panoramaContainer, elemWidth, settings);
return false;
});
panoramaViewport.bind('click', function() {
$(panoramaContainer).stop();
});
panoramaViewport.find('a.panorama-control-right').bind('click', function() {
$(panoramaContainer).stop();
settings.direction = 'left';
panorama_animate(panoramaContainer, elemWidth, settings);
return false;
});
panoramaViewport.find('a.panorama-control-pause').bind('click', function() {
$(panoramaContainer).stop();
return false;
});
if (settings.control_display == 'yes') {
panoramaViewport.find('.panorama-control').show();
} else if (settings.control_display == 'auto') {
panoramaViewport.bind('mouseover', function(){
$(this).find('.panorama-control').show();
return false;
}).bind('mouseout', function(){
$(this).find('.panorama-control').hide();
return false;
});
}
$(this).parent().css('margin-left', '-'+settings.start_position+'px');
if (settings.auto_start)
panorama_animate(panoramaContainer, elemWidth, settings);
});
function panorama_animate(element, elemWidth, settings) {
currentPosition = 0-parseInt($(element).css('margin-left'));
if (settings.direction == 'right') {
$(element).animate({marginLeft: 0}, ((settings.speed / elemWidth) * (currentPosition)) , 'linear', function (){
if (settings.mode_360) {
$(element).css('marginLeft', '-'+(parseInt(parseInt(elemWidth))+'px'));
panorama_animate(element, elemWidth, settings);
}
});
} else {
var rightlimit;
if (settings.mode_360)
rightlimit = elemWidth;
else
rightlimit = elemWidth-settings.viewport_width;
$(element).animate({marginLeft: -rightlimit}, ((settings.speed / rightlimit) * (rightlimit - currentPosition)), 'linear', function (){
if (settings.mode_360) {
$(element).css('margin-left', 0);
panorama_animate(element, elemWidth, settings);
}
});
}
}
};
$(document).ready(function(){
$("img.panorama").panorama();
});
in})(jQuery);
https://jsfiddle.net/pm6swLxa/
You code use css animations
HTML
<div id="img_container" class="pano slide"></div>
CSS
#img_container {
width:400px;
height: 200px;
overflow: hidden;
background: url('http://www.the-farm.net/piccies/pano2.jpg');
background-size: auto 100%;
background-position: right;
animation: back-and-forth 5s infinite;
}
#keyframes back-and-forth {
0% {
background-position: right;
}
50% {
background-position: left;
}
100% {
background-position: right;
}
}

setInterval wont work if timing is too short

I have a setInterval function that wont execute if the increment is less than 101ms. The timing will go any number above 100ms. I want to be able to increment the function by 10ms. offY and strtPos also become undefined when the timing goes below 101ms. How do I make it work the same as it is, but instead, have it incremented by 10ms?
var strtPos;
var offY;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 101); //<-- When I change that value to below 101, it prevents the code from working
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>
The short answer is you need to give offY a value that is not undefined initially, so I've rearranged the variables at the top of your code.
Originally, offY only gets a value after ~100ms (setInterval(st, 100)), and without a value that is not undefined the otherfunction's calculations won't work. So you needed the st function to execute first, hence requiring a value > 100.
var strtPos;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var offY = obj.offsetTop;
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 10);
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>

TypeError using QueryLoader plugin

For page loader i have used the plugin. Following is js:
var QueryLoader = {
overlay: "",
loadBar: "",
preloader: "",
items: new Array(),
doneStatus: 0,
doneNow: 0,
selectorPreload: "body",
ieLoadFixTime: 2000,
ieTimeout: "",
init: function() {
if (navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/) == "MSIE 6.0,6.0") {
//break if IE6
return false;
}
if (QueryLoader.selectorPreload == "body") {
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
} else {
$(document).ready(function() {
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
});
}
//help IE drown if it is trying to die :)
QueryLoader.ieTimeout = setTimeout("QueryLoader.ieLoadFix()", QueryLoader.ieLoadFixTime);
},
ieLoadFix: function() {
var ie = navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/);
if (ie[0].match("MSIE")) {
while ((100 / QueryLoader.doneStatus) * QueryLoader.doneNow < 100) {
QueryLoader.imgCallback();
}
}
},
imgCallback: function() {
QueryLoader.doneNow ++;
QueryLoader.animateLoader();
},
getImages: function(selector) {
var everything = $(selector).find("*:not(script)").each(function() {
var url = "";
if ($(this).css("background-image") != "none") {
var url = $(this).css("background-image");
} else if (typeof($(this).attr("src")) != "undefined" && $(this).attr("tagName").toLowerCase() == "img") {
var url = $(this).attr("src");
}
url = url.replace("url(\"", "");
url = url.replace("url(", "");
url = url.replace("\")", "");
url = url.replace(")", "");
if (url.length > 0) {
QueryLoader.items.push(url);
}
});
},
createPreloading: function() {
QueryLoader.preloader = $("<div></div>").appendTo(QueryLoader.selectorPreload);
$(QueryLoader.preloader).css({
height: "0px",
width: "0px",
overflow: "hidden"
});
var length = QueryLoader.items.length;
QueryLoader.doneStatus = length;
for (var i = 0; i < length; i++) {
var imgLoad = $("<img></img>");
$(imgLoad).attr("src", QueryLoader.items[i]);
$(imgLoad).unbind("load");
$(imgLoad).bind("load", function() {
QueryLoader.imgCallback();
});
$(imgLoad).appendTo($(QueryLoader.preloader));
}
},
spawnLoader: function() {
if (QueryLoader.selectorPreload == "body") {
var height = $(window).height();
var width = $(window).width();
var position = "fixed";
} else {
var height = $(QueryLoader.selectorPreload).outerHeight();
var width = $(QueryLoader.selectorPreload).outerWidth();
var position = "absolute";
}
var left = $(QueryLoader.selectorPreload).offset()['left'];
var top = $(QueryLoader.selectorPreload).offset()['top'];
QueryLoader.overlay = $("<div></div>").appendTo($(QueryLoader.selectorPreload));
$(QueryLoader.overlay).addClass("QOverlay");
$(QueryLoader.overlay).css({
position: position,
top: top,
left: left,
width: width + "px",
height: height + "px"
});
QueryLoader.loadBar = $("<div></div>").appendTo($(QueryLoader.overlay));
$(QueryLoader.loadBar).addClass("QLoader");
$(QueryLoader.loadBar).css({
position: "relative",
top: "50%",
width: "0%"
});
},
animateLoader: function() {
var perc = (100 / QueryLoader.doneStatus) * QueryLoader.doneNow;
if (perc > 99) {
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function() {
QueryLoader.doneLoad();
});
} else {
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function() { });
}
},
doneLoad: function() {
//prevent IE from calling the fix
clearTimeout(QueryLoader.ieTimeout);
//determine the height of the preloader for the effect
if (QueryLoader.selectorPreload == "body") {
var height = $(window).height();
} else {
var height = $(QueryLoader.selectorPreload).outerHeight();
}
//The end animation, adjust to your likings
$(QueryLoader.loadBar).animate({
height: height + "px",
top: 0
}, 500, "linear", function() {
$(QueryLoader.overlay).fadeOut(800);
$(QueryLoader.preloader).remove();
});
}
}
In my html file, I used following Javascript:
<script type='text/javascript'>
QueryLoader.init();
</script>
And css is as following:
.QOverlay {
background-color: #000000;
z-index: 9999;
}
.QLoader {
background-color: #CCCCCC;
height: 1px;
}
I used this for simple example it works well.
But when I used this for my site it is giving error in js file as following:
TypeError: $(...).offset(...) is undefined
var left = $(QueryLoader.selectorPreload).offset()['left'];
So please can you help out from this issue:
Thanks in advance..
Your plugin is not really one. Go see the documentation to see more details.
Anyway, even if it's not a plugin, it could work as an object using some jQuery functions.
First, you shouldn't call the object inside the object function.
IE :
QueryLoader.ieTimeout = setTimeout("QueryLoader.ieLoadFix()", QueryLoader.ieLoadFixTime);
Here, you got your first error which you could have seen in the console. It should be :
this.ieTimeout = setTimeout(this.ieLoadFix, this.ieLoadFixTime);
You can start debugging like this, up to your initial error here.

Very Simple, Very Smooth, JavaScript Marquee

I'm trying to find a very simple and smooth, lightweight javascript or jquery marquee. I already tried silk marquee or something, but it wouldn't work with the application I was using. So the simpler and shorter, the better - and easier to debug. Does anybody know of a easy to implement javascript replacement for the marquee?
Pastebin
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
var tWidth='300px'; // width (in pixels)
var tHeight='25px'; // height (in pixels)
var tcolour='#ffffcc'; // background colour:
var moStop=true; // pause on mouseover (true or false)
var fontfamily = 'arial,sans-serif'; // font for content
var tSpeed=3; // scroll speed (1 = slow, 5 = fast)
// enter your ticker content here (use \/ and \' in place of / and ' respectively)
var content='Are you looking for loads of useful information <a href="http:\/\/javascript.about.com\/">About Javascript<\/a>? Well now you\'ve found it.';
var cps=-tSpeed; var aw, mq; var fsz = parseInt(tHeight) - 4; function startticker(){if (document.getElementById) {var tick = '<div style="position:relative;width:'+tWidth+';height:'+tHeight+';overflow:hidden;background-color:'+tcolour+'"'; if (moStop) tick += ' onmouseover="cps=0" onmouseout="cps=-tSpeed"'; tick +='><div id="mq" style="position:absolute;right:0px;top:0px;font-family:'+fontfamily+';font-size:'+fsz+'px;white-space:nowrap;"><\/div><\/div>'; document.getElementById('ticker').innerHTML = tick; mq = document.getElementById("mq"); mq.style.right=(10+parseInt(tWidth))+"px"; mq.innerHTML='<span id="tx">'+content+'<\/span>'; aw = document.getElementById("tx").offsetWidth; lefttime=setInterval("scrollticker()",50);}} function scrollticker(){mq.style.right = (parseInt(mq.style.right)>(-10 - aw)) ?
mq.style.right = parseInt(mq.style.right)+cps+"px": parseInt(tWidth)+10+"px";} window.onload=startticker;
</script>
</head>
<body>
<div id="ticker">
this is a simple scrolling text!
</div>
</body>
</html>
hiya simple demo from recommendations in above comments: http://jsfiddle.net/FWWEn/
with pause functionality on mouseover: http://jsfiddle.net/zrW5q/
hope this helps, have a nice one, cheers!
html
<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>​
Jquery code
(function($) {
$.fn.textWidth = function(){
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent' : that.css('text-indent'),
'overflow' : that.css('overflow'),
'white-space' : that.css('white-space')
},
marqueeCss = {
'text-indent' : width,
'overflow' : 'hidden',
'white-space' : 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
i = 0,
stop = textWidth*-1,
dfd = $.Deferred();
function go() {
if(!that.length) return dfd.reject();
if(width == stop) {
i++;
if(i == args.count) {
that.css(css);
return dfd.resolve();
}
if(args.leftToRight) {
width = textWidth*-1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if(args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if(args.leftToRight) {
width = textWidth*-1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
})(jQuery);
$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })​
I've made very simple function for marquee. See: http://jsfiddle.net/vivekw/pHNpk/2/
It pauses on mouseover & resumes on mouseleave. Speed can be varied. Easy to understand.
function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;
function scroll() {
if (b.position().left <= -width) {
b.css('left', start_pos);
scroll();
}
else {
time = (parseInt(b.position().left, 10) - end_pos) *
(10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
b.animate({
'left': -width
}, time, 'linear', function() {
scroll();
});
}
}
b.css({
'width': width,
'left': start_pos
});
scroll(a, b);
b.mouseenter(function() { // Remove these lines
b.stop(); //
b.clearQueue(); // if you don't want
}); //
b.mouseleave(function() { // marquee to pause
scroll(a, b); //
}); // on mouse over
}
$(document).ready(function() {
marquee($('#display'), $('#text')); //Enter name of container element & marquee element
});
I just created a simple jQuery plugin for that. Try it ;)
https://github.com/aamirafridi/jQuery.Marquee
The following works:
http://jsfiddle.net/xAGRJ/4/
The problem with your original code was you are calling scrollticker() by passing a string to setInterval, where you should just pass the function name and treat it as a variable:
lefttime = setInterval(scrollticker, 50);
instead of
lefttime = setInterval("scrollticker()", 50);
Why write custom jQuery code for Marquee... just use a plugin for jQuery - marquee() and use it like in the example below:
First include :
<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>
and then:
//proporcional speed counter (for responsive/fluid use)
var widths = $('.marquee').width()
var duration = widths * 7;
$('.marquee').marquee({
//speed in milliseconds of the marquee
duration: duration, // for responsive/fluid use
//duration: 8000, // for fixed container
//gap in pixels between the tickers
gap: $('.marquee').width(),
//time in milliseconds before the marquee will start animating
delayBeforeStart: 0,
//'left' or 'right'
direction: 'left',
//true or false - should the marquee be duplicated to show an effect of continues flow
duplicated: true
});
If you can make it simpler and better I dare you all people :). Don't make your life more difficult than it should be. More about this plugin and its functionalities at: http://aamirafridi.com/jquery/jquery-marquee-plugin
I made my own version, based in the code presented above by #Tats_innit .
The difference is the pause function. Works a little better in that aspect.
(function ($) {
var timeVar, width=0;
$.fn.textWidth = function () {
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function (args) {
var that = $(this);
if (width == 0) { width = that.width(); };
var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);
function go() {
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i <= args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width=width-2;
}
if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
if (args.pause == true) { clearTimeout(timeVar); };
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
timeVar = setTimeout(function () { go() }, 100);
return dfd.promise();
};
})(jQuery);
usage:
for start: $('#Text1').marquee()
pause: $('#Text1').marquee({ pause: true })
resume: $('#Text1').marquee({ pause: false })
My text marquee for more text,
and position absolute enabled
http://jsfiddle.net/zrW5q/2075/
(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
position: 'absolute',
visibility: 'hidden',
height: 'auto',
width: 'auto',
'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, {
count: -1,
speed: 1e1,
leftToRight: false
}, args),
i = 0,
stop = textWidth * -1,
dfd = $.Deferred();
function go() {
if (that.css('overflow') != "hidden") {
that.css('text-indent', width + 'px');
return false;
}
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i == args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {
$(this).removeAttr("style");
}).mouseout(function () {
$(this).marquee();
});
})(jQuery);
Responsive resist jQuery marquee simple plugin. Tutorial:
// start plugin
(function($){
$.fn.marque = function(options, callback){
// check callback
if(typeof callback == 'function'){
callback.call(this);
} else{
console.log("second argument (callback) is not a function");
// throw "callback must be a function"; //only if callback for some reason is required
// return this; //only if callback for some reason is required
}
//set and overwrite default functions
var defOptions = $.extend({
speedPixelsInOneSecound: 150, //speed will behave same for different screen where duration will be different for each size of the screen
select: $('.message div'),
clickSelect: '', // selector that on click will redirect user ... (optional)
clickUrl: '' //... to this url. (optional)
}, options);
//Run marque plugin
var windowWidth = $(window).width();
var textWidth = defOptions.select.outerWidth();
var duration = (windowWidth + textWidth) * 1000 / defOptions.speedPixelsInOneSecound;
var startingPosition = (windowWidth + textWidth);
var curentPosition = (windowWidth + textWidth);
var speedProportionToLocation = curentPosition / startingPosition;
defOptions.select.css({'right': -(textWidth)});
defOptions.select.show();
var animation;
function marquee(animation){
curentPosition = (windowWidth + defOptions.select.outerWidth());
speedProportionToLocation = curentPosition / startingPosition;
animation = defOptions.select.animate({'right': windowWidth+'px'}, duration * speedProportionToLocation, "linear", function(){
defOptions.select.css({'right': -(textWidth)});
});
}
var play = setInterval(marquee, 200);
//add onclick behaviour
if(defOptions.clickSelect != '' && defOptions.clickUrl != ''){
defOptions.clickSelect.click(function(){
window.location.href = defOptions.clickUrl;
});
}
return this;
};
}(jQuery));
// end plugin
Use this custom jQuery plugin as bellow:
//use example
$(window).marque({
speedPixelsInOneSecound: 150, // spped pixels/secound
select: $('.message div'), // select an object on which you want to apply marquee effects.
clickSelect: $('.message'), // select clicable object (optional)
clickUrl: 'services.php' // define redirection url (optional)
});
Marquee using CSS animations.
`<style>
.items-holder {
animation: moveSlideshow 5s linear infinite;
}
.items-holder:hover {
animation-play-state: paused;
}
#keyframes moveSlideshow {
100% {
transform: translateX(100%);
}
}
</style>`
I try use only css for it this link.
<style>
.header {
background: #212121;
overflow: hidden;
height: 65px;
position: relative;
}
.header div {
display: flex;
flex-direction: row;
align-items: center;
overflow: hidden;
height: 65px;
transform: translate(100%, 0);
}
.header div * {
font-family: "Roboto", sans-serif;
color: #fff339;
text-transform: uppercase;
text-decoration: none;
}
.header div img {
height: 60px;
margin-right: 20px;
}
.header .ticker-wrapper__container{
display: flex;
flex-direction: row;
align-items: center;
position: absolute;
top: 0;
right: 0;
animation: ticker 30s infinite linear forwards;
}
.header:hover .ticker-wrapper__container{
animation-play-state: paused;
}
.ticker-wrapper__container a{
display: flex;
margin-right: 60px;
align-items: center;
}
#keyframes ticker {
0% {
transform: translate(100%, 0);
}
50% {
transform: translate(0, 0);
}
100% {
transform: translate(-100%, 0);
}
}
</style>

Categories

Resources