Why is this div height returning 0? - javascript

I am completely stuck on this one. I'm trying to get the height of a div, but it's constantly returning 0, despite trying numerous ways to resolve the problem. Here's the code.
document.addEventListener("DOMContentLoaded", function() {
const topDrawer = document.querySelector('.drawer__container--top');
console.log(topDrawer.offsetHeight)
})
.drawer {
&__container {
width: 100%;
position: absolute;
width: 90%;
background: white;
height: 500px;
// left: 50%;
transition: all .3s ease-in-out;
border-radius: 1rem;
box-shadow: 0px 3px 15px rgba(0,0,0,0.2);
z-index: 3;
&--top {
top: 0;
// transform: translateY(-400px) translateX(-50%);
}
&--bottom {
bottom: 0;
transform: translateY(60vh) translateX(-50%);
padding: 1rem 2rem;
&.open {
transform: translateY(8vh) translateX(-50%);
}
}
}
<script type="module" src="https://unpkg.com/#ionic/core#latest/dist/ionic/ionic.esm.js"></script>
<script nomodule="" src="https://unpkg.com/#ionic/core#latest/dist/ionic/ionic.js"></script>
<link href="https://unpkg.com/#ionic/core#latest/css/ionic.bundle.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Actor&display=swap" rel="stylesheet" />
<!-- This is the main body - every thing will go in here! -->
<div class="main">
<div class="jp__header">
<div class="jp__header__textrel">
<div class="jp__header__textabs">
<h1>Journey Planner</h1>
</div>
<div class="jp__header__weatherabs">
<canvas id="icon2"></canvas>
</div>
<div class="jp__header__underline"></div>
</div>
</div>
<div class="drawer drawer__container drawer__container--top">
</div>
<div id="map"></div>
<div class="drawer__container drawer__container--bottom">
<div class="drawer__search__wrapper">
<ion-toolbar class="drawer__search__toolbar" no-shadow="">
<ion-searchbar animated="" class="drawer__search__searchbar" mode="ios"
placeholder="Enter a bus stop number..."></ion-searchbar>
</ion-toolbar>
</div>
</div>
</div>
I've tried
- wrapping this in windo.addEventListener("load", () etc)
as well as using this 'ready' function:
function ready(callback){
// in case the document is already rendered
if (document.readyState!='loading') callback();
// modern browsers
else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);
// IE <= 8
else document.attachEvent('onreadystatechange', function(){
if (document.readyState=='complete') callback();
});
}
using document.addEventListener("DOMContentLoaded")
Also there are no floats anywhere but I have tried adding overflow: hidden.
I'm packaging with webpack, but the bundle is being put just before the closing body tag. I see no reason why a height of 500px isn't being returned...hope you can help.
EDIT: I'm using Django and templates too - could that be affecting it?
SECOND EDIT:
There seems to be a tiny delay in the styles being applied, as detected by #Thomas below. Applying a set timeout seems to get things working so I'm going to go with that... pretty baffling.

Foudn the answer to this: Many thanks to #Tibrogargan, #Thomas and #Diego for helping identify it.
The issue was the ionic import:
<link href="https://unpkg.com/#ionic/core#latest/css/ionic.bundle.css" rel="stylesheet" />
The scripts are not loading in until that css file has been sourced. I've solved it by adding a setTimeout of 2ms to the document load handler, but am also going to look into how to either source the css locally or find another solution.

Related

the keyword document is not defined

