Animate menu on scroll event - html

I am using the following code to create a hide/show nav
based on http://jsfiddle.net/mariusc23/s6mLJ/31/
my code
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('nav').outerHeight();
$(window).scroll(function(event) { didScroll = true; });
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
if (Math.abs(lastScrollTop - st) <= delta)
return;
if (st > lastScrollTop && st > navbarHeight ) {
// Scroll Down
$('nav').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
if (st + $(window).height() < $(document).height()) {
$('nav').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}
However I want it to animate up when the user scrolls up OR down and then animates back when they are done scolling

It could be much simpler that that.
For example:
var didScroll;
$(window).scroll(function(event) { didScroll = true; });
setInterval(function() {
if (didScroll) {
$('header').removeClass('nav-down').addClass('nav-up');
didScroll = false;
}else{
$('header').removeClass('nav-up').addClass('nav-down');
}
}, 400);
body {
padding-top: 40px;
}
header {
background: #f5b335;
height: 40px;
position: fixed;
top: 0;
transition: top 0.2s ease-in-out;
width: 100%;
}
.nav-up {
top: -40px;
}
main {
background:url(
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAPklEQVQYV2O8dOnSfwYg0NPTYwTRuAAj0QqxmYBNM1briFaIzRbi3UiRZ75uNgUHGbfvabgfsHqGaIXYPAMAD8wgC/DOrZ4AAAAASUVORK5CYII=
) repeat;
height: 2000px;
}
footer { background: #ddd;}
* { color: white}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="nav-down">
This is your menu.
</header>
<main>
This is your body.
</main>
<footer>
This is your footer.
</footer>

Related

Circular window

I have this fiddle.
https://jsfiddle.net/oeuc8L9y/2/
If you click the background the coordinates where you clicked get centered.
Is it possible to make the pointer events only work inside the hole?
Since I'm using an image for the ring the whole thing blocks the pointer-events but if I set it to pointer-events: none; I can click trough the ring too.
This is good.
This is bad.
I assume a way would be to get the pixel coordinate and calculate if it's inside the hole but I feel like that would only work for a specific screen size and it'd break if resized.
tooltip_X = $("#x-coords");
tooltip_Y = $("#y-coords");
$("#background").on("mouseover", (e) => {
showTooltip(e);
});
$("#background").on("mousemove", (e) => {
updateCoords(e);
moveTooltip(e);
});
$("#background").on("mouseout", (e) => {
hideTooltip(e);
});
$("#background").on("click", (e) => {
move(e);
updateCoords(e);
});
function showTooltip(e) {
$("#tooltip").css("display", "block");
}
function hideTooltip(e) {
$("#tooltip").css("display", "none");
}
function moveTooltip(e) {
var left = 0;
var top = 0;
if (e.pageX + $("#tooltip").width() + 10 < document.body.clientWidth) {
left = e.pageX + 10;
} else {
left = document.body.clientWidth + 5 - $("#tooltip").width();
}
if (e.pageY + $("#tooltip").height() + 10 < document.body.clientHeight) {
top = e.pageY + 10;
} else {
top = document.body.clientHeight + 5 - $("#tooltip").height();
}
$("#tooltip").offset({ top: top, left: left });
}
function updateCoords(e) {
var mouse_x = e.clientX - $("#background").offset().left;
var mouse_y = e.clientY - $("#background").offset().top;
$("#x-coords").text(Number.parseInt(mouse_x));
$("#y-coords").text(Number.parseInt(mouse_y));
}
function move(e) {
var mouse_x = e.clientX - $("#background").offset().left;
var mouse_y = e.clientY - $("#background").offset().top;
var new_x = 0;
var new_y = 0;
if (mouse_x < 250) {
mouse_x = 250;
}
if (mouse_y < 250) {
mouse_y = 250;
}
if (mouse_x > 1670) {
mouse_x = 1670;
}
if (mouse_y > 950) {
mouse_y = 950;
}
new_x = -(mouse_x - 250);
new_y = -(mouse_y - 250);
$("#background").css("margin-top", new_y);
$("#background").css("margin-left", new_x);
}
#container {
position: relative;
width: 500px;
height: 500px;
overflow: hidden;
z-index: 100;
}
#ring {
position: absolute;
border-radius: 100%;
max-height: 500px;
max-width: 500px;
z-index: 90;
pointer-events: none;
}
#lens {
position: absolute;
border: 1px solid red;
/*
something to make it round
*/
z-index: 80;
pointer-events: none;
}
#background {
position: absolute;
width: 1920px;
height: 1200px;
background-image: url("https://wallpaperaccess.com/full/197542.jpg");
z-index: 80;
outline: 5px dotted purple;
outline-offset: -5px;
}
#tooltip {
position: absolute;
white-space: nowrap;
background: #ffffcc;
border: 1px solid black;
padding: 5px;
color: black;
z-index: 999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head> </head>
<body>
<div id="container">
<img id="ring" src="https://pngimg.com/uploads/circle/circle_PNG26.png" alt="Lens Ring" />
<div id="lens"></div>
<div id="background"></div>
<span id="tooltip"> Div Coords (<span id="x-coords"></span>,<span id="y-coords"></span>) </span>
</div>
</body>
</html>

Sticky footer after complete scroll

