Jquery image animation - javascript

I'm newbie of Javascript and Jquery.
I am learning img animation and I have a question.
If I want to move the image from bottom left to the top right in window. Is there any better way than my code?
My code doesn't' work then I expected.
here is my code
$(document).ready(function () {
function startMoving() {
var img = $("#imageId");
var imgWidth = img.width();
var imgHeight = img.height();
var screenWidth = $(window).innerWeight();
var screenHeight = $(window).innerHeight();
var c = Math.sqrt((screenWidth*screenWidth+screenHeight*screenWidth));
var movement = c/10 // This is for the step of movement
var zScale = (screenWidth+screenHeight)/2;
var imgZScale = (imgHeight+imgWidth)/2;
console.log(zScale);
console.log(imgHeight);
img.animate({
"left": "+="+movement,
"top": "-="+movement
},"slow");
}
setInterval(function(){
startMoving();
},1000)
});
If the image at the corner how can I restart image movement again from bottom left?
Thank you in advance!

You can simplify things using CSS transitions instead of JQuery animate(). This feature is easy to manage and with less code.
I've just created an initial CSS state and a final stage (.end), using jQuery to toggle the class to switch from initial/final position.
$(document).ready(function () {
setInterval(function(){
$("#imageId").toggleClass("end");
},2000);
});
img{
position: absolute;
width: 5vw;
height: 5vw;
top: 95vh;
left: 0;
transition: linear 1s;
}
img.end{
top: 0;
left: 95vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="imageId" class="start" width="48" height="48">

Related

Custom scroll bar flows out of screen

I'm trying to make my own scroll bar, and so far it's working fine, for this small exception.
When I reach the bottom of the page, the bar handle goes under the viewport.
Gif of what's happening:
I know it has to do with the CSS, but I'm unsure on how to set it correctly. Foundation's .off-canvas-content has a class added named .full-height, and the height property is added so that the scroll bar won't be tied to that element.
The scroll bar markup is added to div.content, which is where all the remaining content will be.
I'm trying to get the handle bar to stop at the bottom of the container, when the user has scrolled all the way of the bottom of the document, but haven't found a way to do this correctly.
CSS:
.scroll-container {
position: fixed;
right: 50px;
top: 0;
height: 100%;
width: 7.5px;
background-color: rgba(55,55,55,.3);
}
.scroll-bar {
position: relative;
top: 0;
height: 20%;
width: 100%;
background-color: #6A1B9A;
}
.full-height {
height: 100vh;
min-height: 100vh;
}
.content {
float: left;
width: 100%;
height: 100%;
display: block;
padding: 10px 20px;
overflow-y: scroll;
}
JS:
(function($) {
$.fn.scroller = function() {
var self = this,
scrollBarDrag = false,
docHeight = $(document).height();
var scrollContainer = document.createElement('div'),
scrollBar = document.createElement('div');
scrollContainer.className = 'scroll-container';
scrollBar.className = 'scroll-bar';
scrollContainer.appendChild(scrollBar);
self[0].appendChild(scrollContainer);
self.on('scroll', function() {
var top = $(this).scrollTop();
setScrollBarTop(top);
});
function setScrollBarTop (top) {
scrollBar.style.top = top + 'px';
}
};
})(jQuery);
I tried using plugins for this, but they don't simulate the scroll bar as intended (missing mouse wheel click and drag to scroll), so I decided to make my own, lightweight version of it. Any suggestions about using plugins, albeit appreciated, will be disregarded and not accepted as an answer.
With absolute positioning:
I think you forgot to account for the scrollbar's height. Lets say the scrollbar is 100px tall and your page is 500px tall, you are only able to move the scrollbar by 400px, not all 500.
Find out the difference between your scrollbar height and the document height, find the ratio of how they compare, and apply that to your new scrollbar position.
havent tested it, but something like;
var heightToWorkWith = docHeight - scrollBarHeight;
var ratio = heightToWorkWith / docHeight;
function setScrollBarTop (top) {
scrollBar.style.top = (top * ratio) + 'px';
}
Have found a solution regarding this, was quite a bit of trial and error, but managed to find it in the end. Hope it can be of use to some of you.
Edited it to a more revised version.
self.on('scroll', function() {
elHeight = self.height();
docHeight = $(document).height();
var sTop = self[0].scrollTop;
var sHeight = self[0].scrollHeight;
var sBHeight = $(scrollBar).height();
var ratio = (elHeight - $(scrollBar).height()) / elHeight;
var currentPosY = (sTop / (sHeight - docHeight)) * 100;
scrollBar.style.top = (currentPosY * ratio) + '%';
});
You can get scroll ratio by doing this:
(thumbHeight / containerHeight) + 1
containerHeight is not the scroll area height, but the actual overflow: hidden container.
When you get the scrollTop value just multiply it with your ratio. Like this:
thumbPosition.top = el.scrollTop * ratio + 'px';

responsive issue jquery click slider

I have a click slide that goes back and forward through the images,
But it doesnt scale or act responsive when on smaller window because obviously the width is set absolutely with pixels in the CSS and as the variable in my function.
If i change this I'm not sure how it'll work though as it slides back and forth the width of each img (607px)
Anyone got ideas?? Or a better way to do this??
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="slider">
<ul class="slides">
<li class="slide"><img src="images/banner1.jpg" class="img-responsive"></li>
<li class="slide"><img src="images/banner2.jpg" class="img-responsive"></li>
<li class="slide"><img src="images/banner3.jpg" class="img-responsive"></li>
<li class="slide"><img src="images/banner1.jpg" class="img-responsive"></li>
</ul>
</div>
CSS:
#slider {
width: 607px;
height: 248px;
overflow: hidden;
}
#slider .slides {
display: block;
width: 6000px;
height: 248px;
margin: 0px;
padding: 0px;
}
#slider .slide {
float: left;
list-style-type: none;
}
JS:
(function() {
var width = 607;
var slideSpeed = 300;
var currentSlide = 1;
var $slider = $('#slider');
var $slideContainer = $slider.find('.slides');
var $slides = $slideContainer.find('.slide');
var totalLength = $slides.length;
$('#button-next').on('click', function(){
$slideContainer.animate({'margin-left': '-='+width}, slideSpeed, function(){
currentSlide++;
if(currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', '0');
}
});
});
$('#button-prev').on('click', function(){
if(currentSlide === 1) {
var pos = -1 * (width * ($slides.length -1));
$slideContainer.css('margin-left', pos);
$slideContainer.animate({'margin-left': '+='+width}, slideSpeed);
currentSlide = $slides.length - 1;
} else {
$slideContainer.animate({'margin-left': '+='+width}, slideSpeed);
currentSlide--;
}
});
});
In order to make the slider you have posted responsive you will need to set your fixed dimensions in your CSS to fluid width.
Like this:
.slider {
position: relative;
padding: 10px;
}
.slider-frame {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
white-space: nowrap;
}
.slide {
width: 100%;
display: inline-block;
}
.control {
width: 49%;
}
A wrote a very simple demo slider that hardly has any functionality just to serve the purpose of this explanation:
http://codepen.io/nicholasabrams/pen/aOLoYM
Resize your screen. The slides stay the width of the screen because the .slide and .slider are both set to 100% of the screens width.
Dont forget to add your own functionality for next and prev that adjusts each slide progression distance according to the width of the slides in the slider.
Also see here:
How to make a image slider responsive?
And this is a good tutorial with somewhat quality code used. The slide comes out usable as well!
http://www.barrelny.com/blog/building-a-jquery-slideshow-plugin-from-scratch/
Hope this helps!
UPDATE:
Since the OP stated that the issue is with the js I dug up a simple slider I wrote a while back, here is the javascript/jQuery:
$(function(){
$.fn.someCustomSlider = function (autoplay, velocity){
var sliderProps = [
// props n methods, accessible through data-slider-* attributes
{
settings : {
invokeBecause : $('[data-widget~="slider"]'),
autoplay : autoplay,
speed : velocity,
},
bindings : {
slideRail : $('[data-function~="slide-rail"]'),
nextButton : $('[data-function~="next"]'),
prevButton : $('[data-function~="prev"]'),
playButton : $('[data-function~="play"]'),
pauseButton : $('[data-function~="pause"]'),
stopButton : $('[data-function~="stop"]')
// attach this functionality to the DOM
},
methods : {
slideNext : function(){ slideRail.animate({left: '-=100%'}, velocity) },
slidePrev : function(){ slideRail.animate({left: '+=100%'}, velocity) },
slideRestart : function(){ slideRail.animate({left: '0%'}, velocity) },
pause : function(){ window.sliderTimer = setInterval(slideNext, velocity) }
}
}
]
$.each(sliderProps, function(){
// iterate through all of the slider objects properties
window.SliderProps = this;
// set slider props to be accessible to the global scope
});
// slider props stored as vars
var slideRail = SliderProps.bindings.slideRail;
var play = SliderProps.bindings.playButton;
var next = SliderProps.bindings.nextButton;
var prev = SliderProps.bindings.prevButton;
var pause = SliderProps.bindings.pauseButton;
var stop = SliderProps.bindings.stopButton;
var i = 0;
function slideNext(){
var slideNext = SliderProps.methods.slideNext();
}
function slidePrev(){
var slidePrev = SliderProps.methods.slidePrev();
}
function slideStop(){
/*slideRail.stop(); */
window.clearInterval( sliderTimer )
}
function slideRestart(){
var slidePrev = SliderProps.methods.slideRestart();
slideRail.stop();
window.clearInterval( sliderTimer )
}
function autoPlay(){
SliderProps.methods.pause()
}
// elemen -> event delegation -> function()
next.click(slideNext)
prev.click(slidePrev)
stop.click(slideRestart)
pause.click(slideStop)
play.click(autoPlay)
} // close function slider()
someCustomSlider(true, 1000);
});
http://codepen.io/anon/pen/eytrh
This was a basic version that I eventually extended but for simplicity sake, this should be just perfect I imagine.
When working with responsive design, thinking in terms of pixels is a bad practice.
Give your slider and each slide a width of 100vw instead of 607px. That would make it equivalent to one "viewport width". In your JavaScript try modifying the width variable to be the string 100vw as well. Make sure to include the unit.
For more information on CSS units refer here.