tried to read and learn some code from github
so I copied below link and tried to run it on my intellij
https://github.com/bradtraversy/50projects50days/tree/master/background-slider
but when I run the code it said "Document is not defined" which refers to the keyword* "document.getElementById"* )
I googled it and it said I am running the code in a server side application like node.js
but I feel like I am not on the server side since I got the html, js(not node js ) and css files in the same folder and they are copied straight from the GitHub and to my sheet.
but when I run some test code as below on my script.js
if (typeof window === "object") {
// code is running in a browser environment
} else {
// code is running in a non-browser environment
}
it said I am running in a non-browser environment
what is wrong with my environment setting ???
am I missing some plugin?
and should I use a library or framework that provides a document-like object in a non-browser environment? if so, any recommendations?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"
integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog=="
crossorigin="anonymous"
/>
<link rel="stylesheet" href="style.css" />
<title>Background Slider</title>
</head>
<body>
<div class="slider-container">
<div
class="slide active"
style="
background-image: url('https://images.unsplash.com/photo-1549880338-65ddcdfd017b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2100&q=80');
"
></div>
<div
class="slide"
style="
background-image: url('https://images.unsplash.com/photo-1511593358241-7eea1f3c84e5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1934&q=80');
"
></div>
<div
class="slide"
style="
background-image: url('https://images.unsplash.com/photo-1495467033336-2effd8753d51?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2100&q=80');
"
></div>
<div
class="slide"
style="
background-image: url('https://images.unsplash.com/photo-1522735338363-cc7313be0ae0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80');
"
></div>
<div
class="slide"
style="
background-image: url('https://images.unsplash.com/photo-1559087867-ce4c91325525?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2100&q=80');
"
></div>
<button class="arrow left-arrow" id="left">
<i class="fas fa-arrow-left"></i>
</button>
<button class="arrow right-arrow" id="right">
<i class="fas fa-arrow-right"></i>
</button>
</div>
<script src="hello.js"></script>
</body>
</html>
Your html has the line <script src="hello.js"></script> which means it is going to include your Javascript code. So basically you shouldn't run your Javascript script directly (with node) but you should open your html file in a browser and the browser is going to execute your Javascript.
The same applies to your css actually. Since you have the line <link rel="stylesheet" href="style.css" />, the browser will include the CSS when you open the HTML page, but you can't run the CSS on its own. It doesn't make sense without an HTML page to apply it to.
In your Javascript, whenever you want to call a method (for example getElementById()) or an attribute of the document object, there needs to be a web page (= an HTML document) that your Javascript can access. And one way to do it is to execute your Javascript code within the <script> tag of your html document.
Hope this makes sense.
How to make the project work
Put the 3 files in the same folder.
Open a browser, e.g. Google Chrome
Throw the .html file into the browser window.
How to edit the files
I am not sure why you are using InteliJ: I am not familiar with using this for Javascript/HTML. Probably it will work for editing, but let me suggest trying VS Code which is free and widely used for the HTML/JS/CSS combination. To edit the files in that:
Install Visual Studio Code and open it.
Drag the containing folder of the 3 files, into the VS Code window.
The 3 files will be listed in the left panel: click on any of them to edit in VS Code, and press Control-S to save.
Once you have saved an update, go to the browser window and press F5.
To view the "output" of the program, I personally always use a browser, e.g. Google Chrome, rather than any command line tool. These projects should always work, and work simply and easily, in a browser. Whether they work in a command line tool depends on the tool, and what it is set up to do. Some tools will open a browser window for you. But why not just open the window yourself and that way it is easier to understand what is happening.
Once you have the editing process working in VS Code, feel free to try editing in IntelliJ. I am assuming that will also work. However, I am guessing that you are being confused by any buttons in IntelliJ for "running" the code. They are intended to run programs that are not the "child" of a web page, but rather are called directly. For Javascript, typically such programs are in Node JS. However the code you present is not intended to be run in Node JS environment.
How to make the project work here in Stack Overflow
In a simple .html/.js/.css project like this, you can often make it work here just within Stack Overflow. This is not the best way to edit a program in general, but makes it easy for people to reproduce your problem and help you.
To do that, while typing your question, click the small "<>" icon above the text entry box. That opens a window with 4 panels. Into the corresponding 3 panels, paste in your HTML, JS and CSS code. Then click the big blue button to "Run" the code.
That will give you this:
const body = document.body
const slides = document.querySelectorAll('.slide')
const leftBtn = document.getElementById('left')
const rightBtn = document.getElementById('right')
let activeSlide = 0
rightBtn.addEventListener('click', () => {
activeSlide++
if (activeSlide > slides.length - 1) {
activeSlide = 0
}
setBgToBody()
setActiveSlide()
})
leftBtn.addEventListener('click', () => {
activeSlide--
if (activeSlide < 0) {
activeSlide = slides.length - 1
}
setBgToBody()
setActiveSlide()
})
setBgToBody()
function setBgToBody() {
body.style.backgroundImage = slides[activeSlide].style.backgroundImage
}
function setActiveSlide() {
slides.forEach((slide) => slide.classList.remove('active'))
slides[activeSlide].classList.add('active')
}
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#400;700&display=swap');
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
overflow: hidden;
margin: 0;
background-position: center center;
background-size: cover;
transition: 0.4s;
}
body::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100vh;
background-color: rgba(0, 0, 0, 0.7);
z-index: -1;
}
.slider-container {
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
height: 70vh;
width: 70vw;
position: relative;
overflow: hidden;
}
.slide {
opacity: 0;
height: 100vh;
width: 100vw;
background-position: center center;
background-size: cover;
position: absolute;
top: -15vh;
left: -15vw;
transition: 0.4s ease;
z-index: 1;
}
.slide.active {
opacity: 1;
}
.arrow {
position: fixed;
background-color: transparent;
color: #fff;
padding: 20px;
font-size: 30px;
border: 2px solid orange;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}
.arrow:focus {
outline: 0;
}
.left-arrow {
left: calc(15vw - 65px);
}
.right-arrow {
right: calc(15vw - 65px);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />
<link rel="stylesheet" href="style.css" />
<title>Background Slider</title>
</head>
<body>
<div class="slider-container">
<div class="slide active" style="
background-image: url('https://images.unsplash.com/photo-1549880338-65ddcdfd017b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2100&q=80');
"></div>
<div class="slide" style="
background-image: url('https://images.unsplash.com/photo-1511593358241-7eea1f3c84e5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1934&q=80');
"></div>
<div class="slide" style="
background-image: url('https://images.unsplash.com/photo-1495467033336-2effd8753d51?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2100&q=80');
"></div>
<div class="slide" style="
background-image: url('https://images.unsplash.com/photo-1522735338363-cc7313be0ae0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2689&q=80');
"></div>
<div class="slide" style="
background-image: url('https://images.unsplash.com/photo-1559087867-ce4c91325525?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2100&q=80');
"></div>
<button class="arrow left-arrow" id="left">
<i class="fas fa-arrow-left"></i>
</button>
<button class="arrow right-arrow" id="right">
<i class="fas fa-arrow-right"></i>
</button>
</div>
<script src="script.js"></script>
</body>
</html>
In the code above, which I have copied and pasted directly from the Brad Traversy github, there are two statements in the .html file that are needed for normal browser use, but are not needed in the Stack Overflow emulator.
<link rel="stylesheet" href="style.css" />
and
<script src="script.js"></script>
These statements tell the browser that is reading the .html file where to look for the .css and .js files.
When you are running it in the Stack Overflow snippet editor, that snippet editor automatically secretly inserts equivalent statements into your HTML, so that the 3 panels are linked together, without you specifically giving the 3 panels actual filenames. So when pasting into Stack Overflow's snippet editor, you don't need those statements. If you leave those statements in, the browser fails to find the files you explicitly pasted in (because you have not given them explicit names) but does find them through the secret automatic process of linking the CSS and JS to the parent HTML, so it still works.

HTML - How can I hide a loading div when a new tab loads?

I have a button, when you click it shows a loading div and opens a new tab which loads an html. I want to hide this div when the html in the new tab loads. I've tried so many things to hide this but no one works, can I have some help? I'm new on html, javascript, ajax, jquery development.
<!DOCTYPE html>
<html>
<style>
.loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
}
#keyframes spin {
0% { transform: rotate(0deg); }
00% { transform: rotate(360deg); }
}
#white-background{
display: none;
width: 100%;
height: 100%;
position: fixed;
top: 0px;
left: 0px;
background-color: #fefefe;
opacity: 0.7;
z-index: 9999;
}
#dlgbox{
/*initially dialog box is hidden*/
display: none;
position: fixed;
width: 480px;
z-index: 9999;
border-radius: 10px;
}
</style>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#show").click(function(){
$("div").show();
var win = window.open("new2.html");
});
});
</script>
</head>
<body>
<button id="show">Show</button>
<center>
<div id="loadingImage" style="display:none;">
<div id="white-background"></div>
<center>
<div id="dlgbox">
<div class="loader"></div>
<h1>Loading...</h1>
</center>
</div>
</div>
</center>
</body>
</html>
You can not remove the loading if cause your browser IS in loading state. So you might ask google or mozilla to remove it ;) It just is shown cause your new window CAN NOT LOAD THE PAGE.To open a window is like open a new browser. Without "http://whatever" it will show a error 404 or in some case this "logo". So if you use a full qualified URL nothing is shown. Your code has some more issues.
1.) jquery is depriated and overkill
2.) do not use such libs untilyou has understand javascript at its base !
3.) you should use chrome as developement browser - with F12 it opens a nice IDE which can clean up also your messy HTML code ;) Ther was some divs not correctly nested. Will mix up javascript and css.
<!DOCTYPE html>
<html>
<style>
.loader {
border: 16px solid #f3f3f3;
/* Light grey */
border-top: 16px solid #3498db;
/* Blue */
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
}
#keyframes spin {
0% {
transform: rotate(0deg);
}
00% {
transform: rotate(360deg);
}
}
#white-background {
display: none;
width: 100%;
height: 100%;
position: fixed;
top: 0px;
left: 0px;
background-color: #fefefe;
opacity: 0.7;
z-index: 9999;
}
#dlgbox {
/*initially dialog box is hidden*/
display: none;
position: fixed;
width: 480px;
z-index: 9999;
border-radius: 10px;
}
</style>
<head></head>
<body>
<button id="show" onclick="javascript:winopen('new2.html');">Show</button>
<div id="progress" style="display:none;">
<div id="white-background">
<center>
<div id="dlgbox">
<div class="loader"></div>
<h1>Loading...</h1>
</div>
</center>
</div>
</div>
<script>
//if you load or put scripts at the end the DOM (direct before </body>) the
//page html is already loaded so no need
// for onload tricks The page is already ready here.
var win;
var progress;
var baseurl = ""
baseurl = window.location.href;//current page location
//current url
url = baseurl.split("/");
//remove current filname by split to array
url.pop();
//remove last array element
baseurl = url.join("/");
// join rest of array
console.log(baseurl);
function winopen(page) {
progress = document.getElementById("progress");// get the div by its id
//i have put the file in the same directory. i gues you has to change "/" to "/YOUR_SUBDIRECTORY e.g. /test//"
var href = baseurl + "/" + page; //create new url for the window open thing
progress.style.display = "block";// show the progress info
win = (window.open(href)); // open the window
progress.style.display = "none;"; // it's loaded hide the progress info
}
//bonus trick:
function content_manager(showme_id,hideme_id) {
document.getElementById(hideme_id).style.display="none";
document.getElementById(showme_id).style.display="block";
}
</script>
</body>
</html>
You own me a beer ;) BTW: you might not see you loading stage. Its too fast to see. Comment out the hide part or use the chrome debugger to se whats going on :)
To center things : center a info box you might also read about the z-index css property. You can hide the whole page by a div with is width 100% height 100% , has a frixed position and has a z-index: 2; so you put your loading info over the page and hide the page completely. You might use as background-color: rgba(1,1,1,.5) to make it half transparent ;)
If you are on same domain then try with localStorage:
Add this script:
<script>
localStorage.setItem("ispageloaded",false);
function load(){
var func=setTimeout(function(){
if(localStorage.getItem("ispageloaded")){
clearTimeout(func);
//Then hide loading div here...
}else{
load();
}
},2000);
}
load();
window.open("nav2.html","_blank");
</script>
Add this script to nav2.html:
<script>
localStorage.setItem("ispageloaded",true);
</script>
Hope you are understood this script...
If you are using ajax code to populate that content, you can hide that div with a single line code.