I am trying to create a "see-also" button that is located on the bottom of the page.
When the user reaches the bottom and decides to scroll back up, I want it to stick to the bottom of the viewport.
I have been trying with position:sticky but then it is already sticked to the bottom of the viewport when the page just loaded. I only want this after a complete scroll down.
Any clues?
Thanks in advance.
This is an example with javascript (see result sticky button on scroll top
const DIRECTION_BOTTOM = 1;
const DIRECTION_TOP = 0;
let previousScroll = 0;
let direction = scrollY === 0 ? DIRECTION_BOTTOM : DIRECTION_TOP;
window.addEventListener('scroll', function(){
const scrollY = window.scrollY;
if(direction === DIRECTION_TOP && previousScroll < scrollY){
direction = DIRECTION_BOTTOM;
// remove sticky
document.getElementById("sticky").classList.remove("show");
}
else if(direction === DIRECTION_BOTTOM && previousScroll > scrollY ){
direction = DIRECTION_TOP;
// Add sticky
document.getElementById("sticky").classList.add("show");
}
previousScroll = scrollY;
})
You can create this functionality with JQuery by creating a function which calculates when an element is in the viewport. If the button enters the viewport, add a class which makes the element position: sticky. There are different ways to approach this problem but one solution is something like this:
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on("scroll", function() {
if($('#button').isInViewport()) {
$('#button').addClass('sticky');
}
});
body {
text-align: center;
}
.button {
padding: 6px 12px;
}
.div {
width: 100%;
height: 250px;
color: #fff;
}
.div1 {
background: blue;
}
.div2 {
background: red;
}
.div3 {
background: purple;
}
.sticky {
position: sticky;
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
height: 100%;
bottom: 5px;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div class="div div1">Filler div 1</div>
<div class="div div2">Filler div 2</div>
<div class="div div3">Filler div 3</div>
<button type="button" class="button" id="button">See Also</button>
Scrambled everything together and this is working now:
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
document.getElementById("see-also").classList.add("sticky");
}
};
Thanks you everyone

Bootstrap collapsible not pushing down parallax

