Parallax Curtain Reveal Effect with jQuery and CSS3 - javascript

It is really difficult to explain what kind of effect I mean. But let me try. :)
When you scroll down one DIV with text Block moves over a fixed background DIV with a background image. Now when the DIV on top leave the bottom area and moves to the top of the viewport you can seen the half (and later the full) new background image. But the Background Images are not moving, they are fixed. Only the Page Content with Text Blocks moves when you scroll down.
If you still see a question mark then take a look at this website, there you can see the concept in use.
So my question is how can I recreate this effect only with CSS3 and jQuery (Without YUI etc.)?
I don't really understand the logic that is needed for this to work. How do I need to animate the DIVs and where should I place them in the HTML Document.
Below you find some tests I did (But they don't work)
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=0, minimal-ui">
<title>Agency</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("div.blankItem").css("min-height", $(window).innerHeight()-44);
$("div.red").css("min-height", $(window).innerHeight()-44);
var windowHeight = $(window).innerHeight()+ 44;
var total = - windowHeight - 400;
$('div.red').css('-webkit-transform', 'translate3d(0,' + total + 'px,0)');
//$("div.pageContentBackground").css("bottom", -$(window).innerHeight()+44 + "px");
//$("div.pageContentBackground").css("bottom", -$(window).innerHeight()-44);
$(window).resize(function() {
$("div.blankItem").css("min-height", $(window).innerHeight()-44);
$("div.red").css("min-height", $(window).innerHeight()-44);
//$("div.pageContentBackground").css("bottom", -$(window).innerHeight()+44 + "px");
//$("div.pageContentBackground").css("bottom", -$(window).innerHeight()-44);
});
$(function(){
$(window).bind({scroll: Scroll, touchmove: Scroll});
});
function Scroll(){
// var op = (window.pageYOffset-$(window).innerHeight()-44-356);
// $("div.pageContentBackground").css("bottom", + op);
var scrollTop = $(window).scrollTop();
var pageYDoc = 1300;
var factor = 0.8;
var pageYViewport = pageYDoc - scrollTop;
var imageY = -1 * parseInt(pageYViewport * factor);
//var tr = -200; // You'd need to calculate this value
/**$('div.red').css("-webkit-transform", "translate3d(0, " + tr + "px, 0)");
*/
//var offset = total + $(window).scrollTop()+400;
$('div.red').css({'-webkit-transform': 'translate3d(0, '+ imageY + '%, 0)'});
// $('div.blue').stop().css('bottom', $(window).scrollTop() - $(window).innerHeight()-44-400 + "px");
console.log(offset);
}
});
</script>
<style>
* {
padding: 0;
margin: 0;
}
ul, li {
margin: 0;
padding: 0;
}
a {
-webkit-tap-highlight-color: rgba(0,0,0,0);
-moz-tap-highlight-color: rgba(0,0,0,0);
tap-highlight-color: rgba(0,0,0,0);
text-decoration: none;
}
html {
-ms-text-size-adjust: none;
-webkit-text-size-adjust: none;
}
body {
transition:all .2s linear;
-o-transition:all .2s linear;
-moz-transition:all .2s linear;
-webkit-transition:all .2s linear;
font-family: 'Open Sans', Helvetica;
color: #F0F2ED;
-webkit-font-smoothing: subpixel-antialiased !important;
}
div.pageMenu {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 44px;
background-color: #333;
z-index: 10;
opacity: 0.99;
}
a.pageMenuButton {
position: fixed;
top: 8px;
right: 44px;
text-decoration: none;
color: #fff;
font-weight: bold;
}
div.pageHeader {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background-color: #daddda;
z-index: 1;
padding-bottom: 10px;
}
div.pageContent {
position: absolute;
top: 100%;
width: 100%;
z-index: 5;
max-width: 100%;
overflow: hidden;
}
div.pageContentBackground {
position: fixed;
left: 0px;
width: 100%;
}
div.red {
background-color: red;
z-index: 2;
}
div.blue {
background-color: blue;
z-index: 3;
}
div.pageContentBody {
width: 100%;
z-index: 2;
}
div.pageContentBodyItem {
width: 100%;
height: 400px;
background-color: #fff;
display: block;
}
div.blankItem {
background: transparent;
width: 100%;
display: block;
}
</style>
</head>
<body>
<div class="pageMenu">
<div class="pageMenuLogo">
</div>
☰
</div>
<div class="pageHeader">
</div>
<div class="pageContentBackground red">
</div>
<!--<div class="pageContentBackground blue">
</div>-->
<div class="pageContent">
<div class="pageContentBody">
<div class="pageContentBodyItem">
</div>
<div class="blankItem">
</div>
<div class="pageContentBodyItem">
</div>
<div class="blankItem">
</div>
<div class="pageContentBodyItem">
</div>
<div class="blankItem">
</div>
<div class="pageContentBodyItem">
</div>
<div class="blankItem">
</div>
<div class="pageContentBodyItem">
</div>
</div>
</div>
<div class="pageContentFooter">
</div>
</div>
</body>