How to make an element jump from top to the bottom of the web page and back to the top?

I have an element div in a shape of a ball. What I am trying to do is, when I refresh the page I want to the ball to fall to the bottom of the webpage and then bounce back up to the top of the page.
This is my jQuery function where the ball falls to the bottom of the web page
$(document).ready(function(){
$("div").animate({ top: '+=585'}, 400);
});
Am I using a correct approach? Should I use slideDwon and slideUp instead?
Try utilizing jQuery UI .effect()
$(function() {
var div = $("div");
// `elem`: element to apply bounce effect,
// `n`: number of bounce effects to apply to `elem`
var bounce = function bounce(elem, n) {
var fx = function fx(el) {
return (el || $(this))
.effect({
effect: "bounce",
easing: "swing",
duration: 400,
distance: window.innerHeight
- (el.height() + el.offset().top * 1.5),
direction: "down",
times: 1
}).promise()
};
return fx(elem).then.apply(elem, $.map(Array(n - 1), function() {
return fx(elem)
}));
};
bounce(div, 1).then(function(el) {
// do stuff when bounce effect complete
console.log("complete", el)
});
});
div {
position: relative;
width: 100px;
height: 100px;
background: rgb(212, 98, 44);
border: 2px solid navy;
border-radius: 50%;
}
<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"
rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div></div>
Take advantage of jQuery's animation chainability. Also, you probably shouldn't assume a static value of 585 will be suitable for every screen size. I suggest using calculated values for generating the offsets, check this fiddle:
$(document).ready(function () {
var viewportH = $(window).height();
var elem = $('div');
var elemH = elem.height();
elem.animate({
top: '+=' + (viewportH - elemH) // bottom of screen
}, 400).animate({
top: '-=' + (viewportH - elemH) // original position
});
});
Using this HTML :
<div id="myDiv" class="myRelativeDiv">test</div>
1st step is to set the position of your div as "relative" :
.relative {
position:relative;
}
2nd step is animate with Jquery (You can chain many animate):
$(function() {
$("#myDiv").animate({ top: '+=585'}, 400).animate({ top: '0'}, 400);
});
JsFiddle
$(document).ready(function(){
$("div").animate({ top: '+=585'}, 400);
setTimeout(
function()
{
$("div").animate({ top: '-=585'}, 400);
}, 400);
});

