How to change element width on scroll? - javascript

I'm pretty new at coding, and right now I'm working on a small school assignment where the idea is to create a single serving site.
I want to make a face from the side with a nose that grows - from left to right - (exactly like Pinocchio) when scrolling the page.
Maybe the code I have written will help to explain what I want to do more accurately...
My question is: what should I do to have my nose element fixed centered to the left, and growing more and more to the right when scrolling? When I set the position to fixed my nose element disappears.
This is my source of inspiration/code -> http://jsfiddle.net/95EtZ/11/
Here is my code:
$(function() {
var Node = $('#container'),
BaseWidth = Node.width();
$(window).resize(function() {
$('#container').css({
top: ($(window).height() - $('#container').outerHeight()) / 2
});
});
$(window).resize();
var $scrollingDiv = Node;
$(window).scroll(function() {
var winScrollTop = $(window).scrollTop() + 0,
zeroSizeHeight = $(document).height() - $(window).height(),
newSize = BaseWidth * (1 - (winScrollTop / zeroSizeHeight) * (2 / 3));
Node.css({
width: newSize,
"marginTop": winScrollTop + "px"
});
});
});
#added {
background: white;
height: 1500px;
overflow: hidden;
position: relative;
}
#container {
width: 600px;
height: 100px;
background-color: #567;
margin: 0 auto;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div id="added">
<div id="container"></div>
</div>
</body>
</html>

Just make the div floating left and it should work.
#container {
width: 600px;
height: 2000px;
background-color: #567;
margin: 0 auto;
position:relative;
float:left;
}

Related

Scrollbar height indicator to execute function