This is my try: http://codepen.io/rafaelcastrocouto/pen/bCxAd
Although there are lots of differences in the sites, they are still kinda alike.
Notice that my parallax only woks on big screens.
The JS is pretty small:
var lastScrollTop = 0;
var backgroundImages = $('.backgroundImage');
$(window).scroll(function(e){
var st = $(this).scrollTop();
var ah = $(this).height();
backgroundImages.each(function(i){
var img = $(this);
var pos = img.position().top;
var hei = img.height();
if ((st + ah) > pos && st < (pos + hei)){
var p = ((pos - st)/ah) + 0.25;
if(i == 1) console.log(p);
img.css('background-position', '50%'+(p*100)+'%');
}
});
lastScrollTop = st;
});
$(window).scroll();

Related

How can I make text change when a page is scrolled to a certain point using jQuery?

I am trying to make the content of a div change when the page is scrolled to a certain point using jQuery. Currently, I am trying to accomplish this by adding a class when the page is scrolled past 800 and removing it and adding a different class when the page is above 800. Here is my current code on jsfiddle: https://jsfiddle.net/shgfrdm8/
Here is the jQuery code:
$(window).scroll(function() {
let windowTop = $(window).scrollTop();
if (windowTop < 800) {
$('image-content').addClass('scrolledDown');
$('image-content').removeClass('scrolledUp');
} else {
$('image-content').addClass('scrolledUp');
$('image-content').removeClass('scrolledDown')
}
})
The CSS ids/classes:
.main {
width: 100%;
height: 700px;
overflow: hidden;
position: relative;
}
.main-image {
width: 100%;
position: fixed;
left: 50%;
transform: translate(-50%) scale(500%);
}
.filler {
height: 400vh;
}
.main-text {
left: -14px;
width: 99.3vw;
height: 4000px;
text-align: center;
background-color: red;
position: relative;
}
#image-content::before {
white-space: pre;
position: absolute;
bottom: 20px;
left: 20px;
font-family: Impact;
font-size: 55px;
font-weight: 550;
color: white;
z-index: 4;
opacity: 1;
position: fixed;
}
#image-content.scrolledDown::before {
opacity: 1;
content: 'ABC';
}
#image-content.scrolledUp::before {
opacity: 1;
content: "DEF";
}
The HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="zoom.css">
</head>
<body>
<div class="image-container">
<div class="zoom main">
<img src="images/sourcecode.jpg" class="main-image">
</div>
<div id="content-anchor"></div>
<div id="image-content"></div>
</div>
<div class="filler">
</div>
<div class="main-text">
</div>
I am wondering how I can make this work because I far as I can tell the classes either not being added or the classes are not working.
Suggesting the following changes:
$(window).scroll(function() {
var windowTop = $(window).scrollTop();
if (windowTop < 800) {
$('.image-content').addClass('scrolledDown');
$('.image-content').removeClass('scrolledUp');
} else {
$('.image-content').addClass('scrolledUp');
$('.image-content').removeClass('scrolledDown')
}
});
This ensures you have the correct Class selector.

CSS3 Div Animation Relative Spacing

