the keyword document is not defined - javascript

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.

Related

Javascript works in codepen but not on browser

const toggleButton = document.getElementsByClassName('navbar-toggle')[0];
const navbarLinks = document.getElementsByClassName('navbar-links');
toggleButton.addEventListener('click', function() {
for(var i=0; i<navbarLinks.length; i++)
navbarLinks[i].classList.toggle('active');
});
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-family: "Montserrat", sans serif;
}
.navbar ul {
display: flex;
width: 100%;
align-items: center;
background-color: none;
color: black;
}
.navbar li {
list-style-type: none;
padding: 1rem;
}
.navbar a {
text-decoration: none;
}
.navbar-logo {
margin-right: auto;
width: 250px;
height: 150px;
user-select: none;
}
.navbar-toggle {
display: none;
}
.navbar-links:hover {
color: rgba(245, 40, 145, 0.8);
transition: all 0.3s ease 0s;
}
button {
padding: 9px 25px;
color:white;
background-color: rgba(245, 40, 145, 0.8);
border: none;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease 0s;
}
button:hover {
background-color: rgba(245, 40, 145, 0.5);
}
#media (max-width: 600px) {
.navbar ul {
flex-wrap: wrap;
}
.navbar-toggle {
display: block;
cursor:pointer;
}
.navbar-links {
display: none;
width: 100%;
text-align: center;
}
.active {
display: block;
}
}
.slideshow {
max-width: auto;
height: 600px;
display: block;
position: relative;
overflow: hidden;
}
img.mySlides {
max-width: 100%;
max-height: 100%;
display: block;
object-fit: cover;
top: 0;
left: 0;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>KK Beauty Parlor </title>
<link rel="stylesheet" href="CSS/homestyle.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/3/w3.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/a37ae7cae6.js" crossorigin="anonymous"></script>
<script src="JS/myScript.js"></script>
</head>
<body>
<nav class="navbar">
<ul>
<img class="navbar-logo" src="images/KKLogo.svg">
<li class="navbar-toggle"><i class="fa-solid fa-bars"></i></li>
<li class="navbar-links">Home</li>
<li class="navbar-links">Products</li>
<li class="navbar-links">Services</li>
<li class="navbar-links">Appointments</li>
<li class="navbar-links">Learn More</li>
<li class="navbar-links"><button>Login</button></li>
<li class="navbar-links"><button>Register</button></li>
</ul>
</nav>
<section class="slideshow">
<img class="mySlides" src="images/slideshow1.jpg" style="width:100%">
<img class="mySlides" src="images/slideshow2.jpg" style="width:100%">
<img class="mySlides" src="images/slideshow3.jpg" style="width:100%">
<img class="mySlides" src="images/slideshow4.jpg" style="width:100%">
</section>
<script>
// Automatic Slideshow - change image every 3 seconds
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 3000);
}
</script>
</body>
</html>
In the snippet, the hamburger icon does what its supposed to do, however, when I try to run it locally on my browser the hamburger icon doesn't work at all. Has anyone ever had an issue with this? Not sure why it's happening or how to fix it. Any ideas/advice? I'm working inside of Visual Studio Code and have tried both Safari and Google Chrome as a browser. JavaScript is enabled in both.
Your JavaScript is loading before the HTML does, which means that the following code will be undefined, as it doesn't exist yet.
console.log(document.getElementsByClassName('navbar-toggle')[0]);
<!-- It's like there's nothing here for JavaScript! -->
To fix this, you can do two things.
You can add the JavaScript at the end of the <body> tag. This makes the JavaScript load after all of the HTML has, as HTML loads line by line.
<body>
<!-- Some HTML here... -->
<script src="JS/myScript.js"></script>
</body>
If you want to leave the JavaScript in the <head>, then you can add the defer attribute.
According to MDN...
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
So, you can simply change your code to below.
<head>
<!-- Some HTML here... -->
<script defer src="JS/myScript.js"></script>
</head>
Both of these will work, but it's up to you what you want to do.
I think it is happening because you're importing js file in the head tag. And that's why it is getting rendered before the HTML code does. And because of that the values of toggleButton and navbarLinks will be undefined.
So try moving your js import at the bottom after the body tag.
<body>...</body>
<script src="https://kit.fontawesome.com/a37ae7cae6.js" crossorigin="anonymous"></script>
<script src="JS/myScript.js"></script>
What is actually happening here...
First the page started loading.Then it found the js. it executes js when you are in head tag. but your elements are inside the body that isn't loaded yet. So the script found nothing.
const toggleButton = document.getElementsByClassName('navbar-toggle')[0];
const navbarLinks = document.getElementsByClassName('navbar-links');
Here:
toggleButton = undefined;
navbarLinks = undefined;
This means you don't have navbarLinks and toggleButton. Then it will never work.
To solve this you need to execute this javascript code after these elements.
It is better to use script tag just before the end of body tag or inside head tag using defer or async attribute.
In codepen or codeply this is automatically configured.
// Tips:
Why are you using ....
document.getElementsByClassName('navbar-toggle')[0]
Try this:
document.querySelector('.navbar-toggle')
Docs: https://www.w3schools.com/jsref/met_document_queryselector.asp
There are many ways to select an element.
document.getElementById()
document.getElementsByClassName()
document.getElementsByName()
document.getElementsByTagName()
document.querySelector()
document.querySelectorAll()
Here is an example.
<section class="parent-class" id="parent-id">
<div class="child">
</div>
<div class=child2>
</div>
</section>
If you want to select the child div using getElementById, then you can't do this normally because the div has no id.
getElementById finds just one element that contains all the id given here.
document.getElementById('a b c')
it will find an element that has a,b and c id.
Thinking using getElementsByClassName? Well you can do this, but if you want to select a div that is under a section then again you can't do this. It also works similar with id, it find an element with all the class names given here. there is also a big problem. this returns an array not a single element.
getElementsByName, getElementsByTagName are also similar, these find all elements with the tag given here. But querySelector querySelectorAll is a magic. It works similar with css.
document.querySelector('#parent-id .child'); // <div class='child'> document.querySelector('.parent-class .child'); // <div class='child'> document.querySelector('.child'); // <div class='child'> document.querySelector('.child2'); // <div class='child2'> document.querySelectorAll('#parent-id div'); // [div,div] document.querySelectorAll('.parent-class div'); // [div,div]
https://www.w3schools.com/jsref/met_document_getelementbyid.asp https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp https://www.w3schools.com/jsref/met_document_queryselector.asp https://www.w3schools.com/jsref/met_document_queryselectorall.asp

