Trying to change the id of an element with Javascript - javascript

I am trying to change the id of a div whenever I hover over a selection in my navbar. I just can't see where my problem is. When I inspect the page and hover over the navbar selections, the div id is not changing.
This is my javascript:
// Run JS after contents are loaded
document.addEventListener("DOMContentLoaded", initialiseWebPage);
function initialiseWebPage() //Loads DOM content
{
var navImage = document.getElementById("picture");
// Variables for each Nav Selection
const home = document.getElementById("Home");
const portfolio = document.getElementsById("Portfolio");
const services = document.getElementsById("Services");
const achievements = document.getElementsById("Achievements");
const hobbies = document.getElementsById("Hobbies");
// Event listeners
home.addEventListener("mouseover", changeIdHome);
portfolio.addEventListener("mouseover", changeIdPortfolio);
services.addEventListener("click", changeIdServices);
achievements.addEventListener("mouseover", changeIdAchievements);
hobbies.addEventListener("mouseover", changeIdHobbies);
function changeIdHome()
{
navImag.id = "Home";
}
function changeIdPortfolio()
{
navImage.id = "Portfolio";
}
function changeIdServices()
{
navImage.id = "Services";
}
function changeIdAchievements()
{
navImage.id = "Achievements";
}
function changeIdHobbies()
{
navImage.id = "Hobbies";
}
}
This is the beginning of my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Website</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
<script src="Script.js"></script> <!-- Link document to javascript file -->
<link href="style.css" rel="stylesheet">
<link rel="stylesheet" href="https://m.w3newbie.com/you-tube.css">
</head>
<body>
<!-- Navigation -->
<div class="container-fluid">
<div id="picture">
I am pretty sure I linked my js correctly to my html.
as you can see at the bottom of the HTML, the div that im trying to play around has the id of "picture".

I can't 100% confirm this, however, on many of your constants you used document.getElementsById and it's supposed to be document.getElementById.
Heres the changed JavaScript code
document.addEventListener("DOMContentLoaded", initialiseWebPage);
function initialiseWebPage() //Loads DOM content
{
var navImage = document.getElementById("picture");
// Variables for each Nav Selection
const home = document.getElementById("Home");
const portfolio = document.getElementById("Portfolio");
const services = document.getElementById("Services");
const achievements = document.getElementById("Achievements");
const hobbies = document.getElementById("Hobbies");
// Event listeners
home.addEventListener("mouseover", changeIdHome);
portfolio.addEventListener("mouseover", changeIdPortfolio);
services.addEventListener("click", changeIdServices);
achievements.addEventListener("mouseover", changeIdAchievements);
hobbies.addEventListener("mouseover", changeIdHobbies);
function changeIdHome()
{
navImag.id = "Home";
}
function changeIdPortfolio()
{
navImage.id = "Portfolio";
}
function changeIdServices()
{
navImage.id = "Services";
}
function changeIdAchievements()
{
navImage.id = "Achievements";
}
function changeIdHobbies()
{
navImage.id = "Hobbies";
}
}
I hope this helps!

Every element should have unique id.
You can't get array from one element:
document.getElementsById()
So just replace it with:
document.getElementById()

Related

Site shows without CSS for like 500ms after I added a random css script

I have added a javascript which loads a random css each time the site loads, and after I added this script, the website shows without CSS for a few milliseconds before showing normally
Here is the script:
(function() {
var sheet = document.createElement('link');
sheet.rel = 'stylesheet';
sheet.href = 'css/' + (Math.floor(Math.random()*6)+1) + '.css';
document.getElementsByTagName('head')[0].appendChild(sheet);
})();
and here is where I put it in html
I have tried putting it outside the body and outside the head but still the same issue
<html lang="en" class="no-js">
<head>
<script type="text/javascript" src="js/random.js"></script>
<head>
Fixed
new code:
var RANDOM_CSS = {
cssfiles : ['1.css','2.css','3.css','4.css','5.css','6.css'],
pathtocss : 'css/',
getrandomcss : function() { return this.cssfiles[Math.floor(Math.random()*this.cssfiles.length)]; },
getlinktag : function() { return '<link rel="stylesheet" type="text/css" href="'+this.pathtocss+this.getrandomcss()+'" />'; },
printlinktag : function() { document.write(this.getlinktag()); }
};
and
<script type="text/javascript" src="/js/random.js"></script>
<script type="text/javascript">
RANDOM_CSS.printlinktag();
</script>

How can I get the next and previous buttons working on my javascript code

