addEventListener without handler - javascript

I want to set an Event on an Element without inline Events like:
let myDiv = document.querySelector("#div");
myDiv.addEventListener("click",function({this.style.opacity = "0";})
<div onclick="zero()"></div>
this is code:
<div id="div"></div>
I expected the opacity of div Element changes to 0 but in console of the browser show this error:
Uncaught error: cannot read property addEventListener of null!

You're missing some brackets and introducing an unnecessary line break:
let myDiv = document.querySelector("#div");
myDiv.addEventListener("click", function() {
this.style.opacity = "0";
});
<div id="div">Hallo</div>
With regard to the error you're getting it suggests that you haven't allowed the DOM to load - ie you're trying to add an event listener to an element that isn't there. Your code is in the right order in your question but it's something to be mindful of.

Please try to check the syntax you have written
let myDiv = document.querySelector("#div");
myDiv.addEventListener("click", function() {
this.style.opacity = "0";
});
<div id="div">Content</div>

Related

Class model for html backend [duplicate]

I'm working on a flexible menu, that does not need to jump from page to page when clicking 'links'.
The JavaScript I use for that is as follows:
var inbox = document.getElementById("u-content-inbox");
var friends = document.getElementById("u-content-friends");
var agenda = document.getElementById("u-content-agenda");
var list = document.getElementById("u-content-list");
var news = document.getElementById("u-content-news");
var notes = document.getElementById("u-content-notes");
function Inbox() {
inbox.style.visibility='visible';
}
function Friends() {
friends.style.visibility='visible';
}
function Agenda() {
agenda.style.visibility='visible';
}
function List() {
list.style.visibility='visible';
}
function News() {
news.style.visibility='visible';
}
function Notes() {
notes.style.visibility='visible';
}
The div elements are like this:
<div id="u-content-inbox" style="visibility:hidden;">
Inbox
</div>
<div id="u-content-friends" style="visibility:hidden;">
Friends
</div>
Each div has a "u-content-x".
However, when I try to change the style attribute "visibility" to visible. It gives me the following error: Uncaught TypeError: Cannot read property 'style' of null
I'm not seeing what I'm doing wrong. Could somebody please bring clearance to me why exactly JavaScript, or rather, I fail to make it work?
Whenever I run a check on
if(!inbox) {
alert("Inbox div has not been found);
}
does not show the alert message.
Make sure you call your javascript after the document is loaded! I'm nearly certain you are trying to get element references before they exist in the dom. The best practices is to put all scripts just before the closing of the body tag.
<script src="some/path/to/file.js"></script>
</body>
If your scripts appear in the document before the elements do, you can put your code inside of this load event function:
window.addEventListener('load', function() {
//your code here
});
Just as a note on your code architecture, you could attach a class to each element and then do this:
var toMakeVisible = document.getElementsByClassName('some-class');
for (var i=0; i<toMakeVisible; ++i) {
var elem = toMakeVisible[i];
elem.style.visibility = 'visible';
}

addClass breaks JS

I wrote the following code:
document.addEventListener("DOMContentLoaded", ()=>{
let menu = document.querySelector(' #menu-mainmenu ');
menu.style.display = 'none';
});
let newButton = document.createElement(' div ');
This code didn't cause any problem.
The moment I've added the following code right under the let newButton, suddenly, as it seems, the JS broke (no JS would load properly anywhere in the site).
newButton.className = 'menuButton';
Console returns this error:
Uncaught DOMException:
Failed to execute 'createElement' on 'Document':
The tag name provided (' div ') is not a valid name.
Why would this happen? What is the problem with creating a div element this way?
You have extra spaces around the div tag and that cause an error. Remove them
document.addEventListener("DOMContentLoaded", ()=>{
//let menu = document.querySelector(' #menu-mainmenu ');
//menu.style.display = 'none';
console.log('Worked !!!');
});
let newButton = document.createElement('div');
newButton.className = 'menuButton';

Javascript - Onclick event should trigger a function and it's not working

I am finishing an assesstment for a course certificate. In my final task I am asked to create a mini js game that will generate random faces in two mirror sides and one side will have a missing face. An onclick event above the "missing face" should trigger my function nextLevel() that will erase the two divs (mirror divs) and generate new content.
I have develop this script in order to achieve the problem but I have an specific error for the onclick event. It says:
Uncaught TypeError: Cannot set property 'onclick' of null
But running a DOM viewer it says there is 5 childs added on the leftSide Div. Please, help me I cant find the solution to this issue.
var numberOfFaces=5;
var theLeftSide=document.getElementById("leftSide");
var theRightSide=document.getElementById("rightSide");
var theBody =document.getElementsByTagName("body")[0];
function generateFaces(){
for(i=0;i<numberOfFaces;i++){
var oImg=document.createElement("img"); // Creates an oimg node
oImg.setAttribute('src', 'http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png'); // sets the source for img file
theLeftSide.appendChild(oImg); // append the img to leftSide Div.
oImg.style.top = Math.floor(Math.random()*401)+'px';
oImg.style.left = Math.floor(Math.random()*401)+'px';
}
copyDiv();
}
function copyDiv(){
var cloned = theLeftSide.cloneNode(true);
cloned.removeChild( cloned.childNodes[ cloned.childNodes.length - 1 ] );
theRightSide.appendChild(cloned);
}
theLeftSide.lastChild.onclick=function nextLevel(event){
event.stopPropagation();
numberOfFaces += 5;
deleteAllChilds();
generateFaces();
};
/*
theBody.onclick =function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
*/
function deleteAllChilds(){
while(theLeftSide.childNodes.length>0){
theLeftSide.removeChild(theLeftSide.childNodes[theLeftSide.childNodes.lenth-1]);
}
while(theRightSide.childNodes.length>0){
theRightSide.removeChild(theRightSide.childNodes[theRightSide.childNodes.lenth-1]);
}
}
It was the position of the function nextLevel. Adding it inside the function generateFaces will provide the usability I was looking for. Thank you all.
generally the
Uncaught TypeError: Cannot set property 'onclick' of null
is warned when you're trying to apply an events on a DOM Object which is not loaded yet !! to avoid this verify that your script is loaded in the <head> element or if it is in the body be sure that it was loaded before HTML content having as id "leftSide" ..

DOM Element reference is null - Uncaught TypeError: Cannot read property 'style' of null

I'm working on a flexible menu, that does not need to jump from page to page when clicking 'links'.
The JavaScript I use for that is as follows:
var inbox = document.getElementById("u-content-inbox");
var friends = document.getElementById("u-content-friends");
var agenda = document.getElementById("u-content-agenda");
var list = document.getElementById("u-content-list");
var news = document.getElementById("u-content-news");
var notes = document.getElementById("u-content-notes");
function Inbox() {
inbox.style.visibility='visible';
}
function Friends() {
friends.style.visibility='visible';
}
function Agenda() {
agenda.style.visibility='visible';
}
function List() {
list.style.visibility='visible';
}
function News() {
news.style.visibility='visible';
}
function Notes() {
notes.style.visibility='visible';
}
The div elements are like this:
<div id="u-content-inbox" style="visibility:hidden;">
Inbox
</div>
<div id="u-content-friends" style="visibility:hidden;">
Friends
</div>
Each div has a "u-content-x".
However, when I try to change the style attribute "visibility" to visible. It gives me the following error: Uncaught TypeError: Cannot read property 'style' of null
I'm not seeing what I'm doing wrong. Could somebody please bring clearance to me why exactly JavaScript, or rather, I fail to make it work?
Whenever I run a check on
if(!inbox) {
alert("Inbox div has not been found);
}
does not show the alert message.
Make sure you call your javascript after the document is loaded! I'm nearly certain you are trying to get element references before they exist in the dom. The best practices is to put all scripts just before the closing of the body tag.
<script src="some/path/to/file.js"></script>
</body>
If your scripts appear in the document before the elements do, you can put your code inside of this load event function:
window.addEventListener('load', function() {
//your code here
});
Just as a note on your code architecture, you could attach a class to each element and then do this:
var toMakeVisible = document.getElementsByClassName('some-class');
for (var i=0; i<toMakeVisible; ++i) {
var elem = toMakeVisible[i];
elem.style.visibility = 'visible';
}

inserting divs into the dom using javascript?

im trying to insert a new div into the DOM with an id of "app"
var new_div = document.createElement("div");
var app_div = document.getElementById("app");
document.body.insertBefore(new_div, app_div);​
this gives me an error in the console:
Uncaught TypeError: Cannot call method 'insertBefore' of null
but i don't know why?
You need to wrap your code to window.onload handler:
window.onload = function() {
var new_div = document.createElement("div");
var app_div = document.getElementById("app");
document.body.insertBefore(new_div, app_div);
}
Example on jsFiddle.
Except that it would be better wrapped in onload() as suggested by Igor, don't you want to add new_div to the document first?
document.body.insertBefore(new_div, document.body.firstChild);
Try use jquery document.ready event

Categories

Resources