Controlling Jquery scrolltop speed - javascript

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.

Related

Jquery image animation

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">

How can I fix the warping issue in jQuery?

What my blue fish should do: Move around to random positions on the screen and when you touch it with the mouse, it should flee to a random location fast, then continue swimming.
What my blue fish does: After fleeing, it warps to a random location.
How can I fix the warping, so that the fish continues swimming from its current position after fleeing?
/*globals $:false, window:false*/
$("#blueFishId").animate({}, function() {
blueFish(this)
});
function blueFish(IdRef) {
var x = Math.floor(Math.random() * ($(window).width() - $(IdRef).width()))
var y = Math.floor(Math.random() * ($(window).height() - $(IdRef).height()))
$(IdRef).delay(500).animate({
top: y,
left: x
}, 5000, function() {
blueFish(IdRef);
});
}
$("#blueFishId").on("mouseenter", function() {
var x = Math.floor(Math.random() * ($(window).width() - $("#blueFishId").width()))
var y = Math.floor(Math.random() * ($(window).height() - $("#blueFishId").height()))
$("#blueFishId").animate({
top: y,
left: x
}, 1000);
});
img {
position: relative;
}
#blueFishId {
height: auto;
width: auto;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="blueFish" id="blueFishId" src="images/fish2.png">
To fix this you need to clear the queued animation on mouseover and you also need to stop the current animation that's executing. You can achieve this by calling stop() and also putting the delay() call after the animate(). Also note that you can DRY up the logic by just calling your function from within mouseenter after you stop() the current animation. Try this:
var $fish = $('#blueFishId');
function moveFish($fish) {
var x = Math.floor(Math.random() * ($(window).width() - $fish.width()))
var y = Math.floor(Math.random() * ($(window).height() - $fish.height()))
$fish.animate({
top: y,
left: x
}, 5000, function() {
moveFish($fish);
}).delay(500);
}
$fish.on("mouseenter", function() {
$fish.stop(true);
moveFish($fish);
});
moveFish($fish);
img {
position: relative;
}
#blueFishId {
height: auto;
width: auto;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="blueFish" id="blueFishId" src="images/fish2.png">
You may also want to consider making the fish move a greater distance on mouseenter to make it look more like it's 'fleeing' the mouse.

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';

Set height to element dynamically and change height on window resizes using jQuery