Animation (toggle class possibly) not working

So I'm making a website where I have several divs that should slide either from right, left, or top when user clicks on specific button or nav items. However, none of those are working. None of the divs will slide over when I click on the button that are supposed to make them slide. I'm using pure javascript to perform those actions. So far, I've tried several actions. First, I thought it was because I didn't have window.onload, but after adding it, nothing changed. Then I though maybe the links were still carrying the default actions, so I tried to add e.preventDefault in hopes that was the problem, it also didn't work. Then I found out something weird that made think maybe it is my computer that is not interpreting javascript correctly(weird thought, I know. But I was just considering anything since I was running out of solutions).But actually, it turns out that my computer or the editor is not reading "document" or window in javascript. It says both of them are not defined, which is weird since I have linked the javascript file correctly at the end of the body. So I decided to run it on JSFiddle to check whether it was really just my computer. However, even in JSFiddle the divs still won't slide when I click the button to make them slide.
I'm out of ideas. Since the project I'm doing is big, I extracted the part of divs that are not sliding to make things easier. The div you guys will see, is supposed to slide from the left when we click on the same div.
Here is the html code:
<!DOCTYPE>
<html>
<head>
<title>Emanuel Inacio</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css? family=Roboto+Condensed:100,300,400" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="home-page">
<div id="nav-bar"></div>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Here is the css code:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Roboto Condesed', 'San-serif';
}
#nav-bar {
width: 50%;
height: 100vh;
background-color: #000000;
transform: translateX(-50%);
transition: transform 0.5s;
}
.active {
transform: translateX(50%);
}
Finally, this is the javascript part:
var nav = document.getElementById("nav-bar");
window.onload = function () {
nav.addEventListener("click", function () {
nav.classList.toggle("active");
});
}
Every other div that is not working has pretty much the same code base as this one. Hence I decided to post only this div. Thanks in advance!
It's a specificity issue, ID is more specific than class so your style will never be applied. You need to adjust CSS like this:
var nav = document.getElementById("nav-bar");
window.onload = function() {
nav.addEventListener("click", function() {
nav.classList.toggle("active");
});
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Roboto Condesed', 'San-serif';
}
#nav-bar {
width: 50%;
height: 100vh;
background-color: #000000;
transform: translateX(-50%);
transition: transform 0.5s;
}
#nav-bar.active {
transform: translateX(50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="home-page">
<div id="nav-bar"></div>
</div>

Make perfect scrollbar visible by default

I am using perfect scrollbar for custom scroll bar. It is working fine.
But the scrollbar is visible only when you mouse over on the container.
How do I make this visible all the time?
$('.container').perfectScrollbar();
Demo
From the perfectscrollbar wiki:
How can I make the scrollbars always visible?
The reason why it's hidden by default is that opacity: 0 is used.
Please change all references of it to opacity: 0.6. If using .scss,
modify the line #include opacity(0) to #include opacity(0.6) in the
scrollbar-rail-default mixin and run gulp build to build .css and
.min.css files.
If you're not willing to modify the CSS files but would like to make
it always visible, please add following lines anywhere after
perfect-scrollbar.css is loaded.
.ps-container > .ps-scrollbar-x-rail,
.ps-container > .ps-scrollbar-y-rail { opacity: 0.6; }
Also, an example code may be helpful to see how to achieve it.
Here is example https://github.com/noraesae/perfect-scrollbar/blob/master/examples/always-visible.html
So, if you modify your JSFiddle by pasting the following into your html, it works.
<div class="container">
<div class="content"></div>
</div>
<style>
.ps-container > .ps-scrollbar-x-rail,
.ps-container > .ps-scrollbar-y-rail { opacity: 0.6; }
</style>
In addition you have to make sure perfect-scrollbar is updated at the right time. If the content is loaded dynamically, call ps.update().
Warning, make sure the the call is made after your data is loaded, on VueJS I had to do it in the 'nextTick' function :
this.$nextTick(() => {
ps.update();
});
},
I guess a timeout may works too.
.ps__rail-x,
.ps__rail-y {
opacity: 0.6;
}
This worked for me.
Try this. This will work even if the container class doesn't exist in you application
.ps> .ps__scrollbar-x-rail, .ps> .ps__scrollbar-y-rail{
opacity: 0.6;
}
I'm using ngx-perfect-scrollbar in Angular 8 and fixed problem by adding the following styles
.ps > .ps__rail-x,
.ps > .ps__rail-y {
opacity: 0.6;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>perfect-scrollbar example</title>
<link href="../dist/css/perfect-scrollbar.css" rel="stylesheet">
<script src="../dist/js/perfect-scrollbar.js"></script>
<style>
h1 { text-align: center; }
.container { position:relative; margin:0px auto; padding:0px; width: 600px; height: 400px; overflow: auto; }
.container .content { background-color: red; width: 1280px; height: 720px; }
</style>
<style>
/* to make scrollbars always visible */
.always-visible.ps-container > .ps-scrollbar-x-rail,
.always-visible.ps-container > .ps-scrollbar-y-rail {
opacity: 0.6;
}
</style>
</head>
<body>
<h1>Default</h1>
<div class="container">
<div class="content">
</div>
</div>
<h1>Always visible</h1>
<div class="container always-visible">
<div class="content">
</div>
</div>
<script>
window.onload = function () {
[].forEach.call(document.querySelectorAll('.container'), function (el) {
Ps.initialize(el);
});
};
</script>
</body>
</html>
I had the same issue. Make sure you are rendering the content first and after that you are creating the scrollbars. No CSS changes are needed. I'm using perfect-scrollbar.jquery.js

Fix navbar to top of page when scrolling

I'm trying to make a navbar similar to the one on Linus Tech tips (https://linustechtips.com/main/) for a school assignment. I'm at the real basic level of Javascript and I cooked up a pinnable navbar but when I made it there was no banner above it. Now there is a banner above it and I don't know how to make the navbar push to the top when I start scrolling.
Here is my HTML:
<div class="navContainer">
<div class="topBanner">
<img src="images/topbanner.png" id="topBannerimg"/>
</div>
<div id="navbar">
<button onclick="pinfunc()"><i id="pin" class="fa fa-thumb-tack fa-2x navButton" id="pinbtn" aria-hidden="true"></i></button>
</div>
</div>
Here is my Javascript:
var pinned = 1;
console.log(pinned);
function pinfunc() {
if (pinned == 1) {
document.getElementById("navbar").style.position= "relative";
document.getElementById("pin").style.color = "black";
document.getElementById("pin").style.transform = "rotate(0deg)";
pinned=0;
}
else if (pinned == 0) {
document.getElementById("navbar").style.position="fixed";
document.getElementById("pin").style.color = "red";
document.getElementById("pin").style.transform = "rotate(270deg)";
pinned=1;
}
}
And here is my CSS:
body{
margin: 0 auto;
}
.navContainer{
width: 100%;
margin: 0 auto;
}
#topBannerimg{
width: 100%;
margin: 0;
display:block
}
.navButton{
height: 25px;
width: 25px;
}
.fa-thumb-tack{
font-size: 50px;
color: red;
transform: rotate(270deg);
}
.container{
height: 1000px;
width: 90%;
margin: 0 auto;
}
#navbar{
height: 50px;
width: 100%;
position: fixed;
margin: 0 auto;
background-color: #D35300;
}
#nav{
background-color: #D35300;
height: 50px;
}
I'm just looking to create a basic one of the LTT forum - no need for the toggle button to fade out or anything.
This is my first post so I'm not 100% sure how to do stuff.
Thanks in advance.
If you are allowed to use external JS or CSS libraries, then try the Affix plugin for bootstrap. (link: http://www.w3schools.com/bootstrap/bootstrap_affix.asp). It makes what you are trying to accomplish simple.
If you are not allowed to use any external libraries then, I suggest you read this: http://getbootstrap.com/javascript/#affix-examples and try to implement it yourself.
Good Luck!
So I got it working with the following HTML, JS, and CSS files:
HTML
<html>
<head>
<link rel="stylesheet" href="path/to/font-awesome.css/file" type="text/css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<!-- Custom CSS File Below -->
<link href="/path/to/custom/css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="topBanner">
<img src="images/topbanner.png" id="topBannerimg"/>
</div>
<div id="navbar" data-spy="affix" data-offset-top="100">
<button onclick="pinfunc()"><i id="pin" class="fa fa-thumb-tack fa-2x navButton" aria-hidden="true"></i></button>
</div>
<div id="SpaceFiller"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="path/to/custom/js/file"></script>
</body>
</html>
The key things to learn from this HTML are the loading the JS files at the bottom of the body tag so the page can load first, and the order in which the CSS and JS files are loaded. The SpacFiller div is just there to enable scrolling. Also, note that I removed your navbar-container as it didn't seem necessary.
Javascript
var pinned = true;
function pinfunc() {
var $pin = $("#pin");
var $navbar = $("#navbar");
if (pinned) {
$pin.css({
'color': 'black',
'transform': 'rotate(0deg)'
});
console.log("not pinned")
$(window).off('.affix');
$navbar.removeClass('affix affix-top affix-bottom');
$navbar.removeData("bs.affix");
pinned = false;
} else {
$pin.css({
'color': 'red',
'transform': 'rotate(270deg)'
});
$(window).on('.affix');
$navbar.addClass('affix');
$navbar.affix({
offset: 100
});
pinned= true;
}
}
This JS uses jQuery Selectors (which actually uses sizzle.js I believe) to get access to HTML elements via their IDs. Using the returned jQuery object, the function sets the appropriate CSS and then toggles affix using functions you can read about here: http://getbootstrap.com/javascript/#affix, https://api.jquery.com/removeclass/, https://api.jquery.com/jQuery.removeData/, http://api.jquery.com/off/. Also, you were using 0 and 1 for the pinned values but it is good practice to use boolean values (true and false) as shown.
CSS
body{
margin: 0 auto;
}
.affix {
top: 0;
width: 100%;
}
.affix + .container-fluid {
padding-top: 70px;
}
#topBannerimg{
width: 100%;
margin: 0;
display:block;
height: 100px;
top: 0px;
}
.navButton{
height: 25px;
width: 25px;
}
.fa-thumb-tack{
font-size: 50px;
color: red;
transform: rotate(270deg);
}
#navbar{
height: 50px;
width: 100%;
margin: 0 auto;
background-color: #D35300;
}
#SpaceFiller {
height: 10000px;
background-color: darkgreen;
}
I think the CSS is self-explanatory, but if it is unclear go ahead and ask for clarification. Hope this helps! :D
Edit: You can also put the onclick attribute on the i tag itself and get rid of the button wrapper if you want to get rid of the white button background.

Categories