Recently I have asked a similar question about transition animation in divs. (See this post)
The Code Snippet below shows my solution.
However, the animation only works if the width is given in pixels, not as a percentage.
Does anybody know a way around this?
EDIT (More info to clarify my problem):
In this section of a website, I have a heading that should always stay the same and 3 pages of content which can be "swiped" on user input.
Thus, the span of the left margin of the page would range from -100% to +100%.
I want a swiping animation so that the user can switch from page 2 (i.e. displaying an image) to page 3 (i.e. the text correlating to the image).
Because of different browser window sizes, I need the width to be in percentages. Sadly...
$(document).ready(function() {
$(".next").click(function() {
var current = $(".container").css("left");
if (current == "-200px") {
current = "-400px";
} else if (current == "0px") {
current = "-200px";
}
$(".container").css("left", current);
});
$(".prev").click(function() {
var current = $(".container").css("left");
if (current == "-200px") {
current = "0px";
} else if (current == "-400px") {
current = "-200px";
}
$(".container").css("left", current);
});
});
.row {
border: 1px solid black;
height: 200px;
margin: 0;
width: 200px;
padding: 0;
display: block;
position: relative;
overflow: hidden;
}
.container {
height: 200px;
margin: 0;
width: 600px;
padding: 0;
display: block;
position: absolute;
left: -200px;
top: 0;
-webkit-transition: left 0.5s ease-in-out;
-moz-transition: left 0.5s ease-in-out;
transition: left 0.5s ease-in-out;
}
.ins {
width: 200px;
float: left;
height: 200px;
margin: 0;
padding: 0;
background-color: red;
}
.div1 {
background-color: red;
}
.div2 {
background-color: green;
}
.div3 {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<!-- Thanks to kittyCat at stackoverflow.com for helping me with this website.-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>TITLE</title>
<meta name="Title" content="Main">
</head>
<body>
<div class="row">
<div class="container">
<div class="ins div1">div-1</div>
<div class="ins div2">div-2</div>
<div class="ins div3">div-3</div>
</div>
</div>
<button class="prev">prev</button>
<button class="next">next</button>
</body>
</html>
I have changed the left positioning for a transform on the individual elements:
Now, also, the class row is set to occupy full browser width. The container class is se to 300% (because it will make room for 3 elements). And the children are set to 33% of this, that at the end is 100% of the row.
var pos = 2; /* values 1 - 2 or 3 */
$(document).ready(function() {
$(".next").click(function() {
if (pos == 1) {
$(".container").removeClass("pos1");
$(".container").addClass("pos2");
pos++;
} else if (pos == 2) {
$(".container").removeClass("pos2");
$(".container").addClass("pos3");
pos++;
}
});
$(".prev").click(function() {
if (pos == 3) {
$(".container").removeClass("pos3");
$(".container").addClass("pos2");
pos--;
} else if (pos == 2) {
$(".container").removeClass("pos2");
$(".container").addClass("pos1");
pos--;
}
});
});
.row {
border: 1px solid black;
height: 200px;
margin: 0;
width: 100%;
padding: 0;
display: block;
position: relative;
overflow: hidden;
}
.container {
height: 200px;
width: 300%;
margin: 0;
padding: 0;
display: block;
position: absolute;
top: 0;
}
.ins {
width: 33.33%;
height: 200px;
margin: 0;
padding: 0;
float: left;
transition: transform 0.5s ease-in-out;
}
.div1 {
background-color: red;
}
.div2 {
background-color: green;
}
.div3 {
background-color: blue;
}
.pos2 .ins {
transform: translateX(-100%);
}
.pos3 .ins {
transform: translateX(-200%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<!-- Thanks to kittyCat at stackoverflow.com for helping me with this website.-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>TITLE</title>
<meta name="Title" content="Main">
</head>
<body>
<div class="row">
<div class="container pos2">
<div class="ins div1">div-1</div>
<div class="ins div2">div-2</div>
<div class="ins div3">div-3</div>
</div>
</div>
<button class="prev">prev</button>
<button class="next">next</button>
</body>
</html>
Narusan,
If I'm understanding your goal correctly, part of the problem is that no matter what, jQuery wants to return px units to you. You can set a percentage value, but it seems it will not then return those percentages to you.
I changed your code some to demonstrate this:
$(document).ready(function() {
$(".next").click(function() {
var current = $(".container").css("left");
console.log(current);
if (current == "-200px" || current == "-100%") {
current = "-200%";
} else if (current == "0%") {
current = "-100%";
}
$(".container").css("left", current);
});
$(".prev").click(function() {
var current = $(".container").css("left");
console.log(current);
if (current == "-200px" || current == "-100%") {
current = "0%";
} else if (current == "-200%") {
current = "-100%";
}
$(".container").css("left", current);
});
});
You'll see that the values printed to the console are always in px, but if you inspect the DOM you'll see that the % value is being set on the element.
Approaching the problem very differently, like vals did, seems like a good approach.

Script works in jsfiddle but not HTML document

I have a script in jsfiddle that works: https://jsfiddle.net/oxw4e5yh/
However in HTML doc it is not working:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function calcSpeed(speed) {
// Time = Distance/Speed
var spanSelector = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelector.length; i++) {
var spanLength = spanSelector[i].offsetWidth,
timeTaken = spanLength / speed;
spanSelector[i].style.animationDuration = timeTaken + "s";
}
}
calcSpeed(75);
</script>
<style>
/* Make it a marquee */
.marquee {
width: 100%;
left: 0px;
height: 10%;
position: fixed;
margin: 0 auto;
white-space: nowrap;
overflow: hidden;
background-color: #000000;
bottom: 0px;
color: white;
font: 50px'Verdana';
}
.marquee span {
display: inline-block;
padding-left: 100%;
text-indent: 0;
animation: marquee linear infinite;
animation-delay: 5s;
background-color: #000000;
color: white;
bottom: 0px;
}
/* Make it move */
#keyframes marquee {
0% {
transform: translate(10%, 0);
}
100% {
transform: translate(-100%, 0);
}
}
/* Make it pretty */
.scroll {
padding-left: 1.5em;
position: fixed;
font: 50px'Verdana';
bottom: 0px;
color: white;
left: 0px;
height: 10%;
}
</style>
</head>
<body>
<div class="marquee">
<span>Lots of text, written in a long sentance to make it go off the screen. Well I hope it goes off the screen</span>
</div>
</body>
</html>
The script is a css and javascript marquee to control a steady speed for the scrolling text.
Any idea what I am missing?
Also, as you can see on the fiddle, it takes a while for the text to start scrolling. Can I reduce the delay?
Call your JS function once all the DOM is ready, usually this is being done by using window.onload as follows:
window.onload = function() {
calcSpeed(75);
}
You are trying to select an element that has not been created yet.
Move your script to below the marquee
<div class="marquee">
<span>Lots of text, written in a long sentance to make it go off the screen. Well I hope it goes off the screen</span>
</div>
<script type="text/javascript">
function calcSpeed(speed) {
// Time = Distance/Speed
var spanSelector = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelector.length; i++) {
var spanLength = spanSelector[i].offsetWidth,
timeTaken = spanLength / speed;
spanSelector[i].style.animationDuration = timeTaken + "s";
}
}
calcSpeed(75);
</script>
put your script and style codes before the closing of body.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="marquee">
<span>Lots of text, written in a long sentance to make it go off the screen. Well I hope it goes off the screen</span>
</div>
<script>
function calcSpeed(speed) {
// Time = Distance/Speed
var spanSelector = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelector.length; i++) {
var spanLength = spanSelector[i].offsetWidth,
timeTaken = spanLength / speed;
spanSelector[i].style.animationDuration = timeTaken + "s";
}
}
calcSpeed(75);
</script>
<style>
/* Make it a marquee */
.marquee {
width: 100%;
left: 0px;
height: 10%;
position: fixed;
margin: 0 auto;
white-space: nowrap;
overflow: hidden;
background-color: #000000;
bottom: 0px;
color: white;
font: 50px'Verdana';
}
.marquee span {
display: inline-block;
padding-left: 100%;
text-indent: 0;
animation: marquee linear infinite;
animation-delay: 5s;
background-color: #000000;
color: white;
bottom: 0px;
}
/* Make it move */
#keyframes marquee {
0% {
transform: translate(10%, 0);
}
100% {
transform: translate(-100%, 0);
}
}
/* Make it pretty */
.scroll {
padding-left: 1.5em;
position: fixed;
font: 50px'Verdana';
bottom: 0px;
color: white;
left: 0px;
height: 10%;
}</style>
</body>
</html>
this works on me
You should write all script in last of page because script will trying to find tag id's and DOM is not ready that time than give error.
Sample
<html>
<head>
<style>
/* your style here */
</style>
</head>
<body>
<!-- your html here -->
<script>
// your script here
</script>
</body>
</html>
Please read
JavaScript and CSS order
See this
function calcSpeed() {
// Time = Distance/Speed
var spanSelector = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelector.length; i++) {
var spanLength = spanSelector[i].offsetWidth,
timeTaken = spanLength / 1000;
spanSelector[i].style.animationDuration = timeTaken + "s";
}
//calcSpeed(10);
}
</script>
<body onload="calcSpeed()">
I tested it on Chrome and Firefox...works perfectly. So, I presume it should work for you too.

