Why am I getting a cannot read property message in my console when I try to use children property and offsetWidth? - javascript

I am new to coding and programming and I have been following, on Youtube, a screen recording of a programmer making a responsive thumbnail slider using HTML, CSS, and Javascript. I've gotten to a point where I am trying to check if my Javascript was logged into the console, but I continue to get this error message: "script.js:3 Uncaught TypeError: Cannot read property 'children' of null at script.js:3" Commenting line 3 solves the problem but then the same error shows for line 4: "script.js:3 Uncaught TypeError: Cannot read property 'offsetWidth' null at script.js:4"
Can someone tell me why this is happening? My code is below.
const container=document.querySelector(".thumbnail-container");
const allBox=container.children;
const containerWidth=container.offsetWidth;
const margin=30;
var item=0;
// item setup per slide
responsive=[
{breakPoint:{width:0,item:1}}, //if width greater than 0 (1 will item show)
{breakPoint:{width:600,item:2}}, //if width greater than 600 (2 will item show)
{breakPoint:{width:1000,item:4}} //if width greater than 1000 (4 will item show)
]
function load(){
for(let i=0; i<responsive.length;i++){
if(window.innerWidth>responsive[i].breakPoint.width){
items=responsive[i].breakPoint.item
}
}
start();
}
function start(){
for(let i=0;i<allBox.length;i++){
//width and margin setup of items
//allBox[i].style.width=containerWidth/items;
console.log(allBox[i])
}
}
window.onload=load();
<div class="thumbnailslider">
<div class="thumbnailcontainer">
<div class="artitem">
1
</div>
<div class="artitem">
2
</div>
<div class="artitem">
3
</div>
<div class="artitem">
4
</div>
<div class="artitem">
5
</div>
<div class="artitem">
6
</div>
<div class="artitem">
7
</div>
<div class="artitem">
8
</div>
</div>
<!-- Control Slides -->
<div class="artcontrols">
</div>
</div>
<script src="script.js"></script>

Please change this line you have misspelled thumbnailcontainer to thumbnail-container
const container=document.querySelector(".thumbnailcontainer");

Related

Next(question) Button does not work when replay is done

This is a small quiz app which I am making to learn JS. It works fine and gives the proper result, but when clicked replay, it displays the quizBox but the 'Next' button does not work. There is no console error and I am unable to understand where to look for the error in the code.
This is the jsFiddle link of the working app
https://jsfiddle.net/lifet/t20h6gw8/10/
js has both the script and the questions file
This is the Html for the quiz and result box
<!--Start Quiz Box-->
<div class="row quiz_box">
<div class="col-md-6 col-sm-12">
<div class="card">
//other part of code
<!--Quix Box Footer-->
<footer>
<button class="next_btn">Next</button>
</footer>
</div>
</div>
</div>
</div>
<!--End Quiz Box-->
<!--Start Result Box-->
<div class="row result_box">
<div class="card col-md-6 col-sm-12">
//other part of code
<div class="buttons">
<button class="restart">Replay Quiz</button>
</div>
</div>
</div>
<!--End Result Box-->
</div>
This is the css for hiding and showing the result and quiz box respectively
.removeResultBox.result_box{
display: none;
}
.removeResultBox.quiz_box{
display: flex;
}
This is the js for replay function and next on click.
//---------------- restart Quiz-------------------//
const replayQuiz = resultBox.querySelector(".restart");
function showQuizBox(){}
replayQuiz.onclick=() =>{
quizBox.classList.add("removeResultBox");// this displays the quiz box
resultBox.classList.add("removeResultBox");// this hides the result box
queCounter = 0;
queNumber = 1;
startTime = 15;
widthValue = 0;
userScore =0;
showQuestions(queCounter);
questionCounter(queNumber);
clearInterval(timeCounter);
clearInterval(counterLine);
startTimer(startTime);
startTimeLine(widthValue);
nextBtn.style.display="none";
}
This is the next button onclick event
//go on to the next question
nextBtn.onclick=()=>{
console.log("next");
if (queCounter < questions.length - 1) {
queCounter++;
queNumber++;
showQuestions(queCounter);
questionCounter(queNumber);
clearInterval(timeCounter);
startTimer(startTime);
clearInterval(counterLine);
startTimeLine(widthValue)
nextBtn.style.display="none";
}
else {
showResultBox();
}
}
I am stuck badly and would really appreciate any help. Thank you!!
you have to change the line
const replayQuiz = document.querySelector(".restart");
check the website
In replayQuiz.onclick instead of adding removeResultBox try and remove showResultBox:
replayQuiz.onclick = () => {
resultBox.classList.remove('showResultBox')
quizBox.classList.remove('showResultBox')
...
}