I'm a new programmer learning and working on an image gallery with a full-screen popup using vanilla javascript and the console keep saying: Cannot set property 'src' of undefined at nextPic (app.js:35) at HTMLAnchorElement.onclick (Imagegallery.html:18).
The HTML code. I have the script running at the end. I am wondering if I need to remove the last popup event listener?? So the user can just keep clicking through using the next and previous buttons. Then, I would like for it once the user gets to the end of the gallery it automatically returns back or could press and X put to exit. I hope this helps to get my problem figured out.
const popup = document.getElementById('popup'); //reference to popup
const selectedImage = document.getElementById('selectedImage'); //reference to selected image
const imageIndexes = [1,2,3]; //array of images
const selectedIndex = null;
var currPic = 0;
var pics= '';
//to show image gallery
imageIndexes.forEach((i)=>{
const image = document.createElement('img'); //reference to image
image.src=`images/logo${i}.PNG`; //updated the source with number dynamically
image.classList.add('galleryImg'); // adding a css class
image.addEventListener('click',() =>{
//popup stuff
popup.style.transform =`translateY(0)`; //image slide down when clicked
selectedImage.src=`images/logo${i}.PNG`;
})
gallery.appendChild(image);
});
function nextPic(e){
e.preventDefault();
if (currPic < imageIndexes.length -1){
currPic++;
document.getElementById('prev').style.display = 'block';
}
else {
document.getElementById('next').style.display = 'none';
document.getElementById('prev').style.display = 'block';
}
document.popup.src = imageIndexes[currPic];
}
function prevPic(e){
e.preventDefault();
if (currPic > 0){
currPic--;
document.getElementById('next').style.display = 'block';
}
else {
document.getElementById('prev').style.display = 'none';
}
document.popup.src = imageIndexes[currPic];
}
popup.addEventListener('click', ()=>{
popup.style.transform =`translateY(-100%)`; //image slides back up
popup.src ='';
});```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Gallery</title>
<link rel="stylesheet" href="image.css">
</head>
<body>
<div class="container">
<h1>Image Gallery</h1>
<div id="gallery"></div>
</div>
<div id="popup">
<img src="" alt="" id="selectedImage">
Prev Next
</div>
<script src="app.js"></script>
</body>
</html>

Simple Vanilla JS game

I tried write simple vanilla JS memories game. I have a problem when i tried use query selector for divs which are created in Square class. Console.log returns empty nodelist or array. I suspect this function is done before divs are created. How Can I gain this elementy by query selector or another method ?
// CLASS SQUARE
export class Square {
constructor (number,type,field) {
this.number = number;
this.type = type;
this.field = field;
this.colors = ['red','red','blue','blue','orange','orange','green','green','gold','gold','pink','pink','cadetblue','cadetblue','purple','purple','beige','beige','cyan','cyan']
this.divs = [];
}
creator() {
for(let i = 0; i < this.number; i++) {
let create = document.createElement(this.type)
this.field.appendChild(create)
create.classList.add('square')
create.setAttribute('id','square')
this.divs.push(create);
console.log(this.divs)
}
}
addColor() {
this.divs.forEach((div)=>{
let chooseColor = Math.floor(Math.random()* this.colors.length);
div.style.backgroundColor = this.colors[chooseColor]
this.colors.splice(chooseColor,1)
})
}
addShadow() {
this.divs.forEach((div)=>{
const shadow = () => {
div.classList.add('shadow')
}
setTimeout(shadow,2000)
})
}
}
// CLASS SHADOW
export class Shadow {
constructor(shadowDivs) {
this.shadowDivs = shadowDivs;
}
revealDiv() { // THERE IS MY PROBLEM
this.shadowDivs.forEach((shadowDiv)=>{
shadowDiv.addEventListener('click',()=>{
console.log(this.shadowDivs)
shadowDiv.classList.remove('shadow')
})
})
}
}
//MAIN JS FILE
import { Square } from "./Square.js";
import { Shadow } from "./Shadow.js";
class Game {
elements = {
number: 20,
type: 'div',
field: document.getElementById('field'),
divs: document.querySelectorAll('.shadow') //THERE I TRY GAIN ELEMENTS
}
init() {
const squareCreator = new Square(this.elements.number,this.elements.type,this.elements.field);
const shadows = new Shadow(this.elements.divs) // AND THERE I CREATE NEW SHADOW
squareCreator.creator();
squareCreator.addColor();
squareCreator.addShadow();
// squareCreator.revealDiv()
shadows.revealDiv()
}
}
const game = new Game();
game.init()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="gameField" id='field'></div>
<script src="js/script.js" type="module"></script>
</body>
</html>
You can simply do this:
addEventListener("DOMContentLoaded", () => {
game.init();
});
Remove the timeout
addShadow() {
this.divs.forEach((div)=>{
div.classList.add('shadow')
})
}
Reorder the ini() and use the querySelector after the addShadow else there will be nothing to select.
init() {
const squareCreator = new Square(this.elements.number,this.elements.type,this.elements.field);
squareCreator.creator();
squareCreator.addColor();
squareCreator.addShadow();
const shadows = new Shadow(document.querySelectorAll('.shadow')) // AND THERE I CREATE NEW SHADOW
shadows.revealDiv()
}

Pure Javascript- Change class of onclick element generated by function

I'm new in coding and have been around a problem for a few days but found no solution.
I'm trying to build a canvas with a grid made out of squares and, when a square is clicked, it changes its background color.
I'm learning pure javascript and my problem is that I can't find a way to refer to the clicked element and change only its class, because my grid is generated by a function. I am doing it this way because I want to be able to change the canvas size in future.
Any suggestions on how to proceed?
HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Square Canvas Game</title>
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css2?family=Merriweather:ital,wght#0,300;0,400;0,700;0,900;1,300;1,400;1,700;1,900&display=swap" rel="stylesheet">
</head>
<body onload="javascript:setInitialCanvas()">
<header>
<h1>Square artist</h1>
</header>
<div id="gameInterfaceContainer">
<button id="clearCanvas" onclick="clearAllSquares()">Clear All</button>
<div id="canvas">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
JS
function setInitialCanvas(){
for (let i =0; i<400; i++){
let initialSquare = document.createElement("div");
document.getElementById("canvas").appendChild(initialSquare);
initialSquare.className = "canvasSquare clearSquare";
initialSquare.onclick = changeSquareColor(this);
initialSquare.style.backgroundColor = "white";
initialSquare.id = "square" + i;
}
}
function changeSquareColor(this){
let squareColor = ["white","blue","black","green","red","yellow","gray","brown"];
let colorIndex = 0;
while (squareColor[colorIndex] != this.style.backgroundColor){
colorIndex += 1;
}
if(this.style.backgroundColor == squareColor[squareColor.length]){
this.style.backgroundColor = squareColor[0];
}else
colorIndex += 1;
this.style.backgroundColor = squareColor[colorIndex];
}
Thank you!
*Edit: Adding codepen (that doesn't work) https://codepen.io/ccue92/pen/qBNKLQY
The reason it's not working is you're not binding the changeSquareColor function to onclick event, you are binding the result of it.
You need to change onclick binding like this:
initialSquare.onclick = function(event) {
changeSquareColor(event.target);
}
And do not use "this" as a variable name, because it's a reserved word for the current scope:
function changeSquareColor(square) {
let squareColor = ["white","blue","black","green","red","yellow","gray","brown"];
let colorIndex = 0;
while (squareColor[colorIndex] != square.style.backgroundColor){
colorIndex += 1;
}
if(square.style.backgroundColor == squareColor[squareColor.length]){
square.style.backgroundColor = squareColor[0];
} else {
colorIndex += 1;
}
square.style.backgroundColor = squareColor[colorIndex];
}

Javascript: How to center multiple buttons that were created in Javascript using dynamically set CSS Style

I am trying to create a row of three buttons in Javascript using dynamically set CSS Style, but I am having difficulty trying to center the row of buttons in the middle of the page. This is with buttons that are currently not part of a div.
I have tried button.align = 'center'; with no success.
Here is the link to jsfiddle snippet.
HTML SKELETON
<head>
<meta charset="utf-8">
<title>Buttons</title>
</head>
<body>
<script>
</script>
</body>
</html>
JAVASCRIPT
var one, two, three;
function button(text) {
var button = document.createElement('button');
var buttonText = document.createTextNode(text);
button.appendChild(buttonText);
return button;
}
function buttonTest() {
one = button('one');
two = button('two');
three = button('three');
// put the buttons on page
document.body.appendChild(one);
document.body.appendChild(two);
document.body.appendChild(three);
}
buttonTest();
Link Here
var one, two, three;
function button(text) {
var button = document.createElement('button');
var buttonText = document.createTextNode(text);
button.appendChild(buttonText);
return button;
}
function buttonTest() {
one = button('one');
two = button('two');
three = button('three');
var divElem = document.createElement('div');
divElem.setAttribute('style', 'text-align:center;');
// put the buttons on page
//document.body.appendChild(one);
//document.body.appendChild(two);
//document.body.appendChild(three);
divElem.appendChild(one);
divElem.appendChild(two);
divElem.appendChild(three);
document.body.appendChild(divElem);
}
buttonTest();
A quick solution would be adding text-align : center to the body
var one, two, three;
function button(text) {
var button = document.createElement('button');
var buttonText = document.createTextNode(text);
button.appendChild(buttonText);
return button;
}
function buttonTest() {
one = button('one');
two = button('two');
three = button('three');
// put the buttons on page
document.body.appendChild(one);
document.body.appendChild(two);
document.body.appendChild(three);
}
buttonTest();
body {text-align: center;}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Buttons</title>
</head>
<body>
<script>
</script>
</body>
</html>

Categories

Resources