Why is this div height returning 0?

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.

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>

using a javascript file as a background in css

I am aware I can use background-image: url("www.linktoimage.com/image.png"), in css, to place an image in the background. I also know I can add a javascript file into html with tag. My challenge is how do I apply css characteristics of a background image to my javascript file?
To add some context, the javascript file is a simple animation (randomly bouncing balls, that responds to the screen width and height. I want to place text on top of this as if it was background, but no matter what I do, text will place itself above the script, in a white box, instead of directly on top of my script. Below is the general result of my various attempts:
I would like to place "Welcome" on top of my javascript, as oppose to how it currently appears on top of window with a white background. My css is as follows:
#font-face {
font-family:'HighTide';
src: url('assets/HighTide.otf')
font-family:'HighTideSans';
src: url('assets/HighTideSans.otf')
}
body {
padding: 0;
margin: 0;
}
canvas {
vertical-align: top;
z-index: -1
}
.title {
font-family:'HighTide';
font-size: 10vw;
margin: auto;
text-align: center;
z-index: 1;
}
.enter {
font-family:'HighTideSans';
font-size: 2vw;
text-align: center;
margin: auto;
z-index: 1;
}
And here is the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>LockeDesign</title>
<script src="libraries/p5.js" type="text/javascript"></script>
<script src="libraries/p5.dom.js" type="text/javascript"></script>
<script src="libraries/p5.sound.js" type="text/javascript"></script>
<script src="libraries/svg.js" type="text/javascript"></script>
<script src="main.js" type="text/javascript"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class=title> WELCOME </div>
<a href="main.html" class=enter> </a>
</body>
</html>
Any suggestions are appreciated, thank you!
EDIT
Using position: absolute; works partially, all I had to do was add left: 0;
right: 0; and bottom: 50%; to re-center the text. Resizing the window would cause scrollbars to appear, which was less than desirable, so I added overflow:hidden; to the body tag. Now this works exactly as intended, thanks all!
I would suggest WRAPPING all of the content you wish to display over the dynamic background in a single div
Example
<html>
<body>
<div id="BodyWrapper">
<h1> This is an HTML Page </h1>
</div><!-- End BodyWrapper -->
</body>
</html>
Then apply some Z positioning to the BodyWrapper with css
#BodyWrapper{position:absolute; top:0; left:0; width:100%; height:100%; z-index:5;}
If the above is still not enough then you may have to delay the
showing of the body content (make sure the dynamic background
completely loads first).
You can set the initial display styling of the wrapper to
#BodyWrapper{position:absolute; top:0; left:0; width:100%; height:100%; z-index:1; display:none;}
and onLoad... call this function
function show_PageBody()
{
setTimeout(function(){ update_Wrapper(); },1000);
function update_Wrapper()
{
document.getElementById('BodyWrapper').style.display='block';
document.getElementById('BodyWrapper').style.zIndex = 5;
}
}
You can add a css transition for the opacity of the BodyWrapper so that it fades onto the screen instead of just appearing.
This should work (has worked for me in the pass).
If not please let me know.
Using position: absolute; works partially, and renders this result:
All I had to do was add left: 0; right: 0; and bottom: 50%; to re-center the text. Also, resizing the window would cause scrollbars to appear, which was less than desirable, so I added overflow:hidden; to the body tag. Now this works exactly as intended:

