Nice scrolling parallax effect isn't working - javascript

This is the link to the website: http://codepen.io/zabielski/pen/MyoBaY/
I am following the instructions and code from this website to try and get a similar scrolling parallax effect. Below is my HTML, CSS and JavaScript code (basically just copying but with my own images and stuff).
<!DOCTYPE html>
<html lang="en">
<!--Meta equiv for the whole web page to be emulated into IE straight from the chrome styling, If this is not done, then the whole webpage is green instead of the gray and orange and the text on the opage is shoved onto the far left side of the page.-->
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7"/>
<!--Link to Favicon-->
<link rel="shortcut icon" type="image/x-icon" href="Favicon/Ulearn.ico">
<!--Links to CSS style sheet-->
<link rel="stylesheet" type="text/css" href="CSS style sheets/Main style sheet.css">
<link rel="stylesheet" type="text/css" href="CSS style sheets/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="CSS style sheets/animate.min.css">
<!--Links to JavaScript external sheets-->
<script type="text/javascript" src="JavaScript sheets/Main javascript.js"></script>
<script type="text/javascript" src="JavaScript sheets/jquery-2.2.3.js"></script>
<head>
<span class="header">Physics Level 3</span>
<!--Meta and links to make sure the webpage is dynamic-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Playfair+Display' rel='stylesheet' type='text/css'>
</head>
<body>
<div id='hero'>
<div class='layer-1 layer' data-depth='0.20' data-type='parallax'></div>
<div class='layer-2 layer' data-depth='0.50' data-type='parallax'></div>
<div class='layer-3 layer' data-depth='0.80' data-type='parallax'></div>
<div class='layer-4 layer' data-depth='1.00' data-type='parallax'></div>
</div>
<div id="content">
</div>
</body>
</html>
#hero {
height: 1000px;
overflow: hidden;
position: relative;
}
.header {
background-color: white;
border-style: solid;
border-width: 0px;
position: absolute;
text-align: left;
left: 1%;
top: 2.4%;
width: 97%;
padding-top: 1%;
padding-bottom: 1%;
padding-left: 0.7%;
padding-right: 0.2%;
z-index: 1;
}
.layer {
background-position: center;
background-size: auto;
width: 100%;
height: 800px;
position: fixed;
z-index: -1;
}
.layer-1 {
background-image: url("background-last.jpg");
}
.layer-2 {
background-image: url("background-middle.png");
background-repeat: no-repeat;
background-position: center;
}
.layer-3 {
background-image: url("background-top.png");
background-repeat: no-repeat;
}
.layer-4 {
background-image: url("background-verytop.png");
}
(function () {
window.addEventListener('scroll', function (event) {
var depth, i, layer, layers, len, movement, topDistance, translate3d;
topDistance = this.pageYOffset;
layers = document.querySelectorAll('[data-type=\'parallax\']');
for (i = 0, len = layers.length; i < len; i++) {
if (window.CP.shouldStopExecution(1)) {
break;
}
layer = layers[i];
depth = layer.getAttribute('data-depth');
movement = -(topDistance * depth);
translate3d = 'translate3d(0, ' + movement + 'px, 0)';
layer.style['-webkit-transform'] = translate3d;
layer.style['-moz-transform'] = translate3d;
layer.style['-ms-transform'] = translate3d;
layer.style['-o-transform'] = translate3d;
layer.style.transform = translate3d;
}
window.CP.exitedLoop(1);
});
}.call(this));