Fluid Box jQuery plugin not working

Can someone please tell me why my fluid box isn't working for my photo. I've followed all of the instructions to create the code for the fluidbox, but my photo doesn't show up on the webpage. But when you click on where it is supposed to be on the webpage, it takes you to another page that has my photo in it. Here is my codes:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootswatch: Cosmo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./bootstrap.css" media="screen">
<link rel="stylesheet" href="bootstrap-lightbox.css">
<link rel="stylesheet" href="portfoliostyle.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="../bower_components/html5shiv/dist/html5shiv.js"></script>
<script src="../bower_components/respond/dest/respond.min.js"></script>
<![endif]-->
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-23019901-1']);
_gaq.push(['_setDomainName', "bootswatch.com"]);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script src="jquery.js"></script>
<script src="imagelightbox.js"></script>
<script>
$( function()
{
$( 'a' ).imageLightbox();
});
</script>
</head>
<body>
<ul class="navigation">
<li class="nav-item">Home</li>
<li class="nav-item">Portfolio</li>
<li class="nav-item">About</li>
<li class="nav-item">Blog</li>
<li class="nav-item">Contact</li>
</ul>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger"></label>
<div class="site-wrap">
<div class="gallery">
<a class="space" href="images/spacetime.jpg" title="A Space in Time" data-fluidbox>
<img src="images/spacetime.jpg" />
</a>
<a href="images/spacetime.jpg" data-fluidbox>
<div class="fluidbox-wrap">
<img src="images/spacetime.jpg" />
<div class="fluidbox-ghost"></div>
</div>
</a>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
$(function () {
// Global variables
var $fb = $('a[data-fluidbox');
vpRatio; // To store viewport aspect ratio
// Add class to all Fluidboxes
$fb.addClass('fluidbox');
// Create fluidbox modal background
$('body').append('<div id="fluidbox-overlay"></div>');
// Functions:
// 1. to close any opened Fluidbox
// 2. to position Fluidbox dynamically
var closeFb = function (){
$('a[data-fluidbox].fluidbox-opened').trigger('click');
},
positionFb = function ($activeFb){
// Get elements
var $img = $activeFb.find('img'),
$ghost = $activeFb.find('.fluidbox-ghost');
// Calculate offset and scale
var offsetY = $(window).scrollTop()-$img.offset().top+0.5*($img.data('imgHeight')*($img.data('imgScale')-1))+0.5*($(window).height()-$img.data('imgHeight')*$img.data('imgScale')),
offsetX = 0.5*($img.data('imgWidth')*($img.data('imgScale')-1))+0.5*($(window).width()- $img.data('imgWidth')*$img.data('imgScale')) - $img.offset().left,
scale = $img.data('imgScale');
// Animate wrapped elements
// Parse integers:
// 1. Offsets can be integers
// 2. Scale is rounded to nearest 2 decimal places
$ghost.css({ 'transform': 'translate('+parseInt(offsetX*10)/10+'px,'+parseInt(offsetY*10)/10+'px) scale('+parseInt(scale*1000)/1000+')' });
}
// The following events will force FB to close
// ... when the opqaue overlay is clicked upon
$('#fluidbox-bg').click(closeFb);
})();
$fb.imagesLoaded().done(function (){
$fb
.wrapInner('<div class="fluidbox-wrap" />')
.find('img')
.css({ opacity: 1 })
.after('<div class="fluidbox-ghost" />');
// Listen to resize event for calculations
$(window).resize(function (){
// Get viewport aspect ratio (#1)
vpRatio = $(window).width() / $(window).height();
// Get dimensions and aspect ratios
$fb.each(function (){
var $img = $(this).find('img'),
$ghost = $(this).find('.fluidbox-ghost'),
$wrap = $(this).find('.fluidbox-wrap'),
data = $img.data();
// Save image dimensions as jQuery object (#2)
data.imgWidth = $img.width();
data.imgHeight = $img.height();
data.imgRatio = $img.width() / $img.height();
// Resize ghost element (#3)
$ghost.css({
width: $img.width(),
height: $img.height(),
top: $img.offset().top - $wrap.offset().top,
left: $img.offset().left - $wrap.offset().left
});
// Calculate scale based on orientation (#4)
if(vpRatio > data.imgRatio) {
data.imgScale = $(window).height()*.95 / $img.height();
} else {
data.imgScale = $(window).width()*.95 / $img.width();
}
});
}).resize();
// Bind click event
$fb.click(function (e){
// Variables
var $img = $(this).find('img'),
$ghost = $(this).find('.fluidbox-ghost'),
$wrap = $(this).find('.fluidbox-wrap');
if($(this).data('fluidbox-state') == 0 || !$(this).data('fluidbox-state')) {
// State: Closed
// Action: Open Fluidbox
$(this)
.data('fluidbox-state', 1)
.removeClass('fluidbox-closed')
.addClass('fluidbox-opened');
// Show overlay
$('#fluidbox-overlay').fadeIn();
// Set thumbnail image source as background image first.
// We also show the ghost element
$ghost.css({
'background-image': 'url('+$img.attr('src')+')',
opacity: 1
});
// Hide original image
$img.css({ opacity: 0 });
// Preload ghost image
var ghostImg = new Image();
ghostImg.onload = function (){ $ghost.css({ 'background-image': 'url('+$activeFb.attr('href')+')' } ); };
ghostImg.src = $(this).attr('href');
// Position Fluidbox
positionFb($(this));
} else {
// State: Opened
// Action: Close Fluidbox
/// Switch state
$(this)
.data('fluidbox-state', 0)
.removeClass('fluidbox-opened')
.addClass('fluidbox-closed');
// Hide overlay
$('#fluidbox-overlay').fadeOut();
// Show original image
$img.css({ opacity: 1 });
// Hide ghost image
$ghost.css({ opacity: 0 });
// Reverse animation on wrapped elements
$ghost
.css({ 'transform': 'translate(0,0) scale(1)' })
.one('webkitTransitionEnd MSTransitionEnd oTransitionEnd transitionend', function (){
// Wait for transntion to run its course first
$ghost.css({ opacity: 0 });
});
}
});
</script>
CSS:
/* Navigation Menu - Background */
.navigation {
/* critical sizing and position styles */
width: 100%;
height: 100%;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 0;
/* non-critical appearance styles */
list-style: none;
background: #111;
}
/* Navigation Menu - List items */
.nav-item {
/* non-critical appearance styles */
width: 200px;
border-top: 1px solid #111;
border-bottom: 1px solid #000;
}
.nav-item a {
/* non-critical appearance styles */
display: block;
padding: 1em;
background: linear-gradient(135deg, rgba(0,0,0,0) 0%,rgba(0,0,0,0.65) 100%);
color: white;
font-size: 1.2em;
text-decoration: none;
transition: color 0.2s, background 0.5s;
}
.nav-item a:hover {
color: #c74438;
background: linear-gradient(135deg, rgba(0,0,0,0) 0%,rgba(75,20,20,0.65) 100%);
}
.site-wrap {
min-width: 100%;
min-height: 100%;
background-color: #fff;
position: absolute;
top: 0;
bottom: 100%;
left: 0;
z-index: 1;
padding: 4em;
background-image: linear-gradient(135deg,
rgb(254,255,255) 0%,
rgb(221,241,249) 35%,
rgb(160,216,239) 100%);
background-size: 200%;
}
.name {
position: absolute;
top: 60%;
right:40%;
}
h3{
text-align: center;
top: 65%;
}
/* Nav Trigger */
.nav-trigger {
/* critical styles - hide the checkbox input */
position: absolute;
clip: rect(0, 0, 0, 0);
}
label[for="nav-trigger"] {
/* critical positioning styles */
position: fixed;
left: 15px; top: 15px;
z-index: 2;
/* non-critical apperance styles */
height: 30px;
width: 30px;
cursor: pointer;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' x='0px' y='0px' width='30px' height='30px' viewBox='0 0 30 30' enable-background='new 0 0 30 30' xml:space='preserve'><rect width='30' height='6'/> <rect y='24' width='30' height='6'/><rect y='12' width='30' height='6'/></svg>");
background-size: contain;
}
/* Make the Magic Happen */
.nav-trigger + label, .site-wrap {
transition: left 0.2s;
}
.nav-trigger:checked + label {
left: 215px;
}
.nav-trigger:checked ~ .site-wrap {
left: 200px;
box-shadow: 0 0 5px 5px rgba(0,0,0,0.5);
}
body {
/* Without this, the body has excess horizontal scroll when the menu is open */
overflow-x: hidden;
}
/* Additional non-critical styles */
h1, h3, p {
max-width: 600px;
margin: 0 auto 1em;
}
code {
padding: 2px;
background: #ddd;
}
/* Micro reset */
*,*:before,*:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border- box;margin:0;padding:0;}
html, body { height: 100%; width: 100%; font-family: Helvetica, Arial, sans-serif; }
/* Image Lightbox Galley */
a[data-fluidbox] {
background-color: #eee;
border: none;
cursor: -webkit-zoom-in;
cursor: -moz-zoom-in;
margin-bottom: 1.5rem;
}
a[data-fluidbox].fluidbox-opened {
cursor: -webkit-zoom-out;
cursor: -moz-zoom-out;
}
a[class^='float'] {
margin: 1rem;
margin-top: 0;
width: 33.33333%;
}
a.float-left {
float: left;
margin-left: 0;
}
a.float-right {
float: right;
margin-right: 0;
}
a[data-fluidbox] img {
display: block;
margin: 0 auto;
opacity: 0;
max-width: 100%;
transition: all .25s ease-in-out;
}
#fluidbox-overlay {
background-color: rgba(255,255,255,.85);
cursor: pointer;
cursor: -webkit-zoom-out;
cursor: -moz-zoom-out;
display: none;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 500;
}
.fluidbox-wrap {
background-position: center center;
background-size: cover;
margin: 0 auto;
position: relative;
z-index: 400;
transition: all .25s ease-in-out;
}
.fluidbox-opened .fluidbox-wrap {
z-index: 600;
}
.fluidbox-ghost {
background-size: cover;
background-position: center center;
position: absolute;
transition: all .25s ease-in-out;
}
.space img{
height: 25%;
width: 50%
}