I'm using jQuery to get user's current height, and after he reaches that height, there will be animation function (Such as reactive websites, when user scroll down he has animation in different part of the page).
Yet, I can't really figure out why exactly the following code doesn't work.
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > 200) {
$("#project").animate({
bottom: '250px',
opacity: '0.5',
height: '1000px',
width: '100%'
});
}
});
CSS:
/* About Page */
.about{
width: 100%;
height: 1000px;
background-color: blue;
}
/* Projects Page */
.project{
background-color: red;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="jquery-3.4.1.min.js"></script>
<script src="myscripts.js"></script>
<title>My Portfolio</title>
</head>
<body>
<div id="about" class="about">
</div>
<div id="project" class="project">
</div>
</body>
</html>
How can I use scrolling height indicator to activate functions such as animation?
You need to take into account the height of each section and calculate the scrollBottom position instead, which might be more useful if you want to trigger an animation once you reach some element:
const $about = $('#about');
const $projects = $('#projects');
const $services = $('#services');
// Calculate the top offset of each section (number of sections above it * 1000px each).
// We want to expand them when we are 50px above them, so we substract that.
let projectTop = 1000 - 50;
let servicesTop = 2000 - 50;
$(window).scroll(() => {
requestAnimationFrame(() => {
// Calculate the scrollBottom by summing the viewport's height:
const scrollBottom = $(window).scrollTop() + $(window).height();
if (scrollBottom >= projectTop) {
$projects.animate({ height: '1000px' });
}
if (scrollBottom >= servicesTop) {
$services.animate({ height: '1000px' });
}
});
});
body {
margin: 0;
}
.about {
background: red;
width: 100%;
height: 1000px;
}
.projects {
background: green;
width: 100%;
}
.services {
background: blue;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="about" class="about"></div>
<div id="projects" class="projects"></div>
<div id="services" class="services"></div>

Scroll top does not equal as moving blocks up

I am trying to make some 2d game with javascript, html and css.
This is just a start but it seems like I have some weird problem.
When I move up I move my player block up and scroll top but scroll top is scrolling more then player block moved.
I am getting player block position to move up with 50px and document scrollTop position to move up same 50px by subscription.
$(document).ready(function() {
//map info
var $map = $('#map'),
viewportWidth = +$(window).width(),
viewportHeight = +$(window).height(),
mapWidth = +$map.width(),
mapHeight = +$map.width();
//player info
var $player = $('.player').eq(0);
//Adding some logic
//Half height and width of map and half of viewport to center it
var halfMW = mapWidth / 2,
halfMH = mapHeight / 2,
halfVW = viewportWidth / 2,
halfVH = viewportHeight / 2;
//Now we need to get subsrtiction of half map width and half viewport width
//and same for height
var mapPositionX = halfMW - halfVW,
mapPositionY = halfMH - halfVH;
//Now we need to put map in negative values so the viewport stands in the center
//Css example
/*
$map.css({
'top': '-' + mapPositionY + 'px',
'left': '-' + mapPositionX + 'px'
});
*/
//Scroll example
$(document).scrollLeft(mapPositionX);
$(document).scrollTop(mapPositionY);
//moving player
$(document).keydown( function(key) {
console.log(key.which);
//down - 40
//right - 39
//up - 38
//left - 37
if(key.which === 38) {
var posUP = +$player.css("top").replace("px", "");
$player.css('top', posUP-50+'px');
$(document).scrollTop($(document).scrollTop() - 50);
}
});
});
html, body {
margin: 0;
padding: 0;
}
#map {
width: 10000px;
height: 10000px;
background: #71D014;
position: relative;
overflow: scroll;
}
.blocks {
width: 100px;
height: 100px;
position: absolute;
top: 4950px;
left: 4950px;
background: orange;
}
.player {
width: 50px;
height: 50px;
position: absolute;
top: 5050px;
left: 5050px;
background: #005ED2;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tanks</title>
<link rel="stylesheet" href="css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="map">
<div class="blocks"></div>
<div class="player"></div>
</div>
<script src="js/main.js"></script>
</body>
</html>
I found out what was the problem.
Well up, down, left and right arrows on keyboard are set as defaults for moving scroll x and y and I just needed to add preventDefault(); on start.

JS (CSS) dynamic background image moving

I made up a little script that makes a photo background to scroll up/button in same time with page scrolling. The problem is that the background image is scrolling after the page was scrolling (it have a delay).
Question: How may I make to move background image with page scrolling like in this example http://shapebootstrap.net/item/1524936-unika-responsive-one-page-html5-template/live-demo ?
I made a plnkr with my code: https://plnkr.co/edit/e6OCUF4sXSA80Pi6XANj?p=preview
var bgScroll = function(lastScrollTop, elem) {
lastScrollTop = $(window).scrollTop();
$(elem).css('transition', 'all .5s');
$(elem).css('background-position', '0% ' + parseInt(-lastScrollTop / 2) + 'px');
console.log('lastScrollTop = ' + lastScrollTop);
};
$(window).load(function() {
var lastST = 0;
var homeElem = '#add-outer-container';
$(window).on("scroll", function() {
bgScroll(lastST, homeElem);
});
});
html,
body {
height: 100%;
margin: 0;
padding: 0;
background-color: gray;
}
#add-outer-container {
width: 100%;
height: 500px;
background: #fff url(http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg) no-repeat fixed 0% 0%;
overflow: hidden;
color: white;
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- version 0.6.1.0 -->
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" type="text/css" href="app.css"></link>
</head>
<body>
<div id="add-outer-container"></div>
<div style="height: 1500px; color: green;"></div>
</body>
</html>
What your are looking for is called parallax effect. There are several libraries which can help you (http://pixelcog.github.io/parallax.js/ for instance). But the simplest solution could something like this:
// Handle the window scroll event
$(window).scroll(function () {
// Store the distance scrolled
var scrolled = $(window).scrollTop() + 1;
// Set the scroll speed
var scrollSpeed = 0.3;
// Update the background position
$("#add-outer-container").css('background-position', '0' + -(scrolled * scrollSpeed) + 'px');
});
body {
min-height:3000px;
}
#add-outer-container {
background:url(http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg) no-repeat fixed;
width:100%;
height:500px;
margin:0 auto;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="add-outer-container"></div>
1- from JS remove the line: $(elem).css('transition', 'all .5s');
2- in your CSS add to #add-outer-container class:
transition: all 0.5s;
transition-timing-function:cubic-bezier(0,0,0.2,1);

Moving css scaled div using javascript

I have posted my problem at http://jsfiddle.net/ugnf4/ as it would be make it easier.
Below is my html / javascript code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="mainContainer">
<div id="pageContainer" style="background: #cdcdcd;"></div>
</div>
<style>
BODY {
margin: 0px;
padding: 0px;
}
#pageContainer {
position: relative;
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
border: 1px solid #000000;
}
#mainContainer {
width: 100%;
overflow: hidden;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script type="text/javascript">
$(document).ready(function() {
setHeight();
$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
});
</script>
</body>
</html>
Currently #mainContainer div has overflow hidden as i dont want to show scroll bars and #pageContainer div (inner div) is scaled at 1.37 using css3, as in certain cases based on screen / browser width height #pageContainer's content would be hidden because of overflow hidden.
I want to code javascript so that if somebody moves cursor in #mainContainer, based on position of mouse X and Y co-ordinates I would like to move #pageContainer so that similar position of #pageContainer would be visible (I hope it is clear).
I m having problem as I m using -webkit-transform-origin, unable to understand how to move #pageContainer around with respect to mouse co-ordinates of #mainContainer.
UPDATE:
I m looking something like what happens in issuu.com website when you open an ebook and zoom it more than the browser size (Should make it more clear)
I m looking for algo or pointer how to achieve it (how to calculate it) not necessarily a working script.
How can this be achieved.
Below is working html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="mainContainer">
<div id="pageContainer" >
<div id="pageContainerInner"style="background: #cdcdcd;">
</div>
</div>
<style>
BODY {
margin: 0px;
padding: 0px;
}
#pageContainer {
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
}
#mainContainer {
width: 100%;
overflow: hidden;
}
#pageContainerInner {
position: relative;
width: 1218px;
height: 774px;
border: 1px solid #000000;
top: 0;
left: 0;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script type="text/javascript">
var pageWidth = 1220;
var pageHeight = 776;
var scale = 1.37;
var scaledDelta = 5; //Percentage mouse position approximation
$(document).ready(function() {
setHeight();
$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
// Calculate the offset of scaled Div
var offsetX = $('#pageContainer').offset().left;
var offsetY = $('#pageContainer').offset().top;
// Calculate div origin with respect to screen
var originX = (-1 * offsetX) / scale;
var originY = (-1 * offsetY) / scale;
var wWdt = $(window).width();
var wHgt = $(window).height();
// Now convert screen positions to percentage
var perX = e.pageX * 100 / wWdt;
var perY = e.pageY * 100 / wHgt;
// Div content which should be visible
var pageX = perX * pageWidth / 100;
var pageY = perY * pageHeight / 100;
// Calculate scaled divs new X, Y offset
var shiftX = (originX - pageX) + (e.pageX / scale);
var shiftY = (originY - pageY) + (e.pageY / scale);
$('#pageContainerInner').css({'left': shiftX+'px', 'top': shiftY+'px'});
});
</script>
</body>
</html>
Hope this will help others.
I have posted a probable solution at http://jsfiddle.net/PYP8c/.
Below are the modified styles for your page.
BODY {
margin: 0px;
padding: 0px;
}
#mainContainer {
width: 100%;
overflow: hidden;
position: relative;
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
border: 1px solid #000000;
}
#pageContainer {
position:absolute;
top:0px;
}
This is the javascript code for the same.
$(document).ready(function() {
//setHeight();
//$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
var contentHeight = $("#pageContainer").height();
var minTop = 774 - contentHeight;
if(minTop>0)
minTop = 0;
var currTop = ((e.pageY-10)/774.0)*(minTop);
document.getElementById("pageContainer").style.top = currTop+'px';
});
Its just a demo on how you could get the text to move based on the mouse coordinates.
You could make a lot of changes, like adding a scrollbar that fades which gives the user a feedback about how much content is still available in both the vertical directions.
Also I have used hard coded values for height, but in your final version I would recommend you get the height of the mainContainer division dynamically.