You cant just copy and paste all off the contents, you must format it - the code was specially compiled.
Here's the formatted RAW page:
<html class="animated fadeIn">
<head>
<script src="//assets.codepen.io/assets/editor/live/console_runner-d0a557e5cb67f9cd9bbb9673355c7e8e.js"></script><script src="//assets.codepen.io/assets/editor/live/events_runner-21174b4c7273cfddc124acb0876792e0.js"></script><script src="//assets.codepen.io/assets/editor/live/css_live_reload_init-7618a0de08795409d8f6c9ef6805f7b2.js"></script>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<link rel="canonical" href="http://codepen.io/zabielski/pen/MyoBaY/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Playfair+Display" rel="stylesheet" type="text/css">
<link rel="stylesheet prefetch" href="//codepen.io/assets/reset/normalize.css">
<link rel="stylesheet prefetch" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet prefetch" href="//cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.3/animate.min.css">
<style class="cp-pen-styles">body {
padding: 0;
margin: 0;
background-color: #130d0a;
font-family: 'Playfair Display', serif;
color: #fff;
}
#hero {
height: 800px;
overflow: hidden;
position: relative;
}
#content {
background-color: #130d0a;
}
.layer {
background-position: bottom center;
background-size: auto;
background-repeat: no-repeat;
width: 100%;
height: 800px;
position: fixed;
z-index: -1;
}
#hero-mobile {
display: none;
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/full_illustration.png") no-repeat center bottom/cover;
height: 320px;
}
.first-section {
padding: 50px 0 20px 0;
}
.text-header {
font-size: 50px;
text-align: center;
}
h1 {
line-height: 120%;
margin-bottom: 30px;
}
p {
color: #ede0d5;
font-size: 18px;
line-height: 150%;
}
#hero, .layer {
min-height: 800px;
}
.layer-bg {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_bg.jpg");
}
.layer-1 {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_03.png\a ");
background-position: left bottom;
}
.layer-2 {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_02.png");
}
.layer-3 {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_man.png\a ");
background-position: right bottom;
}
.layer-4 {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_01.png\a ");
}
.layer-overlay {
background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_overlay.png\a ");
}
#media only screen and (max-width: 768px) {
#hero {
display: none;
}
#hero-mobile {
display: block;
}
}
.tutorial-link {
color: #fff;
font-size: 18px;
text-decoration: underline;
}
.tutorial-link:hover {
color: #ede0d5;
}
</style>
</head>
<body>
<div id="hero">
<div class="layer-bg layer" data-depth="0.10" data-type="parallax"></div>
<div class="layer-1 layer" data-depth="0.20" data-type="parallax"></div>
<div class="layer-2 layer" data-depth="0.50" data-type="parallax"></div>
<div class="layer-3 layer" data-depth="0.80" data-type="parallax"></div>
<div class="layer-overlay layer" data-depth="0.85" data-type="parallax"></div>
<div class="layer-4 layer" data-depth="1.00" data-type="parallax"></div>
</div>
<div id="hero-mobile"></div>
<div id="content">
<div class="container">
<section class="first-section">
<div class="row">
<div class="col-sm-6">
<h1>You cannot hide the soul. Through all his unearthly tattooings, I thought I saw the traces of a simple honest heart.</h1>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<p>And besides all this, there was a certain lofty bearing about the Pagan, which even his uncouthness could not altogether maim. He looked like a man who had never cringed and never had had a creditor. Whether it was, too, that his head being shaved, his forehead was drawn out in freer and brighter relief, and looked more expansive than it otherwise would, this I will not venture to decide; but certain it was his head was phrenologically an excellent one.</p>
<p>It may seem ridiculous, but it reminded me of General Washington's head, as seen in the popular busts of him. It had the same long regularly graded retreating slope from above the brows, which were likewise very projecting, like two long promontories thickly wooded on top. Queequeg was George Washington cannibalistically developed.</p>
<p>Whilst I was thus closely scanning him, half-pretending meanwhile to be looking out at the storm from the casement, he never heeded my presence, never troubled himself with so much as a single glance; but appeared wholly occupied with counting the pages of the marvellous book. Considering how sociably we had been sleeping together the night previous, and especially considering the affectionate arm I had found thrown over me upon waking in the morning, I thought this indifference of his very strange. But savages are strange beings; at times you do not know exactly how to take them.</p>
</div>
<div class="col-sm-6">
<p>At first they are overawing; their calm self-collectedness of simplicity seems a Socratic wisdom. I had noticed also that Queequeg never consorted at all, or but very little, with the other seamen in the inn. He made no advances whatever; appeared to have no desire to enlarge the circle of his acquaintances. All this struck me as mighty singular; yet, upon second thoughts, there was something almost sublime in it. Here was a man some twenty thousand miles from home, by the way of Cape Horn, that is—which was the only way he could get there—thrown among people as strange to him as though he were in the planet Jupiter; and yet he seemed entirely at his ease; preserving the utmost serenity; content with his own companionship; always equal to himself.</p>
<p>Here was a man some twenty thousand miles from home, by the way of Cape Horn, that is—which was the only way he could get there—thrown among people as strange to him as though he were in the planet Jupiter; and yet he seemed entirely at his ease; preserving the utmost serenity; content with his own companionship; always equal to himself. Surely this was a touch of fine philosophy; though no doubt he had never heard there was such a thing as that.</p>
<a class="tutorial-link" href="https://medium.com/#PatrykZabielski/how-to-make-multi-layered-parallax-illustration-with-css-javascript-2b56883c3f27">
Learn how to create this parallax effect
</a>
</div>
</div>
</section>
</div>
</div>
<script src="//assets.codepen.io/assets/common/stopExecutionOnTimeout.js?t=1"></script>
<script>(function () {
window.addEventListener('scroll', function (event) {
var depth, i, layer, layers, len, movement, topDistance, translate3d;
topDistance = this.pageYOffset;
layers = document.querySelectorAll('[data-type=\'parallax\']');
for (i = 0, len = layers.length; i < len; i++) {
if (window.CP.shouldStopExecution(1)) {
break;
}
layer = layers[i];
depth = layer.getAttribute('data-depth');
movement = -(topDistance * depth);
translate3d = 'translate3d(0, ' + movement + 'px, 0)';
layer.style['-webkit-transform'] = translate3d;
layer.style['-moz-transform'] = translate3d;
layer.style['-ms-transform'] = translate3d;
layer.style['-o-transform'] = translate3d;
layer.style.transform = translate3d;
}
window.CP.exitedLoop(1);
});
}.call(this));
//# sourceURL=pen.js
</script>
</body>
</html>