HTML Pong attemp not working

I have started a pong game where the guidelines have already been set for me but I have an issue with the ball. It is very early in development but I am stuck on this problem: The X axis will not move up and down. The ball is not meant to bounce off the paddles yet. Here is my code:
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ping Pong</title>
<link href="pong.css" rel="stylesheet" type="text/css"/>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/pong.js" type="text/javascript"></script>
</head>
<body>
<header>
<h1>Ping Pong</h1>
</header>
<!-- Scoreboard goes here -->
<div id="game">
<div id="playground">
<div id="ball"></div>
<div id="paddleA" class="paddle"></div>
<div id="paddleB" class="paddle"></div>
</div>
</div>
<!-- used for debugging -->
<div id="debug">
</div>
<footer>
This is an example of creating a Ping Pong Game.
</footer>
</body>
</html>
Pong.js
var KEY = {
UP:38,
DOWN:40,
W:87,
S:83
};
var directionX = 1;
var directionY = 1;
$(function(){
var timer = setInterval(gameloop,30)
});
//This is where the logic for the game goes.
function gameloop(){
var playground = $("#playground");
var ball = $("#ball");
var width = parseInt (playground.css("width"))
var left = parseInt (ball.css("left"));
if(left >= width){
directionX = -1;
}
else if (left <= 0){
directionX = 1;
}
var height = parseInt (playground.css("height"))
var top = parseInt (ball.css("top"));
if(top >= height){
directionY = -1;
}
else if (top <= 0){
directionY = 1;
}
ball.css("left",left+5 * directionX);
ball.css("top",height+5 * directionY);
}
function debug(text){
$("#debug").text(text);
}
And pong.css
#playground{
background: #e0ffe0 /*url(images/pixel_grid.jpg)*/;
width: 400px;
height: 200px;
position: relative;
overflow: hidden;
}
#ball {
background: #fbb;
position: absolute;
width: 20px;
height: 20px;
left: 150px;
top: 100px;
border-radius: 10px;
}
.paddle {
background: #bbf;
left: 50px;
top: 70px;
position: absolute;
width: 30px;
height: 70px;
}
#paddleB {
left: 320px;
}
#winner{
display:none;
position: relative;
width: 200px;
margin-left: 100px;
top: 30%;
font-size: 20px;
border: 3px solid red;
padding: 20px;
background-color: #FFF;
text-align:center;
font-family: Comic-Sans;
}
Oh and in case you were wondering, the js library was written for me.
You're using the height of the element instead of the offset (top).
It should be
ball.css("top", top + 5 * directionY);
I believe you need to use px when setting the CSS for top and left.
ball.css("left",(left+5 * directionX) + "px");
ball.css("top",(height+5 * directionY) + "px");

Categories

Resources