I got a website that was working earlier, and suddenly my bottom collapsible doesn't push the parallax down, it does push my <hr> down and also the footer, but not the parallax window, I'd be happy if someone could help me with this.
/*#media screen and (max-width: 667px) {
body {
overflow-x: hidden !important;
}
.container {
max-width: 100% !important;
overflow-x: hidden !important;
}
}*/
body {
text-align: center;
background-color: #222;
}
hr {
border-color: #191919;
}
.inf {
color: white;
}
#logo-pc {
background-color: rgb(255,255,255); /* Fallback color */
background-color: rgba(255,255,255, 0.4); /* Black w/opacity/see-through */
font-weight: bold;
border: 3px solid #f1f1f1;
position: absolute;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 2;
padding: 20px;
text-align: center;
}
#logo-tablet {
padding-top: 130px;
width: 800px;
background-color: rgb(255,255,255); /* Fallback color */
background-color: rgba(255,255,255, 0.4); /* Black w/opacity/see-through */
font-weight: bold;
border: 3px solid #f1f1f1;
position: absolute;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 2;
padding: 20px;
text-align: center;
}
#logo-smaller {
padding-top: 130px;
width: 600px;
background-color: rgb(255,255,255); /* Fallback color */
background-color: rgba(255,255,255, 0.4); /* Black w/opacity/see-through */
font-weight: bold;
border: 3px solid #f1f1f1;
position: absolute;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 2;
padding: 20px;
text-align: center;
}
#logo-phone {
padding-top: 190px;
width: 200px;
background-color: rgb(255,255,255); /* Fallback color */
background-color: rgba(255,255,255, 0.4); /* Black w/opacity/see-through */
font-weight: bold;
border: 3px solid #f1f1f1;
position: absolute;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 2;
padding: 20px;
text-align: center;
}
.panel {
background-image: none;
background-color: #393939;
color: white;
}
button {
width: 200px;
}
.included1 {
font-size: 18pt;
margin-top: 15px;
margin-bottom: 0;
}
.included {
font-size: 15pt;
color: rgb(255,255,255); /* Fallback color */
color: rgba(255,255,255, 0.5);
margin: 0px;
}
.included2 {
font-size: 15pt;
color: rgb(255,255,255); /* Fallback color */
color: rgba(255,255,255, 0.5);
margin: 5px;
}
.logo-animation {
animation-duration: 3s;
animation-delay: 0.5s;
}
.maten {
font-size: 12pt;
}
.ingredienser {
font-size: 10pt;
color: rgb(255,255,255); /* Fallback color */
color: rgba(255,255,255, 0.5);
}
.overlay {
background:transparent;
position:relative;
width:350px;
height:440px; /* your iframe height */
top:440px; /* your iframe height */
margin-top:-440px; /* your iframe height */
}
/* Footer CSS */
footer {
background: #333;
color: #eee;
font-size: 12px;
padding: 20px;
}
#keyframes heartbeat{
0%
{
transform: scale( .75 );
}
20%
{
transform: scale( 1 );
}
40%
{
transform: scale( .75 );
}
60%
{
transform: scale( 1 );
}
80%
{
transform: scale( .75 );
}
100%
{
transform: scale( .75 );
}
}
.heart{
animation: heartbeat 1s infinite;
}
/* END Footer CSS; */
<!DOCTYPE html>
<html>
<head>
<!-- Bootstrap CDN v3.3.7 -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/parallax.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- //.Bootstrap -->
</head>
<body>
<div class="col-xs-12 col-sm-6 fadeIn wow">
<div class="accordion" id="myAccordion4">
<div class="panel">
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#collapsible-13" data-parent="#myAccordion4" style="margin: 10px;">Barnmeny</button>
<div id="collapsible-13" class="collapse">
<h1 class="included">(Korv Meny)</h1>
<hr>
<p class="maten">Smal<br></p>
<h5 class="ingredienser">(Bröd 15:-) (Mos/Pommes 35:-)</h5>
<hr>
<p class="maten">Tjock<br></p>
<h5 class="ingredienser">(Bröd 25:-) (Mos/Pommes 45:-)</h5>
<hr>
<p class="maten">Pommes<br></p>
<h5 class="ingredienser">(Mellan 25:-) (Stor 35:-)</h5>
<hr>
<p class="maten">Fiskpinnar (4st 35:-) (8st 50:-)<br></p>
<h5 class="ingredienser">med potatismos & lingon</h5>
<hr>
<p class="maten">Chicky Bits (5st 40:-) (10st 60:-)<br></p>
<h5 class="ingredienser">med potatismos & lingon</h5>
<hr>
<p class="maten">Köttbullar (8st 45:-) (20st 60:-)<br></p>
<h5 class="ingredienser">med potatismos & lingon</h5>
</div>
</div>
<div class="panel">
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#collapsible-14" data-parent="#myAccordion4" style="margin: 10px;">Salladsmeny 75:-</button>
<div id="collapsible-14" class="collapse">
<h1 class="included1">I alla salladsmenyer ingår</h1>
<h1 class="included">(sallad, tomat, gurka, bröd och dressing)
<hr>
</h1>
<p class="maten">Gyros<br></p>
<h5 class="ingredienser">gyros, lök, sås</h5>
<hr>
<p class="maten">Kycklingsallad<br></p>
<h5 class="ingredienser">kyckling, ananas, salladsost, sås</h5>
<hr>
<p class="maten">Kebabsallad<br></p>
<h5 class="ingredienser">kebabkött, lök, sås</h5>
<hr>
<p class="maten">Grekisk sallad<br></p>
<h5 class="ingredienser">salladsost, oliver, paprika, lök, sås</h5>
<hr>
<p class="maten">Tonfisksallad<br></p>
<h5 class="ingredienser">tonfisk, lök, oliver, sås</h5>
<hr>
<p class="maten">Amerikansk sallad<br></p>
<h5 class="ingredienser">ost, skinka, ananas, sås</h5>
<hr>
<p class="maten">Räksallad 80:-<br></p>
<h5 class="ingredienser">räkor, ost, paprika, citron</h5>
<hr>
</div>
</div>
<div class="panel">
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#collapsible-15" data-parent="#myAccordion4" style="margin: 10px;">Pasta 75:-</button>
<div id="collapsible-15" class="collapse">
<p class="maten">Kyckling Pasta<br></p>
<h5 class="ingredienser">med curry, isbergssallad, tomat, gurka</h5>
<hr>
<p class="maten">Tonfisk Pasta<br></p>
<h5 class="ingredienser">isbergssallad, tomat, lök, dressing</h5>
<hr>
<p class="maten">Gyros Pasta<br></p>
<h5 class="ingredienser">isbergssallad, tomat, gurka, lök, dressing</h5>
<hr>
<p class="maten">Pasta Bolognese<br></p>
<h5 class="ingredienser">köttfärs, lök, sallad, tomat, gurka</h5>
</div>
</div>
</div>
</div><!-- //.col-xs-12 col-sm-6 -->
</div><!-- //.row -->
</div><!-- //.container -->
<hr>
<div style="width: 100%; height: 80vh;" class="parallax-window" data-parallax="scroll" data-image-src="images/visning5.jpg"></div>
<footer>
<div class="container">
<div class="row">
<div class="col-sm-2">
<h6>©2018 Bence Papp. All rights reserved.</h6>
</div><!-- //.col-sm-2 -->
<div class="col-sm-3">
<h5>Kontakta oss</h5>
<p>Tel. nrtel.</p>
<!-- <p>Mailaddress: exempel#domän.se</p> -->
<a target="_blank" href="https://www.google.se/maps/place/Kristianstadsv%C3%A4gen+703,+295+38+Brom%C3%B6lla/#56.0654977,14.4700173,18z/data=!3m1!4b1!4m5!3m4!1s0x46541fff4df0e3c7:0xdc6c817862e77450!8m2!3d56.0654977!4d14.4711116"><p style="color: white;"><b>Adress</b>Address<br>Address</p></a>
</div><!-- //.col-sm-3 -->
<div class="col-sm-2">
<h5>Hoppa till</h5>
<ul class="unstyled">
<li>Start</li>
</ul>
</div><!-- //.col-sm-2 -->
<div class="col-sm-2">
<!-- <h5>Sociala medier</h5>
<ul>
<li>Facebook</li>
</ul> -->
</div><!-- //.col-sm-2 -->
<div class="col-md-3">
<h6>Coded with <span class="glyphicon glyphicon-heart heart"></span> by: <span>Bence</span></h6>
</div><!-- //.col-sm-3 -->
</div><!-- //.row -->
</div><!-- //.container -->
</footer>
</body>
</html>
It does push the footer down, and the <hr> like I said, but not the parallax window...
[EDIT(adding js code)]
/*!
* parallax.js v1.5.0 (http://pixelcog.github.io/parallax.js/)
* #copyright 2016 PixelCog, Inc.
* #license MIT (https://github.com/pixelcog/parallax.js/blob/master/LICENSE)
*/
;(function ( $, window, document, undefined ) {
// Polyfill for requestAnimationFrame
// via: https://gist.github.com/paulirish/1579671
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
// Parallax Constructor
function Parallax(element, options) {
var self = this;
if (typeof options == 'object') {
delete options.refresh;
delete options.render;
$.extend(this, options);
}
this.$element = $(element);
if (!this.imageSrc && this.$element.is('img')) {
this.imageSrc = this.$element.attr('src');
}
var positions = (this.position + '').toLowerCase().match(/\S+/g) || [];
if (positions.length < 1) {
positions.push('center');
}
if (positions.length == 1) {
positions.push(positions[0]);
}
if (positions[0] == 'top' || positions[0] == 'bottom' || positions[1] == 'left' || positions[1] == 'right') {
positions = [positions[1], positions[0]];
}
if (this.positionX !== undefined) positions[0] = this.positionX.toLowerCase();
if (this.positionY !== undefined) positions[1] = this.positionY.toLowerCase();
self.positionX = positions[0];
self.positionY = positions[1];
if (this.positionX != 'left' && this.positionX != 'right') {
if (isNaN(parseInt(this.positionX))) {
this.positionX = 'center';
} else {
this.positionX = parseInt(this.positionX);
}
}
if (this.positionY != 'top' && this.positionY != 'bottom') {
if (isNaN(parseInt(this.positionY))) {
this.positionY = 'center';
} else {
this.positionY = parseInt(this.positionY);
}
}
this.position =
this.positionX + (isNaN(this.positionX)? '' : 'px') + ' ' +
this.positionY + (isNaN(this.positionY)? '' : 'px');
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
if (this.imageSrc && this.iosFix && !this.$element.is('img')) {
this.$element.css({
backgroundImage: 'url(' + this.imageSrc + ')',
backgroundSize: 'cover',
backgroundPosition: this.position
});
}
return this;
}
if (navigator.userAgent.match(/(Android)/)) {
if (this.imageSrc && this.androidFix && !this.$element.is('img')) {
this.$element.css({
backgroundImage: 'url(' + this.imageSrc + ')',
backgroundSize: 'cover',
backgroundPosition: this.position
});
}
return this;
}
this.$mirror = $('<div />').prependTo(this.mirrorContainer);
var slider = this.$element.find('>.parallax-slider');
var sliderExisted = false;
if (slider.length == 0)
this.$slider = $('<img />').prependTo(this.$mirror);
else {
this.$slider = slider.prependTo(this.$mirror)
sliderExisted = true;
}
this.$mirror.addClass('parallax-mirror').css({
visibility: 'hidden',
zIndex: this.zIndex,
position: 'fixed',
top: 0,
left: 0,
overflow: 'hidden'
});
this.$slider.addClass('parallax-slider').one('load', function() {
if (!self.naturalHeight || !self.naturalWidth) {
self.naturalHeight = this.naturalHeight || this.height || 1;
self.naturalWidth = this.naturalWidth || this.width || 1;
}
self.aspectRatio = self.naturalWidth / self.naturalHeight;
Parallax.isSetup || Parallax.setup();
Parallax.sliders.push(self);
Parallax.isFresh = false;
Parallax.requestRender();
});
if (!sliderExisted)
this.$slider[0].src = this.imageSrc;
if (this.naturalHeight && this.naturalWidth || this.$slider[0].complete || slider.length > 0) {
this.$slider.trigger('load');
}
}
// Parallax Instance Methods
$.extend(Parallax.prototype, {
speed: 0.2,
bleed: 0,
zIndex: -100,
iosFix: true,
androidFix: true,
position: 'center',
overScrollFix: false,
mirrorContainer: 'body',
refresh: function() {
this.boxWidth = this.$element.outerWidth();
this.boxHeight = this.$element.outerHeight() + this.bleed * 2;
this.boxOffsetTop = this.$element.offset().top - this.bleed;
this.boxOffsetLeft = this.$element.offset().left;
this.boxOffsetBottom = this.boxOffsetTop + this.boxHeight;
var winHeight = Parallax.winHeight;
var docHeight = Parallax.docHeight;
var maxOffset = Math.min(this.boxOffsetTop, docHeight - winHeight);
var minOffset = Math.max(this.boxOffsetTop + this.boxHeight - winHeight, 0);
var imageHeightMin = this.boxHeight + (maxOffset - minOffset) * (1 - this.speed) | 0;
var imageOffsetMin = (this.boxOffsetTop - maxOffset) * (1 - this.speed) | 0;
var margin;
if (imageHeightMin * this.aspectRatio >= this.boxWidth) {
this.imageWidth = imageHeightMin * this.aspectRatio | 0;
this.imageHeight = imageHeightMin;
this.offsetBaseTop = imageOffsetMin;
margin = this.imageWidth - this.boxWidth;
if (this.positionX == 'left') {
this.offsetLeft = 0;
} else if (this.positionX == 'right') {
this.offsetLeft = - margin;
} else if (!isNaN(this.positionX)) {
this.offsetLeft = Math.max(this.positionX, - margin);
} else {
this.offsetLeft = - margin / 2 | 0;
}
} else {
this.imageWidth = this.boxWidth;
this.imageHeight = this.boxWidth / this.aspectRatio | 0;
this.offsetLeft = 0;
margin = this.imageHeight - imageHeightMin;
if (this.positionY == 'top') {
this.offsetBaseTop = imageOffsetMin;
} else if (this.positionY == 'bottom') {
this.offsetBaseTop = imageOffsetMin - margin;
} else if (!isNaN(this.positionY)) {
this.offsetBaseTop = imageOffsetMin + Math.max(this.positionY, - margin);
} else {
this.offsetBaseTop = imageOffsetMin - margin / 2 | 0;
}
}
},
render: function() {
var scrollTop = Parallax.scrollTop;
var scrollLeft = Parallax.scrollLeft;
var overScroll = this.overScrollFix ? Parallax.overScroll : 0;
var scrollBottom = scrollTop + Parallax.winHeight;
if (this.boxOffsetBottom > scrollTop && this.boxOffsetTop <= scrollBottom) {
this.visibility = 'visible';
this.mirrorTop = this.boxOffsetTop - scrollTop;
this.mirrorLeft = this.boxOffsetLeft - scrollLeft;
this.offsetTop = this.offsetBaseTop - this.mirrorTop * (1 - this.speed);
} else {
this.visibility = 'hidden';
}
this.$mirror.css({
transform: 'translate3d('+this.mirrorLeft+'px, '+(this.mirrorTop - overScroll)+'px, 0px)',
visibility: this.visibility,
height: this.boxHeight,
width: this.boxWidth
});
this.$slider.css({
transform: 'translate3d('+this.offsetLeft+'px, '+this.offsetTop+'px, 0px)',
position: 'absolute',
height: this.imageHeight,
width: this.imageWidth,
maxWidth: 'none'
});
}
});
// Parallax Static Methods
$.extend(Parallax, {
scrollTop: 0,
scrollLeft: 0,
winHeight: 0,
winWidth: 0,
docHeight: 1 << 30,
docWidth: 1 << 30,
sliders: [],
isReady: false,
isFresh: false,
isBusy: false,
setup: function() {
if (this.isReady) return;
var self = this;
var $doc = $(document), $win = $(window);
var loadDimensions = function() {
Parallax.winHeight = $win.height();
Parallax.winWidth = $win.width();
Parallax.docHeight = $doc.height();
Parallax.docWidth = $doc.width();
};
var loadScrollPosition = function() {
var winScrollTop = $win.scrollTop();
var scrollTopMax = Parallax.docHeight - Parallax.winHeight;
var scrollLeftMax = Parallax.docWidth - Parallax.winWidth;
Parallax.scrollTop = Math.max(0, Math.min(scrollTopMax, winScrollTop));
Parallax.scrollLeft = Math.max(0, Math.min(scrollLeftMax, $win.scrollLeft()));
Parallax.overScroll = Math.max(winScrollTop - scrollTopMax, Math.min(winScrollTop, 0));
};
$win.on('resize.px.parallax load.px.parallax', function() {
loadDimensions();
self.refresh();
Parallax.isFresh = false;
Parallax.requestRender();
})
.on('scroll.px.parallax load.px.parallax', function() {
loadScrollPosition();
Parallax.requestRender();
});
loadDimensions();
loadScrollPosition();
this.isReady = true;
var lastPosition = -1;
function frameLoop() {
if (lastPosition == window.pageYOffset) { // Avoid overcalculations
window.requestAnimationFrame(frameLoop);
return false;
} else lastPosition = window.pageYOffset;
self.render();
window.requestAnimationFrame(frameLoop);
}
frameLoop();
},
configure: function(options) {
if (typeof options == 'object') {
delete options.refresh;
delete options.render;
$.extend(this.prototype, options);
}
},
refresh: function() {
$.each(this.sliders, function(){ this.refresh(); });
this.isFresh = true;
},
render: function() {
this.isFresh || this.refresh();
$.each(this.sliders, function(){ this.render(); });
},
requestRender: function() {
var self = this;
self.render();
self.isBusy = false;
},
destroy: function(el){
var i,
parallaxElement = $(el).data('px.parallax');
parallaxElement.$mirror.remove();
for(i=0; i < this.sliders.length; i+=1){
if(this.sliders[i] == parallaxElement){
this.sliders.splice(i, 1);
}
}
$(el).data('px.parallax', false);
if(this.sliders.length === 0){
$(window).off('scroll.px.parallax resize.px.parallax load.px.parallax');
this.isReady = false;
Parallax.isSetup = false;
}
}
});
// Parallax Plugin Definition
function Plugin(option) {
return this.each(function () {
var $this = $(this);
var options = typeof option == 'object' && option;
if (this == window || this == document || $this.is('body')) {
Parallax.configure(options);
}
else if (!$this.data('px.parallax')) {
options = $.extend({}, $this.data(), options);
$this.data('px.parallax', new Parallax(this, options));
}
else if (typeof option == 'object')
{
$.extend($this.data('px.parallax'), options);
}
if (typeof option == 'string') {
if(option == 'destroy'){
Parallax.destroy(this);
}else{
Parallax[option]();
}
}
});
}
var old = $.fn.parallax;
$.fn.parallax = Plugin;
$.fn.parallax.Constructor = Parallax;
// Parallax No Conflict
$.fn.parallax.noConflict = function () {
$.fn.parallax = old;
return this;
};
// Parallax Data-API
$( function () {
$('[data-parallax="scroll"]').parallax();
});
}(jQuery, window, document));
[EDIT]
I'm using this parallax.js
Thanks in advance!
First of all, you should validate your HTML, </head> and <body> tags are missing and there are two </div> moreover. (line 96 or something like that)
For your purpose, I think is parallax.js is overkill. You can just use background: url('./image.jgp') 50% 50%; background-size: cover; background-attachment: fixed;.
Your content has 80vh and when it overflows it (panels do that), then it will fuck up your footer and other content. Maybe you could use position: absolute;.