Related

Load stylesheet with javascript and localStorage

I'm using a Jekyll website, doesn't really matter because this is a static page, I just write it as additional info.
Desired behavior:
I want to load my stylesheet via javascript, so it can depend of a local stored value, let's say dark and light.
I have done a little test of loading it by JS with the following code (which works).
GREEN
<head>
...
<link rel="stylesheet" href="/assets/css/{{'light'}}.css">
...
</head>
This loads the CSS file called "light" as expected.
But now I want to depend of the localStorage, with a variable theme that has light as value. I tried the following:
RED
<head>
...
<script>
var storedTheme = window.localStorage.getItem('theme'); //Tested and working in console
theme = storedTheme ? storedTheme : 'light'; //global variable (also readable in console)
</script>
<link rel="stylesheet" href="/assets/css/{{theme}}.css"> <!-- cant read global variable -->
...
</head>
Using global variables doesn't work, it gives me a 404 error as the stylesheet path is /assets/css/.css.
After that I thought that maybe creating an element would do the trick and I created one manually to test it:
RED
<head>
...
<p id="theme" style="display:none;">dark</p>
<link rel="stylesheet" href="/assets/css/{{document.getElementById('theme').innerHTML}}.css">
...
</head>
And nope, the path still appears as: /assets/css/.css
If you change styles on the <body> you get FOUC (Flash Of Unstyled Content). Try using a close equivalent like <main> and spread it 100% x 100% and <html> and <body> as well, but give them margin and padding of 0 in order to ensure <main> covers them completely.
The [disabled] attribute for the <link> is the best way of toggling them because they are still loaded but inert. Also, in the example there is a function called loadTheme(e) that is loaded on the 'DOMContentLoaded' event which insures that all of the DOM is loaded before hand. The example below will not work because localStorage is blocked on SO. There is a functioning example on Plunker. To test it:
Click the green Preview button.
Another frame should appear on the right. Within the frame is the webpage example click the ☀️ button.
It should be in dark mode now. Next, click the refresh ⟳ button located in the mini-toolbar within the frame or press ctrl+enter for Windows OS or ⌥+return for Mac OS.
The page should still be in dark mode. 👍
/* night.css
main {
background: #000;
color: #fff;
}
*/
/* default.css */
:root {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font: 1ch/1.5 'Segoe UI';
}
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-size: 4ch;
}
main {
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
color: #000;
}
form {
width: 80vw;
margin: 20px auto;
}
fieldset {
width: max-content;
min-height: 25px;
margin-left: auto;
padding: 0 1.5px 1.5px;
border-radius: 8px;
background: inherit;
color: inherit;
}
button {
display: block;
width: 100%;
height: 100%;
border: 0;
font-size: 4rem;
text-align: center;
background: transparent;
cursor: pointer;
}
#theme::before {
content: '☀️';
}
.night #theme::before {
content: '🌙';
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='lib/default.css' rel='stylesheet'>
<link class='night' href='lib/night.css' rel='stylesheet' disabled>
<style></style>
</head>
<body>
<main>
<form id='UI'>
<fieldset name='box'>
<legend>Theme</legend>
<button id='theme' type='button'></button>
</fieldset>
<p>Click the "Theme" switch to toggle between `disabled` `true` and `false` on `night.css` and `light.css` `
<link>`s.</p>
</form>
</main>
<script>
const UI = document.forms.UI;
const M = document.querySelector('main');
const L = document.querySelector('.night')
const switchTheme = e => {
const clk = e.target;
if (clk.matches('button')) {
M.classList.toggle('night');
L.toggleAttribute('disabled');
}
let status = M.className === 'night' ? 'on' : 'off';
localStorage.setItem('theme', status);
};
const loadTheme = e => {
let cfg = localStorage.getItem('theme');
if (cfg === 'on') {
M.classList.add('night');
L.removeAttribute('disabled');
} else {
M.classList.remove('night');
L.setAttribute('disabled', true);
}
};
UI.addEventListener('click', switchTheme);
document.addEventListener('DOMContentLoaded', loadTheme);
</script>
</body>
</html>