Explain please why doesnt work .className property? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 5 years ago.
DOM-structure in .html
Theres .js and bootstr containers for making stylish gallery.
<script src="main.js"></script>
<div class="container-fluid" id="gal">
<div class="row">
<div class="col-md-offset-2 col-md-8 col-sm-offset-1 col-sm-10 col-xs-12">
<div class="container-fluid galbody" id="gallery3">
<h2 id="galhead">Gallery</h2>
<div id="col1">
</div>
<div id="col2">
</div>
<div id="col3">
</div>
</div>
<div class="container-fluid galbody" id="gallery2">
<div id="col1">
</div>
<div id="col2">
</div>
</div>
<div class="container-fluid galbody" id="gallery1">
<div id="col1">
</div>
</div>
</div>
</div>
</div>
Im trying to insert within .js functions and methods images that are in array arr[] urls.
there is an main.js code:
document.write("hey!");
//definin' width of browser workspace
var galdiv3 = document.getElementById("gallery3").className = "none";
var galdiv2 = document.getElementById("gallery2").className = "none";
var galdiv1 = document.getElementById("gallery1").className = "none";
//creating array of future gallerydir images paths list
var arr = [];
//creating async flow for read json with paths. after calling back func for parse read text as array list in array (arr)
fs.readFile("gallist.json", function cb(err,rd){
var imgList = JSON.parse(rd);
imgList.forEach(function(file) {
arr += file + ", ";
}, this);
console.log(arr);
});
function singleGrid()
{
galdiv1.removeAttribute(className = " none");
function imgFill(){
for (var file in arr){
var x = document.createElement("div");
x.className();
}
}
imgFill();
}
singleGrid();
Problem is there :
var galdiv3 = document.getElementById("gallery3")**.className = "none"**;
var galdiv2 = document.getElementById("gallery2")**.className = "none"**;
var galdiv1 = document.getElementById("gallery1")**.className = "none"**;
Console throws err "Uncaught TypeError: Cannot set property 'className' of null"
you're trying to access DOM element before they've been inserted into the page.
so in the expression
var galdiv3 = document.getElementById("gallery3").className = "none";
the expression document.getElementById("gallery3") returns null. as consequence: null.className throws the error.
this happens because the <script></script> tag executes his content in the moment it's added to the page, that is, during the loading of the page, before the other tags are added. For this, when the script is executed, there are no other elements in the page so that you cannot find them.
move the <script src="main.js"></script> to the bottom or simply put all the code inside the window.onload event.

Why jquery height and javascript height returns 0?

I have a visible div on screen, but when I gets its height, it always returns 0. How it is possible? I have tried many jquery and javascript methods to get hight but it returns 0. This is my div:
<div class="option-content">
<div class="row">
<div class="col-sm-12">
<div class="dropDownStyling" id="filterDropdowns">
</div>
</div>
</div>
<!-- Other contents -->
</div>
I have tried following methods to get height:
var $element = $("#filterDropdowns");
$element.css("height")
$element.height()
$element.innerHeight()
$element.outerHeight()
Also I tried javascript:
document.getElementById('filterDropdowns').offsetHeight
document.getElementById('filterDropdowns').clientHeight
But in all cases, it returns 0 while it returns the width value. Then why height value gets 0?
if you use blank DIV without any content than you will always get 0 height.
For Example :
<div id="demo" class="text">
<div id="abc">
</div>
</div>
so you must add content in DIV
Second way to get height of DIV you can use clientHeight.
document.getElementById("xxx").clientHeight;
create one function & Call after DOM ready
function test () {
var height = $('#filterDropdowns').innerHeight();
alert(height)
}
$(document).ready(function(){
$('#filterDropdowns').append('23');
test();
})
<div class="option-content">
<div class="row">
<div class="col-sm-12">
<div class="dropDownStyling" id="filterDropdowns">
</div>
</div>
</div>
//Other contents
</div>
https://jsfiddle.net/azL0070r/3/
HTML
<div class="option-content">
<div class="row">
<div class="col-sm-12">
<div class="dropDownStyling" id="filterDropdowns">
</div>
</div>
</div>
Javascript
var height = $('#filterDropdowns').height();
alert(height)<br>
CSS
#filterDropdowns {
height: 150px;
}

