This is my code. Im new to JavaScript so idk what I'm really doing. Basically, every time the button is clicked, a new Van Gogh detail/image should fill the background. I feel like many images are repeated and sometimes the button doesn't work (a new image doesn't appear on each click). Ideally, I would like a new image with each click. For now, I only have 10 images, but may add more. Thank you for your help.
HTML
<!DOCTYPE html>
<html>
<head>
<title>VG java project</title>
<link rel="stylesheet" type="text/css" href="assets/main.css">
<script src="assets/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="assets/main.js"></script>
</head>
<body>
<div class="container1"></div>
<div class="container">
<div class="button">
Do you like Van Gogh?
</div>
</div>
</body>
</html>
CSS
body {
font-family: courier new;
padding: 3rem;
z-index: 200;
background: url(gogh4.jpg);
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.item {
max-width: 960px;
text-align: center;
}
.button {
position: absolute;
left: 50px;
top: 50px;
border: 7px double;
border-color: black;
padding: 20px;
font-size: 40px;
background-color: rgb(225, 186, 253);
opacity: 80%;
}
.button:hover {
background-color: rgb(197, 103, 247);
color: white;
cursor: pointer;
opacity: 90%;
}
.gogh1 {
background: url(gogh1.jpg);
}
.gogh2 {
background: url(gogh3.jpg);
}
.gogh3 {
background: url(gogh3.jpg);
}
.gogh4 {
background: url(gogh4.jpg);
}
.gogh5 {
background: url(gogh5.jpg);
}
.gogh6 {
background: url(gogh6.jpg);
}
.gogh7 {
background: url(gogh7.jpg);
}
.gogh8 {
background: url(gogh8.jpg);
}
.gogh9 {
background: url(gogh9.jpg);
}
.gogh10 {
background: url(gogh10.jpg);
}
.highlight {
font-size: 200px;
}
JavaScript ~ I'm using jQuery btw
$(function() {
$(".button").click(function(){
let goghs = ["gogh1", "gogh2", "gogh3", "gogh4",
"gogh5", "gogh6", "gogh7", "gogh8",
"gogh9", "gogh10"]
let i = Math.floor(Math.random()* goghs.length - Math.random() + 2 );
$("body").toggleClass(goghs[i]);
});
});
Since You asked for Javascript help.
Here's a problem you had in your code:
Edited:
$(function () {
$(".button").click(function () {
let goghs = ["gogh1", "gogh2", "gogh3", "gogh4",
"gogh5", "gogh6", "gogh7", "gogh8",
"gogh9", "gogh10"
]
let i = Math.floor(Math.random() * goghs.length); //There was no need to add + Random plus 2 to it. You already Selecting a random index from an array(sometimes 'i' value was 10 -> undefined).
console.log(i, goghs[i]); //logging helps you notice that is nothing wrong with other parts and function runs. only the code itself has some problems.
$("body").toggleClass(goghs[i]);
});
});
If "i" is 2 the first time around then "gogh2" get added as the class.
If "i" is 3 the second time around the "gogh3" will be 'added' to the class list. "gogh2" will still be there.
Then, if "i" is 2 the third time around, then it will remove "gogh2" and you'll just be left with "gogh3".
Try:
$("body").removeClass();
$("body").addClass(goghs[i]);
and do away with your toggleClass line.
toggleClass will add the class to the list if it's not there and remove it if it is.
Related
I'm trying to make a game of little rabbit's farm. My level of programming is a beginner.
Why is addRabbit() code starts to work after the page is loaded? I wrote it to work after click to "Buy Rabbit" button
Why rabbits are not shown at the page near the "Sell Rabbit" and "Buy Rabbit" buttons?
I know that I have a lot of issues here as far as I'm a beginner. Could I ask you to mention any of them?
// VARIABLES
// variables for modal of chosing rabbits
const chooseModal = document.querySelector(".choose-modal");
const selectRabbitBtn = document.querySelector(".choose-rabbit-btn");
const rabbitSelects = document.querySelectorAll("input[type=radio]");
let chosenRabbitUrl = "img/rabbit1.png";
// start screen
const startScreenDiv = document.querySelector(".story-modal");
const rabbit = document.querySelector("img.rabbit");
const buyRabbitBtn = document.querySelector(".buy-btn");
// EVENT LISTENERS
selectRabbitBtn.addEventListener("click", chooseTheRabbit);
// FUNCTIONS
function chooseTheRabbit(e){
e.preventDefault();
for (let rabbit of rabbitSelects) {
if (rabbit.checked) {
chosenRabbitUrl = `img/${rabbit.id}.png`;
break;
}
}
chooseModal.style.display = "none";
startScreen();
}
function startScreen() {
startScreenDiv.style.display = "block";
rabbit.src = chosenRabbitUrl;
}
class RabbitGame {
constructor() {
this.rabbitsCount = parseInt(document.querySelector(".rabbits-count").innerText, 10);
this.rabbitsCountSpan = document.querySelector(".rabbits-count");
this.rabbitsShowDiv = document.querySelector(".rabbits-count-show");
this.coinsCount = parseInt(document.querySelector(".coins-count").innerText, 10);
this.coinsCountSpan = document.querySelector(".coins-count");
this.sellRabbitBtn = document.querySelector(".sell-btn");
this.myRabbits = [{age: 0, src: chosenRabbitUrl, width: 50}];
};
// function, that shows rabbits on the page, that the owner have
// adult rabbits should be bigger, little rabbits smaller
showRabbits() {
// rabbit.src = chosenRabbitUrl
this.myRabbits.forEach((rabbit) => {
this.rabbitsShowDiv.innerHTML += `<img src="${rabbit.src}" width="${rabbit.width}">`});
};
// function that adds a rabbit, if the owner doesn't have any coin, rabbits eat him
addRabbit() {
console.log("Hello");
if (this.coinsCount > 1) {
// remove 1 coin
this.coinsCount -= 1
console.log(this.coinsCount);
// show 1 coin less
this.coinsCountSpan.innerText = this.coinsCount
// add 1 for rabbits age
// if the rabbit is older than 4, make him bigger on screen
this.myRabbits.forEach((rabbit) => {
rabbit.age +=1;
if (rabbit.age > 3) {
rabbit.width = 70
}
})
// add 1 more rabbit to array
this.myRabbits.push({age: 0, src: chosenRabbitUrl, width: 50});
// show 1 more rabbit
this.rabbitsShowDiv.innerHTML += `<img src="${rabbit.src}" width="${rabbit.width}">`
}
};
// функция, которая продает кролика, если он взрослый
// если нет взрослых кроликов, выводит предупреждение, что нет взрослых кроликов
}
const rabbitGame = new RabbitGame();
rabbitGame.showRabbits;
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit());
/* GENERAL */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
h3 {
background-color: rgb(108, 165, 55);
width: 400px;
height: 30px;
padding: 5px;
color: white;
text-align: center;
}
button {
padding: 5px 20px;
background-color: rgb(194, 89, 89);
color: white;
text-transform: uppercase;
border: none;
font-weight: bold;
}
button:hover {
background-color: rgb(172, 79, 84);
}
/* END OF GENERAL */
/* CHOOSE RABBIT MODAL & RULES MODAL */
.choose-modal,
.rules-modal {
display: flex;
justify-content: center;
margin-top: 20px;
}
.choose-modal > div {
display: flex;
flex-direction: column;
}
input[type="radio"] {
opacity: 0;
}
label > img:hover {
border-bottom: 1px solid rgb(199, 199, 199);
}
ul {
list-style: none;
margin: 10px;
}
li {
margin-bottom: 5px;
}
.button-div {
display: flex;
justify-content: center;
}
/* END OF CHOOSE RABBIT MODAL & RULES MODAL */
/* START SCREEN */
/* .story-modal {
display: none;
} */
.story-modal {
background-image: url("img/neighbour.jpg");
background-size: cover;
height: 100vh;
position: relative;
}
img.rabbit {
position: absolute;
height: 40%;
top: 60%;
left: 50%;
overflow: hidden;
}
.story-modal > h3 {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
top: 5%;
}
.img-overlay {
width: 100%;
height: 100%;
background: rgba(61, 61, 61, 0.3);
}
.story-modal > button {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
top: 13%;
}
/* END OF START SCREEN */
/* MAIN GAME */
.main-game {
display: flex;
}
/* END OF MAIN GAME */
<div class="choose-modal">
<div>
<div class="choose-modal-header">
<h3>Please, choose the rabbit</h3>
</div>
<div>
<label for="rabbit1"><input type="radio" id="rabbit1" name="rabbits" value="rabbit1"><img src="img/rabbit1.png" width="100" alt="rabbit1"></label>
<label for="rabbit2"><input type="radio" id="rabbit2" name="rabbits" value="rabbit2"><img src="img/rabbit2.png" width="100" alt="rabbit2"></label>
<label for="rabbit3"><input type="radio" id="rabbit3" name="rabbits" value="rabbit3"><img src="img/rabbit3.png" width="80" alt="rabbit3"></label>
</div>
<div class="button-div">
<button type="submit" value="Choose" class="choose-rabbit-btn">Choose</button>
</div>
</div>
</div>
<div class="story-modal">
<div class="img-overlay"></div>
<h3>Your pretty neighbour gave you a rabbit</h3>
<img alt="rabbit" src="#" class="rabbit">
<button>Rules</button>
</div>
<div class="rules-modal">
<div>
<h3>Rules of game</h3>
<div>
<ul>
<li>Buy grass to feed the rabbits</li>
<li>Sell adult rabbits</li>
<li>Buy new little rabbits</li>
</ul>
</div>
<div class="button-div">
<button>Play</button>
</div>
</div>
</div>
<div class="main-game">
<div class=" navbar">
<p><img src="img/coin.png" height="20"> Coins <span class="coins-count">10</span></p>
<p class="name-of-gamer">Anonymous</p>
<p><img src="img/rabbit.png" height="20"> Rabbits <span class="rabbits-count">3</span></p>
</div>
<div class="rabbits-count-show"></div>
<div>
<button class="sell-btn">Sell Rabbit</button>
<button class="buy-btn">Buy Rabbit</button>
</div>
</div>
Changing the line
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit());
to
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit);
(simply removing those parenthesis) should work. When you add the parenthesis, a function gets called, and that's not what you want. When the button is clicked the eventlistener call the your function itself. as of your second problem you have to add parenthesis to the function to get called thus executing the code inside it.
NOTE: Do not post unnecessary files to a question. Try find the location that error could possibly occur. BTW, CSS has no contributing factor to a error in js code. sometimes html does. I know as a beginner it's hard to find the areas causing the error but it gets easier over time.
I'm trying to make a dark mode toggle button which can toggle between dark and light mode on click, User preference is also stored using localStorage. The user should manually press the button to toggle to other mode. If the user's choice is dark mode, Every page will be in dark mode and it doesn't turn to light mode on refreshing. Everything looks fine upto now but the real issue comes with loading time. The load time of a page is nearly 1 second and in that time, Page appears to be in light mode even if user's choice is dark mode. I don't want that to happen. I want loading time section in dark mode if user's choice is dark.
This is my current code:
<script>
const body = document.querySelector('body');
function toggleDark() {
if (body.classList.contains('dark')) {
body.classList.remove('dark');
localStorage.setItem("theme", "light");
} else {
body.classList.add('dark');
localStorage.setItem("theme", "dark");
}
}
if (localStorage.getItem("theme") === "dark") {
body.classList.add('dark');
}
</script>
<style>
body {background-color: #ffffff}
body.dark {background-color: #000000; color: #ffffff}
</style>
<button class="dark-mode" id="btn-id" onclick="toggleDark()"></button>
Another alternative is to load the script in the <head> element, and toggle the class on html element
To do so, you use document.documentElement.classList as that is the HTML element
Then change your CSS to
html.dark body {}
etc .. the class selector on HTML
html body {background-color: #ffffff}
html.dark body {background-color: #000000; color: #ffffff}
<script>
const body = document.querySelector('body');
function toggleDark() {
if (document.documentElement.classList.contains('dark')) {
document.documentElement.classList.remove('dark');
//localStorage.setItem("theme", "light");
} else {
document.documentElement.classList.add('dark');
//localStorage.setItem("theme", "dark");
}
}
//if (localStorage.getItem("theme") === "dark") {
document.documentElement.classList.add('dark');
//}
</script>
<button class="dark-mode" id="btn-id" onclick="toggleDark()">DARK</button>
Due to restrictions, localStorage is unavailable on stack overflow - uncomment those lines to see it work
Or - see https://jsfiddle.net/e9zg2p4c/
Store it to backend database. Then when serving HTML content put proper class/style for your elements. This will remove flickering between loading times:
<!DOCTYPE html>
<html>
<head>
<style>
/* Use Less/Sass for better management */
.theme.light {
background-color: #ffffff;
}
.theme.dark {
background-color: #000000; color: #ffffff;
}
</style>
</head>
<body class="theme <?= $user->themeName; ?>">
</body>
</html>
A little more tricky to toggle AND have a default theme
Note the localStorage calls do not work here at SO
working example
In the code below replace
const theme = "dark"; with
localStorage.getItem("theme") || "light"
and uncomment // localStorage.setItem("theme", body.classList.contains("dark") ? "light" : "dark");
on your server
.dark { background-color: black; color: white; }
<!DOCTYPE html>
<html>
<head>
<style>
.theme {
background-color: white;
color: black;
}
</style>
<script>
const theme = "dark"; // localStorage.getItem("theme") || "theme"
if (theme === "dark") {
const st = document.createElement("style");
st.id="darkStyle";
st.innerText = `body.theme { background-color: black; color: white; }`;
document.querySelector("head").appendChild(st);
}
window.addEventListener("load", function() {
document.getElementById("toggleTheme").addEventListener("click", function() {
const body = document.querySelector("body");
const darkStyle = document.getElementById("darkStyle");
if (darkStyle) {
darkStyle.remove(); // remove stylesheet now we know what the user wants
body.classList.remove("theme");
}
const theme = body.classList.contains("theme");
body.classList.toggle('theme',!theme);
body.classList.toggle('dark',theme);
// localStorage.setItem("theme", theme ? "light" : "dark"); // uncomment on your server
});
})
</script>
</head>
<body class="theme">
Here is the body
<button id="toggleTheme" type="button">Toggle theme</button>
</body>
</html>
Given that the only real difference between light and dark is the colours, why not simply create css variables for each colour you are going to use and use javascript to change the values of the variables. This way, once you have defined the classes using the variables in the appropriate places, changing the variable values changes the classes automatically. The choice of "dark" and "light" can be stored in whatever way is available to you - localStorage, cookies or backend etc - and you simply set the appropriate colours to the css variables when the page is being loaded. There's no need for separate definitions for each class and, as a developer, it allows you to quickly test the colour schemes without having to manually change every class one by one.
function changeTheme(t) {
if (t == "dark") {
document.documentElement.style.setProperty("--backgroundcolour", "black");
document.documentElement.style.setProperty("--fontcolour", "white");
} else {
document.documentElement.style.setProperty("--backgroundcolour", "white");
document.documentElement.style.setProperty("--fontcolour", "black");
}
}
:root {
--backgroundcolour:black;
--fontcolour:white;
}
body {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
span {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
div {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
table {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
<button onclick="changeTheme('dark');">Use dark theme</button><button onclick="changeTheme('light');">Use light theme</button>
<hr>
<span>Text in a span</span>
<hr>
<div>Text in a div</div>
<hr>
<table>
<tbody>
<tr><td>Text in a table</td></tr>
</tbody>
</table>
If you want to use checkbox, this solution for you.
if you want the value to remain unchanged, use localStorage. If you want a dark mode where you have values disappear when you close a tab or browser, use sessionStorage.
const check = document.getElementById('chk');
check.addEventListener('change', () => {
document.body.classList.toggle('dark');
localStorage.darkMode=!localStorage.darkMode;
});
window.onload=function() {
if(localStorage.darkMode) document.body.classList.toggle('dark');
}
#modeSwitcher{
margin: 5% 50%;
}
#modeSwitcher .checkbox {
opacity: 0;
position: absolute;
}
#modeSwitcher .checkbox:checked + .label .ball{
transform: translateX(35px);
}
#modeSwitcher .checkbox:checked + .label .ball::after{
content: '';
position: absolute;
background-color: #0A0E27;
width: 13px;
height: 13px;
border-radius: 50%;
bottom: 50%;
left: -5%;
transform: translateY(50%);
}
#modeSwitcher .label {
background-color: #0A0E27;
border-radius: 50px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
padding: 5px;
margin: 0;
position: relative;
height: 16px;
width: 50px;
transform: scale(1.5);
}
#modeSwitcher .label .fa-moon{
color:#0A0E27 ;
}
#modeSwitcher .label .ball {
background-color: #FDC503;
border-radius: 50%;
position: absolute;
top: 3px;
left: 3px;
height: 20px;
width: 20px;
transform: translateX(0px);
transition: transform 0.2s linear;
}
body{
background-color: #fff;
}
body.dark{
background-color: black;
}
<div id="modeSwitcher">
<input type="checkbox" class="checkbox" id="chk" />
<label class="label" for="chk">
<i class="fas fa-moon"></i>
<div class="ball"></div>
</label>
</div>
So I have a new notification style ring and green circle with unread notifications in it this circle only is visible when you have new notifications.
when page is refreshed even if you dont have a notification the circle is visible for a second and then goes invisible
If there is a new notification still when refreshed circle shows up empty or with zero and then goes invisible and then with correct number
HTML:
<div class="bell">
<div class="unseen-notification-show" data-bind="visible: UnSeenMessagesCount() > 0, text: UnSeenMessagesCount()" style="display:none"></div>
</div>
CSS:
.unseen-notification-show {
content: '';
display: block !important;
position: absolute;
top: -10px;
right: -8px;
width: 17px;
height: 17px;
border: 1px solid #ffffff;
background-color: #8cdb16;
border-radius: 8px;
cursor: pointer;
z-index: 3;
color: white;
text-align: center;
line-height: 15px;
font-size: 11px;
font-family: 'Times New Roman', Times, serif;
}
self.searchModel = new AuthorizedSearchViewModel();
self.Header = ko.observable(new HeaderModel());
self.UnSeenMessagesCount = ko.observable(0);
self.Messages = ko.observableArray();
self.CanShowRemindProfile = ko.observable(false);
self.Remind = ko.observable(new RemindModel());
self.LoadUserInformation = function () {
$.post('/User/GetUserInfoForDashboardHeader',
function (response) {
InitTawkChat(response);
self.Header(new HeaderModel(response));
if ($('#accountId').length > 0) {
$('#accountId').html(response.accountId);
}
}, "json").done(function () { console.warn("loaderOff"); });
};
self.GetRemindProfile = function () {
self.CanShowRemindProfile(false);
$.post('/User/GetRemindProfile', function (result) {
if (result) {
self.CanShowRemindProfile(true);
self.Remind(new RemindModel(result));
}
});
};
self.GetMessages = function () {
$.post('/Messages/GetAll', {
page: 1,
pageSize: 4
}, function (result) {
var notifications = [];
_.map(result.Notifications, function (item) {
notifications.push(new MessageModel(item));
});
self.Messages(notifications);
self.UnSeenMessagesCount(result.UnseenNotifications);
});
};
Remove !important from display property in your css and let knockout inline handle display.
function viewModel(){
var self = this;
self.UnSeenMessagesCount = ko.observable();
self.initData = function(){
//dummy setTimeout for your ajax get.
setTimeout(function(){
self.UnSeenMessagesCount(4);
},1000);
}
}
var vm = new viewModel();
vm.initData();
ko.applyBindings(vm);
.unseen-notification-show {
content: '';
display: block;
position: absolute;
width: 17px;
height: 17px;
border: 1px solid #ffffff;
background-color: #8cdb16;
border-radius: 8px;
cursor: pointer;
z-index: 3;
color: white;
text-align: center;
line-height: 15px;
font-size: 11px;
font-family: 'Times New Roman', Times, serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="bell">
<div class="unseen-notification-show" data-bind="visible: UnSeenMessagesCount() > 0, text: UnSeenMessagesCount()" style="display:none"></div>
</div>
Sounds like some loading issues. Try moving your css from being loaded in the top of the HTML, to be loaded in the bottom/footer.
What you want to do, is to hide the circle until the result is loaded (either 0 or 1,2,3,4.. and so on. Depending on the number of notifications).
In your div you got this line style="display:none"> which hides the circle. Thats good!
Now you should make sure that the style for .unseen-notification-show which contains display: block !important; that shows the circle - Should not be run before the calculation of the number to show is done.
One way could be to place the file that loads your css to the bottom of the HTML (like moving your <link rel="stylesheet" href="test.css" />). Or another way is to only use css for the hiding and then use javascript/jQuery for showing the cirle.
If this didn't help - then please provide the code you use to generate the number.
I think the issue is due to
self.UnSeenMessagesCount = ko.observable(0);
so when your modal is getting created it is initialized with value 0. So when you refresh the page initially it is 0 but when self.getMessage is called it updates your value.
How do I make the following code only display when the url ends in #404?
<!--404 code-->
<style>
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
border-color: #ff0263;
box-sizing: border-box;
}
</style>
<body>
<font face="century gothic">
<div class="div1" name="div1">
<span id='close' style="cursor:pointer" onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;'>x</span> The vite you were looking for could not be found. <button class="button button5">What do I do now?</button></div>
</font>
<script>
window.onload = function() {
document.getElementById('close').onclick = function() {
this.parentNode.parentNode.parentNode
.removeChild(this.parentNode.parentNode);
return false;
};
};
</script>
<style>
#close {
float: right;
display: inline-block;
padding: 2px 5px;
background: #ccc;
}
#close:hover {
float: right;
display: inline-block;
padding: 2px 5px;
background: #ccc;
color: #fff;
}
</style>
<script>
$(document).ready(function() {
$("#id1").click(function() {
$(".div1").css('display', 'block');
});
});
</script>
I run this website called Vite - vite.website (Google: Vite Flash Engine). and if I could set it up so that when it reaches a 404, it will redirect to vite.website/#404. How do I make the following code visible only when the anchor, #404 is active?
Thanks!
This is css.but you can use jquery.
you can get the hash of the current url of the page and use if statement for your aim.
you can get the hash location of a webpage using
window.location.hash
So, maybe something like this can work (assuming you're using jQuery)
function hashIs404() {
var hash = location.hash.slice(-1);
if (hash === "404") {
//Display things
//$(selector).addClass(classname); recommended
} else {
//Hash is not 404
//$(selector).removeClass(classname); recommended
}
}
and call this function hashIs404(); by binding it to window.onload:
window.onload = hashIs404;
As for actually displaying it, use the if case and
$("head").append("<link rel='stylesheet' href='stylesheet-location.css');
Hope I could help if not entirely solving the issue :)
I am working on a video player that launches a video into an iframe within a div overlay. I want to avoid repetetive code such as onclick=() in every link, and want to avoid external libraries such as jQuery, because jQuery produces an unpleasant flickering screen when my video window is launched.
My problem is that with my work so far, only the first link opens the video overlay. I (somewhat) understand that the [0] indicates the first element in an array. Can an array contain an infinite numerical range, or is there a better way to accomplish my goal here? There will potentially be thousands of videos in these galleries, so listing them one at a time in my script is not practical.
I am still struggling to learn, so a working example would be greatly appreciated. Thanks
My work so far
https://jsfiddle.net/4oomb9rt/
example code
<!doctype html>
<html>
<head>
<title>Video Overlay</title>
<style>
body {
margin: 0;
font-family: arial;
}
#vidPlayer {
height: 100%;
width: 100%;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #000;
overflow: hidden;
transition: 0.5s;
display: none;
color: white;
}
.closebtn {
position: absolute;
top: 7px;
right: 7px;
font-size: 50px;
}
.openbtn {
font-size: 30px;
}
.openbtn, .closebtn {
max-height: 48px;
max-width: 48px;
min-height: 48px;
min-width: 48px;
border-radius: 7px;
line-height: 12px;
}
.vidContent {
width: 100%;
text-align: center;
font-size: 32px;
}
</style>
</head>
<body>
<div id="vidPlayer">
<button class="closebtn">×</button>
<div class="vidContent">vidplayer content</div>
</div>
<button class="openbtn">☰</button>
<button class="openbtn">☰</button>
<button class="openbtn">☰</button>
<script>
function openNav() {
document.getElementById("vidPlayer").style.display = "block";
}
function closeNav() {
document.getElementById("vidPlayer").style.display = "none";
}
var opener = document.getElementsByClassName('openbtn')[0];
opener.addEventListener("click", function(e) {
openNav();
}, false);
var closer = document.getElementsByClassName('closebtn')[0];
closer.addEventListener("click", function(e) {
closeNav();
}, false);
</script>
</body>
</html>
You can iterate over element using ClassName and assign event listener.
for(var i=0;i<document.getElementsByClassName("openbtn").length;i++){
document.getElementsByClassName("openbtn")[i].addEventListener("click", function(e) {
openNav();
}, false);
}
Demo : https://jsfiddle.net/tj23hy3h/
You are on the right track. You want to make a few minor changes to your javascript.
var openers = document.getElementsByClassName('openbtn');
for(var i=0; i<openers.length; i++) {
openers[i].addEventListener("click", function(e) {
openNav();
}, false);
}
var closers = document.getElementsByClassName('closebtn');
for(var i=0; i<closers.length; i++) {
closers[i].addEventListener("click", function(e) {
closeNav();
}, false);
}
by iterating through all of your openers or closers you can add the listener to each one.
What you're problem is that you'll have to add you event listener to all of the elements of that type so something like this would work:
var opener = document.querySelectorAll('.openbtn');
Array.from(opener).foreach(function(opener_single){
opener_single.addEventListener("click", openNav, false);
});
and then the same theory for the closer elements.
what I'm doing here is I'm getting all elements with the class name of openbutton then looping through them in the loop i am then applying the click event listener in which runs the openNav function.