How do I make clickable images return unique values?

I'm trying to make a Monty Hall simulator. The user is presented with three identical pictures of a door, lined up in a row. They choose their door by clicking on image one, two, or three.
I'm unable to figure out a way to get that value into JavaScript. What I mean is, I don't know how to tell JavaScript that the user clicked, say, door one and then assign the value of 1 to a variable which I can then play around with. Here's the code (for what it's worth. I've not managed to come within a thousand miles of a solution):
// ELEMENT VARIABLES
const instructions = document.getElementById('instructions');
const startGameButton = document.getElementById('startGameButton');
const door1 = document.getElementById('door1');
const door2 = document.getElementById('door2');
const door3 = document.getElementById('door3');
// CHOOSING THE PRIZE DOOR
let prizeDoor = Math.floor(Math.random() * 3 + 1);
// LOADING ALL EVENT LISTENERS
function loadEventListeners() {
startGameButton.addEventListener('click', removeInstructionsAndButtonAndMakeDoorsAppear);
}
loadEventListeners();
function removeInstructionsAndButtonAndMakeDoorsAppear() {
instructions.innerHTML = '';
door1.style.display = 'block';
door2.style.display = 'block';
door3.style.display = 'block';
}
#import url('https://fonts.googleapis.com/css2?family=Acme&family=Dancing+Script&family=Festive&family=Lato:wght#100;300;400;700&family=Tourney:wght#100;200;300;400;500&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Festive&family=Tourney:wght#100;200;300;400;500&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Acme&family=Festive&family=Tourney:wght#100;200;300;400;500&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Acme&family=Festive&family=Lato:wght#100;300;400;700&family=Tourney:wght#100;200;300;400;500&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
font-size: 62.5%;
font-family: 'Lato', 'Arial', sans-serif;
}
body {
background-color: rgb(178, 237, 252);
}
.show-title {
font-family: 'Dancing Script';
text-align: center;
font-size: 5rem;
word-spacing: 3rem;
letter-spacing: 1rem;
margin-top: 1rem;
}
.introduction {
position: absolute;
font-family: 'Acme';
top: 40%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 3rem;
text-align: center;
}
.rules {
font-size: 1.8rem;
margin-top: 2rem;
}
.start-game {
font-family: 'Tourney';
color: white;
font-size: 1.5rem;
margin-top: 2rem;
padding-top: .8rem;
padding-bottom: .8rem;
padding-left: 2.5rem;
padding-right: 2.5rem;
background-color: black;
border-radius: 10px;;
}
.door-container {
display: flex;
justify-content: center;
align-items: center;
height: 70vh;
}
.door-styling {
margin-left: 8rem;
cursor: pointer;
}
.door {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>MONTY HALL</title>
</head>
<body>
<div class="title">
<h1 class="show-title">THE MONTY HALL SHOW</h1>
</div>
<div class="introduction" id="instructions">
<p class="welcome">Welcome to the Monty Hall Show.</p>
<p class="rules">The rules are simple. You'll be shown three doors, behind one of which is a jpeg of a briefcase full of cash. Behind the others? <br><br>Goats. <br><br>Yeah. That's right. Dirty, smelly, ungrateful goats.</p>
<p class="rules">All you have to do is pick the door behind which you think lies the cash. I will then open <em>one</em> of the two remaining doors. You'll then be given an opportunity to stick with your original choice, or switch to the one remaining door.</p>
<p class="rules">May the odds be ever in your favour.</p>
<button class="start-game" id="startGameButton">I understand</button>
</div>
<div class="door-container">
<img src="img/doors.jpg" class="door door-styling" id="door1">
<img src="img/doors.jpg" class="door door-styling" id="door2">
<img src="img/doors.jpg" class="door door-styling" id="door3">
</div>
<script src="app.js"></script>
</body>
</html>
I've been working on this for about five hours today, trying everything I can think of and googling my ass off, all to no avail. Any help you could provide would be gratefully appreciated.
Add this function to your javascript:
function doorClicked(doorNumber) {
console.log('Clicked', doorNumber);
// store to variable and do your thing
}
and in the HTML add onclick to your door images:
<img src="img/doors.jpg" class="door door-styling" id="door1" onclick="doorClicked(1)">
<img src="img/doors.jpg" class="door door-styling" id="door2" onclick="doorClicked(2)">
<img src="img/doors.jpg" class="door door-styling" id="door3" onclick="doorClicked(3)">
I think this is a good approach to do it. Just create an event on click and read the door id number. Good luck!
let selectedDoor = 0;
let doors = document.getElementsByClassName("door");
for (let i = 0; i < doors.length; i++) {
doors[i].addEventListener("click", function(){
selectedDoor = parseInt(this.id.split("door")[1]);
console.log(selectedDoor);
});
}
img {
width: 150px;
cursor: pointer;
margin: 10px;
}
<img src="https://images.ole.com.ar/2021/07/10/g0_-ovqlt_720x0__1.jpg" class="door door-styling" id="door1">
<img src="https://images.ole.com.ar/2021/07/10/g0_-ovqlt_720x0__1.jpg" class="door door-styling" id="door2">
<img src="https://images.ole.com.ar/2021/07/10/g0_-ovqlt_720x0__1.jpg" class="door door-styling" id="door3">
learn to use event delegation:
const
allDoors = document.querySelector('#door-container')
, prizeDoor = Math.floor(Math.random() * 3 + 1);
;
allDoors.onclick = ({target}) =>
{
if (!target.matches('img')) return // ignore clicks on spaces
let good_door = (prizeDoor == target.dataset.door)
allDoors.classList.add('no-more-click')
target.classList.add( (good_door?'good':'wrong'))
console.log(`expected is ${prizeDoor}, door clicked is ${target.dataset.door}, => ${good_door} `)
}
#door-container img {
cursor : pointer;
padding : 2px;
border : 5px solid grey;
margin : 2px;
}
#door-container img:hover {
border-color : yellow;
}
#door-container img.good {
border-color : green;
}
#door-container img.wrong {
border-color : red;
}
.no-more-click {
pointer-events : none;
}
<div id="door-container">
<img src="https://picsum.photos/id/1003/150" data-door="1">
<img src="https://picsum.photos/id/1025/150" data-door="2">
<img src="https://picsum.photos/id/1074/150" data-door="3">
</div>