How to integrate a script into a function in HTML?

I want to make a html button that appears when you scroll down and when clicked it shows a random blogger post.
I have code to make it appear when you scroll down and code for a button that shows a random post. But I don't know how to make them work together.
This is my scroll button code, below is random post code. I don't know how to integrate it inside TopFunction.
Thank you very much for your help and insights!
#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#myBtn:hover {
background-color: #555;
}
</style>
<button onclick="topFunction()" id="myBtn"></button>
<script>
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// When the user clicks on the button, show random post
function topFunction() {
}
</script>
RANDOM POST
<script type="text/javascript">
function showLucky(root){ var feed = root.feed; var entries = feed.entry || []; var entry = feed.entry[0]; for (var j = 0; j < entry.link.length; ++j){if (entry.link[j].rel == 'alternate'){window.location = entry.link[j].href;}}} function fetchLuck(luck){ script = document.createElement('script'); script.src = '/feeds/posts/summary?start-index='+luck+'&max-results=1&alt=json-in-script&callback=showLucky'; script.type = 'text/javascript'; document.getElementsByTagName('head')[0].appendChild(script); } function feelingLucky(root){ var feed = root.feed; var total = parseInt(feed.openSearch$totalResults.$t,10); var luckyNumber = Math.floor(Math.random()*total);luckyNumber++; a = document.createElement('a'); a.href = '#random'; a.rel = luckyNumber; a.onclick = function(){fetchLuck(this.rel);}; a.innerHTML = 'RANDOM POST'; document.getElementById('myBtn').appendChild(a); } </script><script src="/feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky">
</script>
I have no idea if below is correct or not. In order to help you correctly we need to know WHERE the codes are coming from. And you need to explain into detail what you have tried.
Below might work: I have added a <div> for which should contain the random posts when button is clicked. Content can be styled as you wish.
Be aware of the path /feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky. This is hardcoded and the JS script change some word in it. This needs to be the same (and the one in the code) to your own folderstructure.
I have also cleared up your code a little... Always use id for scripts and class for CSS styling.
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// When the user clicks on the button, show random post
function topFunction() {
//Why is this empty?
};
function showLucky(root) {
var feed = root.feed;
var entries = feed.entry || [];
var entry = feed.entry[0];
for (var j = 0; j < entry.link.length; ++j) {
if (entry.link[j].rel == 'alternate') {
window.location = entry.link[j].href;
}
}
};
function fetchLuck(luck) {
script = document.createElement('script');
script.src = '/feeds/posts/summary?start-index=' + luck + '&max-results=1&alt=json-in-script&callback=showLucky';
script.type = 'text/javascript';
document.getElementsByTagName('randompost')[0].appendChild(script);
}
function feelingLucky(root) {
var feed = root.feed;
var total = parseInt(feed.openSearch$totalResults.$t, 10);
var luckyNumber = Math.floor(Math.random() * total);
luckyNumber++;
a = document.createElement('a');
a.href = '#random';
a.rel = luckyNumber;
a.onclick = function() {
fetchLuck(this.rel);
};
a.innerHTML = 'RANDOM POST';
document.getElementById('myBtn').appendChild(a);
};
.myBtn {
display: block;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
.myBtn:hover {
background-color: #555;
}
.myDiv {
width: 50%;
height: auto;
background: rgba(255,0,0,0.5);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="showLucky()" id="myBtn" class="myBtn">Try me</button>
<div class="myDiv" id="randompost" >
<script src="/feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky">
</script>
Something here...
</div>

CSS: Make children inside parent responsive

So I am not using any CSS framework like bootstrap to get responsiveness out of the box which is why I am having trouble making responsive layout.
Please see jsbin
I essentially what to auto-resize colorful boxes based on browser window size eg that should shrink or grow automatically based on window size. Colorful boxes inside their parent should always be in horizontal row but should be able to adjust their width and height like this example.
I tried using flex-wrap: nowrap; but it didn't do the trick :(
Please note that colorful boxes are using position:absolute with parent's position being relative. I am also adding left css property to these boxes via JavaScript to change their position for the sake of sliding animation.
function Carousel(options) {
options = options || {};
// options vars
let speed = options.speed || 1; // animation speed in seconds
let width = options.width || 200;
let height = options.height || 100;
let space = options.space || 30;
// other vars
let container = document.querySelector('.carousel-container .carousel');
let slides = container.querySelectorAll('.carousel-item');
let curSlide = null;
let prevSlide = null;
let nextSlide = null;
if (areSlidesPresent()) {
setup();
}
// functions //
function setup() {
// we assume first slide to be current one as per UI requirements
//slides[0].classList.add("current");
curSlide = slides[0];
// we assume second slide to be next as per UI requirements
nextSlide = slides[1];
// we assume last slide to be prev as per UI requirements
prevSlide = slides[slides.length - 1];
// position elements horizontally
positionSlides();
}
function areSlidesPresent() {
return slides.length > 0;
}
this.getCurrentSlide = function() {
return curSlide;
}
this.getNextSlide = function() {
return nextSlide;
}
this.getPreviousSlide = function() {
return prevSlide;
}
this.setNextSlide = function() {
if (areSlidesPresent()) {
let allSlides = [];
// build new order of slides
allSlides.push(nextSlide);
// middle ones
for (let i = 2; i < slides.length; i++) {
allSlides.push(slides[i]);
}
allSlides.push(curSlide);
// now add to DOM after cleaning previous slide order
for (let i = 0; i < allSlides.length; i++) {
container.appendChild(allSlides[i]);
}
slides = allSlides;
setup();
}
}
this.setPreviousSlide = function() {
if (areSlidesPresent()) {
let allSlides = [];
// build new order of slides
allSlides.push(prevSlide);
allSlides.push(curSlide);
// middle ones
for (let i = 1; i < slides.length - 1; i++) {
allSlides.push(slides[i]);
}
// now add to DOM after cleaning previous slide order
for (let i = 0; i < allSlides.length; i++) {
container.appendChild(allSlides[i]);
}
slides = allSlides;
setup();
}
}
function positionSlides() {
curSlide.style.marginLeft = '0px';
for (let i = 0; i < slides.length; i++) {
slides[i].querySelector('.carousel-content').style.width = (width) + 'px';
slides[i].querySelector('.carousel-content').style.height = (height) + 'px';
let elementWidth = getStyle(nextSlide, 'width');
if (i === 0) {
slides[i].style.zIndex = -10;
//slides[i].style.opacity = '1';
slides[i].querySelector('.carousel-content').style.width = (width + 50) + 'px';
slides[i].querySelector('.carousel-content').style.height = (height + 50) + 'px';
} else {
slides[i].style.zIndex = 0;
//slides[i].style.opacity = '0.7';
}
if (i > 0) {
slides[i].style.marginLeft = (space * 2) + 'px';
elementWidth = parseInt(elementWidth, 10) + space;
}
slides[i].style.transition = speed + 's';
slides[i].style.left = (elementWidth * i) + 'px';
}
}
function getStyle(el, prop) {
return window.getComputedStyle(el, null).getPropertyValue(prop)
.replace('px', '')
.replace('em', '');
}
}
// utility
function log(text) {
console.log(text);
}
var options = {
speed: 1, // animation speed
width: 250, // slide width
height: 150, // slide height
space: 25 // space in px between slides
};
var carousel = new Carousel(options);
function selectCurrent() {
log(carousel.getCurrentSlide());
}
function selectNext() {
carousel.setNextSlide();
}
function selectPrev() {
carousel.setPreviousSlide();
}
.carousel-container {
width: auto;
height: auto;
margin: 25px;
display: flex;
align-items: center;
justify-content: center;
}
.carousel {
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
.carousel .carousel-item {
position: absolute;
transition: transform .5s ease-in-out;
color: #fff;
margin-left: 10px;
-webkit-box-reflect: below 10px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(70%, transparent), to(rgba(255, 255, 255, 0.2)));
}
.carousel .carousel-item:first-child .carousel-content {
opacity: 1;
}
.carousel .carousel-item .carousel-title {
font-size: 24px;
text-align: center;
}
.carousel .carousel-item .carousel-content {
font-size: 18px;
font-weight: bold;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
}
/* temp css below */
body {
background: #2C374A;
padding-top: 150px;
}
.navigation {
display: flex;
align-items: center;
justify-content: center;
margin-top: 150px;
}
.button {
color: #444;
padding: 10px;
width: 60px;
cursor: pointer;
background: #CCC;
text-align: center;
font-weight: bold;
border-radius: 5px;
border-top: 1px solid #FFF;
box-shadow: 0 5px 0 #999;
transition: box-shadow 0.1s, top 0.1s;
margin: 10px;
}
.button:hover,
.button:hover {
color: #000;
}
.button:active,
.button:active {
top: 104px;
box-shadow: 0 1px 0 #999;
}
<div class="carousel-container">
<div class="carousel">
<div class="carousel-item">
<div class="carousel-title">Make a Call</div>
<div class="carousel-content" style="background:#0E6DE8;border:10px solid #78B1FA">Slide One</div>
</div>
<div class="carousel-item">
<div class="carousel-title">Send a Message</div>
<div class="carousel-content" style="background:#D90080;border:10px solid #E357A9">Slide Two</div>
</div>
<div class="carousel-item">
<div class="carousel-title">Send a Picture</div>
<div class="carousel-content" style="background:#FEC601;border:10px solid #FFDD64">Slide Three</div>
</div>
<div class="carousel-item">
<div class="carousel-title">Send a Video</div>
<div class="carousel-content" style="background:#3DB365;border:10px solid #90E0AB">Slide Four</div>
</div>
</div>
</div>
<div class="navigation">
<div class="button" onclick="selectNext()">Next</div>
<div class="button" onclick="selectCurrent()">Select</div>
<div class="button" onclick="selectPrev()">Prev</div>
</div>
Problem here was:
Width was hard-coded in your JS, so if width is in px it can't be responsive.
By applying position:absolute to you carousel-item, it forced the children to get out of the box.
What I did:
Got rid of the static width and other functionalities related to width from your JS
Removed position:absolute from carousel-item
Let me know if this is what you are expecting.
function Carousel(options) {
options = options || {};
// options vars
let speed = options.speed || 1; // animation speed in seconds
// let width = options.width || 100;
let height = options.height || 100;
let space = options.space || 30;
// other vars
let container = document.querySelector('.carousel-container .carousel');
let slides = container.querySelectorAll('.carousel-item');
let curSlide = null;
let prevSlide = null;
let nextSlide = null;
if (areSlidesPresent()) {
setup();
}
// functions //
function setup() {
// we assume first slide to be current one as per UI requirements
//slides[0].classList.add("current");
curSlide = slides[0];
// we assume second slide to be next as per UI requirements
nextSlide = slides[1];
// we assume last slide to be prev as per UI requirements
prevSlide = slides[slides.length - 1];
// position elements horizontally
positionSlides();
}
function areSlidesPresent() {
return slides.length > 0;
}
this.getCurrentSlide = function() {
return curSlide;
}
this.getNextSlide = function() {
return nextSlide;
}
this.getPreviousSlide = function() {
return prevSlide;
}
this.setNextSlide = function() {
if (areSlidesPresent()) {
let allSlides = [];
// build new order of slides
allSlides.push(nextSlide);
// middle ones
for (let i = 2; i < slides.length; i++) {
allSlides.push(slides[i]);
}
allSlides.push(curSlide);
// now add to DOM after cleaning previous slide order
for (let i = 0; i < allSlides.length; i++) {
container.appendChild(allSlides[i]);
}
slides = allSlides;
setup();
}
}
this.setPreviousSlide = function() {
if (areSlidesPresent()) {
let allSlides = [];
// build new order of slides
allSlides.push(prevSlide);
allSlides.push(curSlide);
// middle ones
for (let i = 1; i < slides.length - 1; i++) {
allSlides.push(slides[i]);
}
// now add to DOM after cleaning previous slide order
for (let i = 0; i < allSlides.length; i++) {
container.appendChild(allSlides[i]);
}
slides = allSlides;
setup();
}
}
function positionSlides() {
curSlide.style.marginLeft = '0px';
for (let i = 0; i < slides.length; i++) {
// slides[i].querySelector('.carousel-content').style.width = (width) + 'px';
slides[i].querySelector('.carousel-content').style.height = (height) + 'px';
let elementWidth = getStyle(nextSlide, 'width');
if (i === 0) {
slides[i].style.zIndex = -10;
//slides[i].style.opacity = '1';
// slides[i].querySelector('.carousel-content').style.width = (width + 50) + 'px';
slides[i].querySelector('.carousel-content').style.height = (height + 50) + 'px';
} else {
slides[i].style.zIndex = 0;
//slides[i].style.opacity = '0.7';
}
if (i > 0) {
slides[i].style.marginLeft = (space * 2) + 'px';
// elementWidth = parseInt(elementWidth, 10) + space;
}
slides[i].style.transition = speed + 's';
// slides[i].style.left = (elementWidth * i) + 'px';
}
}
function getStyle(el, prop) {
return window.getComputedStyle(el, null).getPropertyValue(prop)
.replace('px', '')
.replace('em', '');
}
}
// utility
function log(text) {
console.log(text);
}
var options = {
speed: 1, // animation speed
width: 250, // slide width
height: 150, // slide height
space: 25 // space in px between slides
};
var carousel = new Carousel(options);
function selectCurrent() {
log(carousel.getCurrentSlide());
}
function selectNext() {
carousel.setNextSlide();
}
function selectPrev() {
carousel.setPreviousSlide();
}
.carousel-container {
height: auto;
margin: 25px;
display: flex;
}
.carousel {
flex: 1;
height: 100%;
width: 100vh;
/* overflow:hidden; */
display: flex;
align-items: center;
justify-content: center;
}
.carousel .carousel-item {
transition: transform .5s ease-in-out;
color: #fff;
flex: 1;
margin-left: 10px;
-webkit-box-reflect: below 10px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(70%, transparent), to(rgba(255, 255, 255, 0.2)));
}
.carousel .carousel-item:first-child .carousel-content {
opacity: 1;
}
.carousel .carousel-item .carousel-title {
font-size: 24px;
text-align: center;
}
.carousel .carousel-item .carousel-content {
font-size: 18px;
font-weight: bold;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
}
/* temp css below */
body {
background: #2C374A;
}
.navigation {
display: flex;
align-items: center;
justify-content: center;
}
.button {
color: #444;
padding: 10px;
width: 60px;
cursor: pointer;
background: #CCC;
text-align: center;
font-weight: bold;
border-radius: 5px;
border-top: 1px solid #FFF;
box-shadow: 0 5px 0 #999;
transition: box-shadow 0.1s, top 0.1s;
margin: 10px;
}
.button:hover,
.button:hover {
color: #000;
}
.button:active,
.button:active {
box-shadow: 0 1px 0 #999;
}
<div class="navigation">
<div class="button" onclick="selectNext()">Next</div>
<div class="button" onclick="selectCurrent()">Select</div>
<div class="button" onclick="selectPrev()">Prev</div>
</div>
<div class="carousel-container">
<div class="carousel">
<div class="carousel-item">
<div class="carousel-title">Make a Call</div>
<div class="carousel-content" style="background:#0E6DE8;border:10px solid #78B1FA">Slide One</div>
</div>
<div class="carousel-item">
<div class="carousel-title">Send a Message</div>
<div class="carousel-content" style="background:#D90080;border:10px solid #E357A9">Slide Two</div>
</div>
<div class="carousel-item">
<div class="carousel-title">Send a Picture</div>
<div class="carousel-content" style="background:#FEC601;border:10px solid #FFDD64">Slide Three</div>
</div>
<div class="carousel-item">
<div class="carousel-title">Send a Video</div>
<div class="carousel-content" style="background:#3DB365;border:10px solid #90E0AB">Slide Four</div>
</div>
</div>
</div>