I am working on a project where I need to set the height dynamically, means when the page loads the height must be set to itself and it's a responsive box, so when the browser window resizes the height increases but I am unable to fix it. I shared the script below. It's not something to calculate with window height or else, it should set and change the height based on window resizes. Any help?
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
var itemHeight = $('.item').height();
$('.item').each(function() {
$(this).css({
height: itemHeight + 'px'
});
});
$(window).on('resize', function(event) {
$('.item').each(function() {
$(this).css({
height: itemHeight + 'px'
});
});
});
Please see the jsfiddle:
https://jsfiddle.net/rj1xy1ue/
I will suggest you to use % instead of px. px will fix the value, but % will automatically compute the values based on the available viewport.
var itemHeight = 20; //Sample value
$('.item').each(function () {
$(this).css({
height: itemHeight + '%'
});
});
Simply, find the perfect value of itemHeight which is ideal for your case and then assign it. No need for extra resize event handler.
In your current code, in resize event you are assigning same value again which doesn't make any difference to the dimension. Hence you are not able to see the difference on resize.
Try this:
var itemHeight = $('.item').height();
function resizer() {
$('.item').each(function () {
$(this).css({
height: itemHeight + 'px'
});
});
}
$(window).on('resize', function (event) {
itemHeight = 350 //any different value
resizer();
});
Sample Demo: http://jsfiddle.net/lotusgodkk/GCu2D/822/
Note: Make sure you change the value of itemHeight in resize handler
What you are describing is called Responsive design.
A key idea in responsive design is to use percentages in place of px.
See these references:
WebDesignerWall on Responsive Design
CSS-Tricks question
for some ideas.
Note that using percentages for height is not as important as for width. You might also want to check out
Responsive Layouts with flexbox
On the jQuery side, you can use something like this:
var win = $(window);
$(function() {
win_size_recalc();
$(window).on('resize', function(){
win_size_recalc();
});
}); //end document.ready
function win_size_recalc(){
ww = win.width();
//EXAMPLE OF USE:
if (ww <= 550){
$('#header').css({'height':'50px'});
$('nav').css({'height':'55px'});
$('#headerstuff').css({'width':'98%'});
}else if (ww <= 650){
$('#headerstuff').css({'width':'98%'});
$('nav').css({'width':'98%'});
}else if (ww <= 770){
$('#headerstuff').css({'width':'90%'});
$('nav').css({'width':'90%'});
}else if (ww <= 850){
$('#headerstuff').css({'width':'90%'});
$('nav').css({'width':'90%'});
}else if (ww <= 900){
//etc etc
}
You might also want to check out CSS media queries, which is the CSS way of doing what we just did above using jQuery:
https://css-tricks.com/css-media-queries/
https://css-tricks.com/snippets/css/media-queries-for-standard-devices/
and more
I am not sure if I am able to understand your question correctly but I'll give a try based on what I could understand anyway.
You want the .item objects to resize on resize event of window object such that you want to start with whatever .height() these .item objects have, and then scale proportionally to the window height on resize.
If this is what you wanted, the solution is pretty simple. You calculate the difference in .height() of window object, and you add (or remove) that difference to the default .height() of .item objects.
Take a look at this jsFiddle and resize the height of the result panel to observe the difference in height of the .item objects. And tell me if this is what you were expecting the result to be.
The JavaScript used in the example is as below:
var items = $('.item');
var windowObject = $(window);
var defaultWinHeight = windowObject.height();
var defaultItemHeight = items.height();
items.css({ height: defaultItemHeight + 'px' });
windowObject.on('resize', function (event) {
var currWinHeight = windowObject.height();
var difference = currWinHeight - defaultWinHeight;
var itemHeight = defaultItemHeight + difference;
items.css({ height: itemHeight + 'px' });
});
Apologies if this is not what you were looking for. Hope it helps in some way though.
Update #1:
And here is another resulting jsFiddle of the same experiment but involving calculating percentages.
JavaScript:
var items = $('.item');
var windowObject = $(window);
var defaultWinHeight = windowObject.height();
var defaultItemHeight = items.height();
items.css({ height: defaultItemHeight + 'px' });
windowObject.on('resize', function (event) {
var currWinHeight = windowObject.height();
var currWinPercent = (currWinHeight/defaultWinHeight)*100;
var itemHeight = (currWinPercent/100)*defaultItemHeight;
items.css({ height: itemHeight + 'px' });
});
As others have noted, the main problem is you're only calculating itemHeight once. This fiddle shows a more modern way to use jQuery to achieve your goals (use on instead of bind):
http://jsfiddle.net/sean9999/7j4sz3wv/6/
$(function(){
"use strict";
var resizeBoxes = function(){
var padding = 25;
var parentHeight = $('body').height() - padding;
$('#debug').html( 'parent height = ' + parentHeight );
$('.item').css('height',parentHeight);
};
$(window).on('resize',resizeBoxes);
resizeBoxes();
});
body {
position: absolute;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background-color: #FED;
}
#debug {
width: 50%;
float: right;
height: 100%;
margin-top: 25%;
font-weight: bold;
color: navy;
}
.item {
min-width: 25px;
border: 2px solid blue;
background-color: silver;
min-height: 100px;
float: left;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div id="debug"></div>

How do I stop a element hit area from moving off the screen when window is scrolled, JavaScript/Jquery?

When I scroll the window/page the hit area denoted by the 100 value in n.mousePositionY('.nav', 100); moves off the page/screen. Is there a way of always having that 100 value stay on the screen irrespective of scrolling...it's for a navigation menu I'm working on. Here's the code so far:
//$('.nav').hide();
var n = new Object();
n.mousePositionY = function(className, y){
$(window).mousemove(function(e){
if(e.pageY < y){ $(className).fadeIn(200); }
if(e.pageY > y){ $(className).fadeOut(200); }
});
}
n.mousePositionY('.nav', 100);
Any help would greatly be appreciated, thanks
If you need a hit area, why don't you use a fixed element and its mouseover event?
http://jsfiddle.net/bZdaU/
<div id="hitme"></div>
#hitme {
position: fixed;
top: 100;
left: 30px;
height: 30px;
width: 100px;
}
$('#hitme').mouseover( function() {
console.log('mouse in hit area');
});

Categories