progress bar for loading animation of webpage

I want to make a loading animation for my webpage which will take 8-10 sec to load using JavaScript or Ajax(Which I don't know)
The loading animation is a progress bar
Which I want to stop for every 1 sec for increment of 10% eg( https://codepen.io/gustitammam/pen/RRXGdj )
Bootstrap is not welcomed and I don't want text and percentage on it
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="D:\PORTFOLIO\master.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.js" integrity="sha512-qsjFwnCEe/k1YLJDkiRqDgKb+Eq+35xdoeptV7qfI7P6G/kajIF0R6d/9SiOxSkU/aNmHzuipOEYaTUHCJUIeQ==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript.util/0.12.12/javascript.util.min.js" integrity="sha512-oHBLR38hkpOtf4dW75gdfO7VhEKg2fsitvHZYHZjObc4BPKou2PGenyxA5ZJ8CCqWytBx5wpiSqwVEBy84b7tw==" crossorigin="anonymous"></script>
</head>
<body>
<div id="myprogress">
<div id="mybar">
<span id="incvalue">1%</span>
</div>
</div>
<br> <button onclick="move()">ClickMe</button>
<script>
const move = () => {
var elem = document.getElementById("mybar");
var width = 1;
var id = setInterval(frame, 10)
function frame(){
if(width >= 100){
clearInterval(id);
}else{
width++;
elem.style.width = width + "%";
document.getElementById("incvalue").innerHTML = width + "%";
}
}
}
</script>
</body>
</html>
CSS
html{
scroll-behavior: smooth;
}
body{
background: #181818;
color: #f4eee8;
}
#myprogress{
width: 45%;
background: #181818;
margin: auto;
}
#mybar{
width: 1%;
background: white;
color: white;
text-align: center;
}
In the example you cited, you can just comment out the JS lines where the following fields are set:
.attr and .text
Regarding your desire to omit Bootstrap, however, you are not asking a simple technical question but proposing that somebody write a whole program fragment for you, which is generally not the intended purpose of Stack overflow.
Actually I didn't do it but I don't know his Stack ID so #0_0#1045(From Discord)
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="D:\PORTFOLIO\master.css">
</head>
<body>
<h3>Dynamic Progress Bar</h3>
<p>Running progress bar from 0% to 100% in 10 seconds</p>
<div class="progress">
<div class="current-progress">
</div>
</div>
</div>
<script src="master.js"></script>
</body>
</html>
CSS
html{
scroll-behavior: smooth;
}
body{
background: #181818;
color: #f4eee8;
height: 100vh;
width: 100vw;
}
.progress {
position: relative;
margin-top: 20px;
height: 20px;
width: 700px;
background-color: #181818;
}
.current-progress {
height: 100%;
width: 0%;
background-color: white;
text-align: center;
transition: all 0.3s;
}
JS
let progressValue = 0;
const progressBar = document.querySelector(".current-progress");
progressBar.style.width = `${progressValue}%`;
const timer = setInterval(() => {
if (progressValue < 100) {
progressValue += 10;
progressBar.style.width = `${progressValue}%`;
}
if (progressValue === 100) {
clearInterval(timer);
}
}, 1000);
Finally Solved!!!