html css and js not working

This is my code:
<!doctype html>
<html lang="en-US">
<head>
<title>Welcome - Home</title>
<link type="text/css" rel="stylesheet" href="Home.css">
<link rel="icon" href="KLOGO.png" type="image/png"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="Home.js"></script>
</head>
<body class="menu">
<header>
Toggle
<nav class="menu-side">
This is a side menu
</nav>
</header>
<p> sioeufh iufha dgrkljbgril unfvuabervluiyboyubn serlibglisuhsefiuh oaisuf aieufh aosih asioeufh iufha dgrkljbgril unfvuabervluiyboyubn serlibglisu</p>
<p>oierua yugafapiwugText and more tejiaslirfuh aiufh oaiuefhioaushf aisbhfailsubfaufha dgrkljbgril unfvuabervluiyboyubn serlibglisuh oaiusg foiygasdefoiawg pghuioyf gaiwuebfyaweoilru gfa s7ierfygasrgoooa8iweygfra iiiastygf a8we8</p>
</body>
</html>
The css:
.menu-side{
background: #333;
border-right: 1px solid #000;
color: #fff;
position: fixed;
top: 0;
left: -231px;
width: 210px;
height: 100%;
padding: 10px;
}
.menu{
overflow-x:hidden;
position: relative;
left: 0px;
}
.menu-open {
left: 231px;
}
And the jquery:
(function () {
var body = $('body');
$('.menu-toggle').bind('click', function () {
body.toggleClass('menu-open');
return false;
});
})();
I'm using the Brackets program to write my code, but when I go to the live view after I saved everything and i press "toggle" the page wont move and I looked over everything and Im 98% sure its correct.
Put <script src="Home.js"></script> before the </body> tag.
I made another class
.menu-side-open{
left:0px;
}
and JQuery
(function () {
var body = $('body');
$('.menu-toggle').bind('click', function () {
body.toggleClass('menu-open');
$('.menu-side').toggleClass('menu-side-open');
return false;
});
})();
Also added
.menu, .menu-side{
transition: 300ms;
}
for a nice slide :)
JSFiddle demo
You need to include jQuery if you want to use it.
Add this line
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
In your html's head or before you use jQuery!
e.g.
<head>
<title>Welcome - Home</title>
<link type="text/css" rel="stylesheet" href="Home.css">
<link rel="icon" href="KLOGO.png" type="image/png"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="Home.js"></script>
Change this:
body.toggleClass('menu-open');
to this:
$('.menu-side').toggleClass('menu-open');
And change the .menu-open css class to this:
.menu-open {
top:10%;
left: 0px;
}
Here is the JSFiddle demo
Its the .menu-side that is hidden on the left. Therefore you should be applying the menu-open class to .menu-side and not the body tag.
Your CSS was setting the left of .menu-side to 231px, setting it back to 0px is enough to make the menu appear back into view. And when the menu appeared, it covered the 'Toggle' link, therefore I also added top:10% to the .menu-open class CSS.
I think it is related to a missing file from the computer. I have the same issue with my computer and it does not really matter wether you put the CSS and JS into the HTML page. The result will be the same. When you open the page in the browser, you won`t see any changes, and if I press F12 it says: Failed to load resource: net::ERR_FILE_NOT_FOUND or dll file not found or something like that

Categories