jQuery image carousel not sliding

Trying create an image carousel whose speed relies upon mouse positioning (i.e. if the mouse is close to the edge of the screen it moves fast, directly in the middle it doesn't move etc.) My issue right now being that the image carousel doesn't move at all. Could be a variety of reasons for it not working, but I am not really sure as to why it isn't working or even if this is a 'good' carousel algorithm.
Created a speed function which I am positive needs work, but I will only be able to know that once I see the image carousel actually moving.
Fiddle
JQuery
$(document).ready(function(){
$('.carousel').mousemove(function(e) {
var mpos = e.pageX;
var speed = $(this).getSpeed(mpos);
var dir = $(this).getDir(mpos);
var $ul = $(this).children('ul');
var cwidth = $ul.width();
$('#speed').html(speed);
if(speed != 0) {
if(dir == -1){
$ul.animate({
left: 0
}, speed, 'linear');
}
if(dir == 1){
$ul.animate({
left: -cwidth
}, speed, 'linear');
}
}
});
});
$.fn.getSpeed = function(mpos){
var width = $(this).width();
var center = width/2;
var ps = (mpos-center)/10;
var speed = ps * ps - (width % 100);
if(speed >= 0) return speed;
else return 0;
};
$.fn.getDir = function(mpos){
var width = $(this).width();
var center = width/2;
if(mpos > center) return 1;
else return -1;
};
HTML
<div class="carousel">
<ul>
<li><img src="http://placehold.it/200x200"/></li>
<li><img src="http://placehold.it/200x200"/></li>
.
.
.
<li><img src="http://placehold.it/200x200"/></li>
</ul>
</div>
<div id="speed"></div>
You have to fix your code to actually do what you want, but the main problem of not animating is fixed if you add the following css:
.carousel ul {
position:relative;
left:0px;
always check the documentation if you run into trouble:
http://api.jquery.com/animate/
There are several problems you have here.
First problem you got is, that position "relative" or "absolute" are missing on the ul.
carousel {
position: relative;
width: 100%;
overflow: hidden;
height: 200px;
}
.carousel ul {
position: absolute;
display: block;
list-style: none;
white-space: nowrap;
}
Then you need to stop your animations before starting another:
$ul.stop().animate
But the biggest problem is, that your "speed" is not a real speed at all.
If your speed is "100", it is very fast. This means that the animation will be done within 100 milliseconds! Thats so fast that you cannot see the animation.
So if you are moving your mouse near to the middle of you gallery it's moving fast and on the edges outside it's moving slow.
You could fix your speed by subtracting your actual mpos-value from a maximum-speed:
var speed = ps * ps - (width % 100);
// SPEED FIX
speed = 5000 - (speed * 2);
Here is the fiddle:
http://jsfiddle.net/56rwR/1/
BUT!! this is buggy as hell because is has not a real speed.. only this animation time which is proportional to the ul-width..
I would recommend you to use a script like this here:
http://bxslider.com/examples/ticker
and write an hover event which increases/decreases the speed.

Controlling Jquery scrolltop speed

I have this code for moving the box using .scrollTop. Using this i code i was able to move the box from bottom to top, is there any other way to control the speed of scrolling every 100 pixel?
Here's my jquery:
$(document).ready(function () {
$(window).scroll(function () {
var x = $(document).scrollTop();
var dh = $(window).innerHeight();
var move = x / 100 * 100;
console.log(x);
$('.box').css('bottom', move);
}
});
});
and the css:
body {
height: 2000px;
}
.box {
width: 50px;
height: 50px;
background: #f00;
bottom: 0;
position: fixed;
}
Is there a way to do this? Thanks in advance guys. Have a nice day.
Not sure if this is exactly what you are getting at, if not, please be more specific as to what you are asking for. That said....
var move = x / 100 * 100;
Just change the numbers in the denominator. It alters the rate of scroll.

Categories