Inverted logo based on background colour

I'm wondering if anyone has discovered a beautiful way to rotate out logo's based on 'sections' of the page.
In more detail I have a logo on a transparent navbar, let's say a white logo.
My page is broken into sections, some gray/light background some darker/black backgrounds. As I scroll, I hope that the sticky logo will be swapped out to an opposing color. I attempted to do this by naming each section with an id such as id='white and id=black.
Then once I scrolled down and hit that I'd trigger the function and swap out the picture, although, I realized that it only detects the first id of white or the second of black.
Not sure how to approach this other then make a unique id for each section, which, seems barbaric.
window.onscroll = function() {
myFunction()
};
function myFunction() {
if ($(this).scrollTop() >= $('#white').position().top) {
logoSwap(0);
} else if (($(this).scrollTop() >= $('#black').position().top)) {
logoSwap(1);
}
}
function logoSwap(which) {
if (which) {
$('#logo').css("background-color", "black");
} else {
$('#logo').css("background-color", "white");
}
}
#logo {
position: fixed;
top: 0;
left: 0;
height: 50px;
width: 50px;
background-color: black;
}
.h500 {
height: 500px;
}
.white {
background-color: white;
}
.black {
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="logo">
</div>
<section id="white" class='h500 white'>
</section>
<section id="black" class='h500 black'>
</section>
<section id="white" class='h500 white'>
</section>
<section id="black" class='h500 black'>
</section>
You have to use classes and not id's because there must be only one item in the document having a same id, contrary to class.
About the script: the idea is to iterate over all the sections .white or .black and get the top and bottom for each one, which will allow you while handling scrolling event to verify if your logo is inside a given section (between the section's top and bottom positions)
Edit: I add this code (with pure javascript) to my comment.
const whites = [...document.querySelectorAll('.white')].map(e => ({
top: e.getBoundingClientRect().top,
bottom: e.getBoundingClientRect().bottom
}));
//If you have a logic of only white and black sections, you can omit blacks, else you can use them
// const blacks = [...document.querySelectorAll('.black')].map(e => ({top: e.top, bottom: e.bottom}));
const logo = document.querySelector('#logo');
document.addEventListener('scroll', () => {
let position = (logo.getBoundingClientRect().bottom + logo.getBoundingClientRect().top) / 2 + window.scrollY;
for (let i = 0; i < whites.length; i++) {
if (position >= whites[i].top && position <= whites[i].bottom) {
logo.classList.remove('whiteLogo');
logo.classList.add('blackLogo');
return;
}
}
logo.classList.remove('blackLogo');
logo.classList.add('whiteLogo');
});
*,
html,
body {
margin: 0;
padding: 0;
}
section {
height: 200px;
}
.black,
.blackLogo {
background: black;
}
.white,
.whiteLogo {
background: white;
}
#logo {
position: fixed;
top: 0;
left: 0;
height: 50px;
width: 50px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="logo" class="whiteLogo"></div>
<section class="black"></section>
<section class="white"></section>
<section class="black"></section>
<section class="black"></section>
<section class="white"></section>
<section class="black"></section>
</body>
</html>
DOM id's need to be unique, so your code will only recognize the first instance of each. You should find the last section you scrolled over, and find what class that has:
function myFunction() {
var position = $(this).scrollTop()
var class_pos = $('.white, .black').filter(function(){ return position >= $(this).position().top})
// console.log(class_pos)
if ($(class_pos[class_pos.length - 1]).hasClass('white')){
logoSwap(0);
} else {
logoSwap(1);
}
}

Animated image (e.g. non-GIF) with JavaScript and CSS?

I had been trying to animate a .png file with JavaScript while following this method. This is the .png file that I want to animate. I want the animated logo to be right by "Cupquake," but the logo doesn't even show up, let alone animate. However, changing "span class=logoCquake" in HTML to a div class displays the logo, but it is below the text.
My JavaScript file:
var scrollUp = (function () {
var timerId;
return function (height, times, element) {
var i = 0;
timerId = setInterval(function () {
if (i > times)
i = 0;
element.style.backgroundPosition = "0px -" + i * height + 'px';
i++;
}, 100);
};
})();
scrollUp(130, 30, document.getElementByClass('logoCquake'))
My HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="../css/normalize.css" />
<link rel="stylesheet" href="../css/style.css" />
<script src="../scripts/logoCquake.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cupquake - Home</title>
</head>
<body>
<div class="wrapper">
<div class="header">
<div class="topbar">
<div class="mCquake">
</div>
</div>
<br>
<br>
<br>
<span class="ninja">Ninja</span><span class="cupquake">Cupquake</span><span class="logoCquake"></span>
</div>
</div>
</body>
</html>
CSS file:
#font-face
{
font-family: typo_semib;
src: url('fonts/typo_semib.ttf');
}
#font-face
{
font-family: typo_light;
src: url('fonts/typo_light.ttf');
}
.wrapper .header
{
height: 250px;
width: 100%;
background: -webkit-gradient(linear,left top,left bottom,color-stop(0%,#ffa200), color-stop(100%,#d25400));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffa200',endColorstr='#d25400',GradientType=0);
background: -moz-linear-gradient(top,#ffa200,#d25400);
background-image: -o-linear-gradient(#ffa200,#d25400);
overflow: hidden;
}
.wrapper .header .topbar
{
height: 60px;
background-image: url(../imgz/head/hBarSBg.png);
background-repeat: repeat-x;
}
.wrapper .header .topbar .mCquake
{
height: 37px;
width: 278px;
background-image: url(../imgz/head/mCqRight.png);
background-repeat: no-repeat;
float: none;
float: right !important;
margin-right: 10px;
margin-top: 11.5px;
margin-bottom: 11.5px;
}
.wrapper .header .ninja
{
font-family: typo_semib;
font-size: 48px;
color: #303030;
margin-left: 55px;
}
.wrapper .header .cupquake
{
font-family: typo_light;
font-size: 48px;
color: #303030;
}
.wrapper .header .logoCquake
{
height: 112px;
width: 130px;
background-image: url(../imgz/logo/logoCquake.png);
background-repeat: no-repeat;
}
EDIT:
Tried again, but with the second method listed here, still nothing. These are my current HTML and JS codes:
JS:
function SpriteAnim (options) {
var timerId,
i = 0,
element = document.getElementByClass(options.elementClass);
element.style.width = options.width + "px";
element.style.height = options.height + "px";
element.style.backgroundRepeat = "no-repeat";
element.style.backgroundImage = "url(" + options.sprite + ")";
timerId = setInterval(function () {
if (i >= options.frames) {
i = 0;
}
element.style.backgroundPosition = "0px -" + i * options.height + "px";
i ++;
}, 100);
this.stopAnimation = function () {
clearInterval(timerId);
};
}
var cupcake = new SpriteAnim({
width: 130,
height: 112,
frames: 30,
sprite: "..\imgz\logo\logoCquake.png",
elementClass : "logoCquake"
});
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="../css/normalize.css" />
<link rel="stylesheet" href="../css/style.css" />
<script language="javascript" src="SpriteAnim.js">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cupquake - Home</title>
</head>
<body>
<div class="header">
<div class="topbar">
<div class="mCquake">
</div>
</div>
<span class="ninja">Ninja </span><span class="cupquake">Cupquake</span><span class="logoCquake"></span>
</div>
</div>
</body>
</html>
my code seems to work:
<!doctype html>
<style>
div{background:url(http://i1243.photobucket.com/albums/gg555/Nyanja/logoCquake.png);height:33px;width:39px}
</style>
<div id=anim></div>
<script>
var i=0;
setInterval(function(){i+=33.6;document.getElementById("anim").style.backgroundPosition="0px "+i+"px"},100)
</script>
I believe 'span' tag being an inline element it either needs a 'display: block' property or 'float: left', i tried your code and it worked for me after i added 'display: block' to the 'span' tag with class 'logoCquake'. Hope this helps you.
Note: if you use 'display: block' the span will move to new line and if you use 'float: left' the 'span' tag will move to the left of the text.

Categories

Resources