I'm trying to change the property of a div from a javascript file but it's not working, it's working if I put it inside body but I want to work it from external js file for some project.
HTML file
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Calendar</title>
<link rel="stylesheet" href="css/styles.css">
<script src="javascript/cal.js"></script>
</head>
<body>
<div id="container">
<div id="calendar-view">
</div>
<div id="events-view">
</div>
</div>
</body>
</html>
CSS file
*{
box-sizing: border-box;
}
#calendar-view{
float: left;
width: 70%;
background-color: blue;
height: 200px;
}
#events-view{
float: left;
width: 30%;
height: 200px;
background-color: red;
}
#container::after{
content: "";
clear: both;
display: table;
}
Javascript file
function startUp(){
document.getElementById("calendar-view").style.display = "none";
}
startUp();
I'm trying to change the property of a div from a javascript file but it's not working, it's working if I put it inside body but I want to work it from external js file for some project.
When you import your JS file at <header> your JS loads and then your body.
When you import your JS file after <body> your body loads and then your JS.
The first solution is to put your JS file after the second one is to put the function call inside the window onload event listener
you have to put the <script src="javascript/cal.js"></script> at the end of the </body> tag.
You cannot get element from the DOM before the browser get it through the HTML.
Related
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.
so i have a simple html file which consists of a div; and a css file which has a simple styling for the mentioned div:
html :
<html>
<head>
<title>Simple Movement</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="index.js"></script>
</head>
<body>
<div id="square"></div>
</body>
</html>
css:
body {
margin: 0;
}
#square {
width: 100px;
height: 100px;
border: 1px solid #095057;
background-color: #20979e;
position: absolute;
left: 200px;
top: 200px;
}
in my js file i do a simple log as follows:
console.log(document.getElementById('square').style.top)
but i receive an error:
Uncaught TypeError: Cannot read properties of null (reading 'style')
at index.js:1
i have no idea why it says style is null.do you?
i have no idea why it says style is null.do you?
It doesnt.
It says document.getElementById('square') returns null so youre reading the property style on null which results in the error.
That happens because your script is loaded (and executed) in the head. At this point the element with the ID "square" isnt existent in the DOM yet.
Move your script to below your element (see snippet) or mark it with async defer like this: <script src="index.js" async defer></script> to make it load and execute after DOM parsing is done.
Also accessing style will only show inline styles from the style attribute so that wont get you values from your stylesheet file (or inline stylesheets).
Use computedStyleMap() (see https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap) to get the actual computed styles including all stylesheets.
body {
margin: 0;
}
#square {
width: 100px;
height: 100px;
border: 1px solid #095057;
background-color: #20979e;
position: absolute;
left: 200px;
top: 200px;
}
<html>
<head>
<title>Simple Movement</title>
<meta charset="UTF-8">
</head>
<body>
<div id="square"></div>
<script>
console.log(document.getElementById('square').computedStyleMap().get('top').value);
</script>
</body>
</html>
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
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
I have the following HTML file that currently has nothing in it except some div class objects that are specified by CSS styles. If I open this web page and inspect the elements in Chrome they are the sizes that I want them to be. What I am wondering is if I can access those sizes via javascript.
HTML File:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>TEST</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
.camp_cont {
float: left;
width: 45%;
height: 50%;
position: relative;
}
.camp_cont_select {
float: left;
width: 45%;
height: 50%;
position: relative;
fill: #800;
}
.sub_camp_cont {
float: left;
width: 15%;
height: 50%;
position: relative;
margin: 10px 25px;
fill: #800;
}
</style>
</head>
<body>
<div class="camp_cont", id="cpa_perf"></div>
<div class="camp_cont", id="ctr_perf"></div>
<div class="sub_camp_cont", id="as_perf"></div>
<div class="sub_camp_cont", id="f_perf"></div>
<div class="sub_camp_cont", id="rh_perf"></div>
<div class="sub_camp_cont", id="rm_perf"></div>
<div class="sub_camp_cont", id="rl_perf"></div>
<div class="sub_camp_cont", id="ul_perf"></div>
<div class="sub_camp_cont", id="rt_perf"></div>
</body>
</html>
I am wondering if I can do something like the following:
x = $("#cpa_perf").width()
Again, when I inspect cpa_perf in Chrome it says its width is 515px. That's what I'm trying to get at
jQuery Width works just fine for this:
x = $("#cpa_perf").width();
alert(x);
JS Fiddle: http://jsfiddle.net/9abcf9d3/
You can use jQuery pretty easily to modify attributes of elements..
$('.classname').css(property, value);
I'm not certain if you are trying to use jQuery or pure javascript.
You're original attempt to get the width of the element should work as long as you're using a jQuery library.
Otherwise, if you just want the width of the element with pure javascript, you can use something like this:
var x = document.getElementById('cpa_perf').offsetWidth;
If you are including a jQuery library then the following should work:
var x = $("#cpa_perf").width()
Additional Note: Make sure that the script isn't called before the DOM element is written to the page as well. For example:
$(document).ready(function (){
var x = $("#cpa_perf").width();
console.log(x);
}) ;