How can I add limits to a custom scrolling element?

I have a pretty huge image being displayed in a container, the image stretches with the view port as it gets resized, but as the image is so big I have added scroller buttons to the side of the page, up and down, the only problem I have now is that when I press up or down there is no limit, the user can keep going until the image is completely out of sight, how can I stop that from happening?
Here is the code I have thus far,
HTML:
<body>
<div id="wrapper">
<div class="scroll top"></div>
<div id="content">
<div id="zoom_container">
<img id="image" src="8052x2000px" />
</div>
</div>
<div class="scroll bot"></div>
</div>
</body>
CSS:
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#wrapper {
overflow: hidden;
height: 100%;
max-height: 100%;
}
#content {
min-height: 100% !important;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#image {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
jQuery:
//side scroller bar
$('.scroll').live('click', function(){
var direction = $(this).hasClass('top');
var img_pos_top = $("#zoom_container img").position().top;
var inc = 0;
inc = $("#zoom_container img").height() / 10;
if(direction)
{
inc = $("#zoom_container img").position().top + inc;
}
else
{
inc = $("#zoom_container img").position().top - inc;
}
$("#zoom_container img").css({ position: 'relative',top: inc });
});
so as you can see I am incrementing or decrementing the top positioning of the image by 10% of it's height each click, how can I make sure the top of the image will never go further down than the top of the viewport and the bottom of the image never further up than the bottom of the viewport?
Is there a better more efficient way of achieving the same result?
Have a try this one.
<html>
<head>
<title>Canvas Sizing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var canvasContext;
resizeCanvas();
$(window).resize(function() { resizeCanvas() });
function resizeCanvas()
{
var w = window.innerWidth - 40;
var h = window.innerHeight - 40;
var canvasString = '<canvas id="mainCanvas" width="' + w + '" height="' + h + '">Canvas is not supported</canvas>';
$('#contentholder').empty();
$(canvasString).appendTo('#contentholder');
canvasContext = $('#mainCanvas').get(0).getContext('2d');
drawOnCanvas();
}
function drawOnCanvas()
{
var x = 15;
var y = 35;
canvasContext.font = "30pt serif";
canvasContext.fillStyle="#0f0";
canvasContext.fillText("Hello World!", x, y);
}
});
</script>
<style>
#mainCanvas
{
background-color: #000;
border: solid 3px #0F0;
}
body
{
background: #000;
}
#contentholder
{
width: 99%;
height: 99%;
margin: auto;
}
</style
</head>
<body>
<div id="contentholder"></div>
</body>

Categories