How to set visible posts by js?

I have issue that I need some helps.
For example, I have HTML like:
<div class="posts">
posts 1
</div>
<div class="posts">
posts 2
</div>
<div class="posts">
posts 3
</div>
<div class="posts">
posts 4
</div>
Now, I want use Javascript/Jquery to make the number of post is visible or not.
Example: if i use js like this then 3 posts is visible, the fourth post... is invisible.
<script>
numbervisible = "3"
</script>
How can I do this with Js/jquery. Thanks.
You can use slice() method:
$('.posts').hide().slice(0, numbervisible).show();
And here is a working example on jsFiddle: http://jsfiddle.net/H7aTs/
You could also use a jQuery psuedo selector
<script>
numbervisible = '3';
$('.posts:gt(' + (numbervisible -1) + ')').hide();
</script>
Link to jsFiddle
If you want to reference posts by specific ID # and not just position in list:
<div id="posts_1">
posts 1
</div>
<div id="posts_2">
posts 2
</div>
<div id="posts_3">
posts 3
</div>
<div id="posts_4">
posts 4
</div>
then:
$("#posts_" + post_no).hide();
$("#posts_" + post_no).show();
$("#posts_" + post_no).toggle();
etc.

Problems using fluentlenium with dynamic generated content

I am doing tests with fluentlenium to my application, but some errors are happening. I ‘m using Play Framework and Slickgrid to create my grid. Slickgrid create the grid dynamically in javascript.
The structure that is created seems like this:
<div id=”grid”>
<div class=”header”>
<div class=”slickgrid-column-header column-1”>Column 1 </div>
<div class=”slickgrid-column-header column-2”>Column 2 </div>
<div class=”slickgrid-column-header column-2”>Column 2 </div>
</div>
<div class=”viewport”>
<div class=”canvas”>
<div class=”slick-row row-1”>
<div class=”slick-cell l0 r0> Column 1 Row 1</div>
<div class=”slick-cell l1 r1> Column 2 Row 1</div>
<div class=”slick-cell l2 r2> Column 3 Row 1</div>
</div>
<div class=”slick-row row-2”>
<div class=”slick-cell l0 r0> Column 1 Row 2</div>
<div class=”slick-cell l1 r1> Column 2 Row 2</div>
<div class=”slick-cell l2 r2> Column 3 Row 2</div>
</div>
</div>
</div>
</div>
Normally, when you see your source code with fluentlenium, you can see all source code, but in my case, some slickgrid code lines are missing. And this missing lines are the lines that I need.
This code creates a simple test that get the page source.
#Test
public final void fakeTest() {
final int port = 3333;
running(testServer(port, fakeApplication()), HTMLUNIT,
new Callback<TestBrowser>() {
#Override
public void invoke(final TestBrowser browser) throws Throwable {
browser.goTo("http://localhost:3333/fake");
System.out.println(browser.pageSource());
}
});
}
The output seems like this:
<html>
<head> <title> </title> </head>
<body>
<div id=”grid>
<div class=”header”>
<div class=”slickgrid-column-header column-1”>Column 1 </div>
<div class=”slickgrid-column-header column-2”>Column 2 </div>
<div class=”slickgrid-column-header column-2”>Column 2 </div>
</div>
<div class=”viewport”>
<div class=”canvas”></div>
</div>
</div>
</body>
</html>
How you can see, the cells didn’t appear and I can’t get the cell FluentWebElement to simulate clicks or get the cell value.
You have the comportement you have write :
go to the page
print the source immediatly
What's happend there : the Slickgrid stuff is not generated yet. If you want so, you have to wait.
So use the await api with something like between the goTo(page) and :
await().atMost(5, TimeUnit.SECONDS).until(".slick-row").isPresent()
or anything you think more appropriate. There it will wait at most 5 seconds until a element with the class slick-row has been found.

Categories

Resources