How to make video player function and hit the red bar - javascript

I have got a basic video player and i followed a tutorial on how to create it, but when you click on the play button, then nothing happens as it does not play the video. Also I have got a red bar on the video as the progress, which is displayed all the time, but i only want it to be displayed on hove, so how can I achieve this as i followed the same youtube video as above.
I have followed a youtube and searched the internet, but i have been unable to fin a solution.
HTML
<div class="c-video">
<video class="galaxy-video" src="../videoplayer/intro.mkv"></video>
<div class="controls">
<div class="blue-bar">
<div class="blue-juice"></div>
</div>
<div class="buttons">
<button id="play-pause"></button>
</div>
</div>
</div>
CSS
.galaxy-video{
width: 100%;
height: 700px;
}
.c-video{
width: 100%;
position: relative;
overflow: hidden;
}
.c-video:hover .controls{
transform: translateY(0);
}
.controls{
display: flex;
position: absolute;
bottom: 5px;
width: 1245px;
margin-left: 155px;
flex-wrap: wrap;
background: rgba(0, 0, 0, 0.7);
transform: translateY(100%);
transition: all 0.2s;
}
.buttons{
padding: 10px;
}
.buttons button{
background: none;
border:0;
outline: 0;
cursor: pointer;
}
.buttons button:before{
content: '\f144';
font-family: 'Font Awesome 5 Free';
width: 30px;
height: 30px;
display: inline-block;
font-size: 28px;
color: #fff;
-webkit-font-smoothing: antialiased;
}
.buttons button.play:before{
content: '\f144';
}
.buttons button.pause:before{
content: '\f28b';
}
.blue-bar{
height: 10px;
top: 0;
left:0;
width: 100%;
background: #000;
}
.blue-juice{
height:10px;
background-color: #ff0000;
}
Javascript
var video = document.querySelector(".galaxy-video");
var juice = document.querySelector(".blue-juice");
var btn = document.getElementById("play-pause");
function togglePlayPause() {
if (video.paused) {
btn.className = "pause";
video.play();
} else {
btn.className = "play";
video.pause();
}
}
btn.onclick = function() {
togglePlayPause();
};
Here is a screen shot of the red bar that i wish to only be displayed on hover:
https://imgur.com/AqtYNg4
Any help appreciated and thanks in advance.

(1)
"When you click on the play button, then nothing happens as it does not play the video."
You need to attach a listener to your button (listening for a "click" event).
<button id="play-pause" onClick="togglePlayPause();"> </button>
Then that should respond to your function togglePlayPause like this...
function togglePlayPause()
{
if (video.paused) { video.play(); btn.className = "pause"; }
else { video.pause(); btn.className = "play"; }
}
(2)
"Also I have got a red bar on the video as the progress, which is displayed all the time, but I only want it to be displayed on hover"
Simply add a "Hover" rule to the CSS of your target element.
.myDivID :hover {
//some hover-related code here...
}
The final setup could look like:
a) The target div is styled to have zero opacity (now is fully transparent).
<div class="blue-bar" style="opacity: 0">
b) Then your CSS rules would be like below (where opacity is animated to increase to 1.0)...
.blue-bar{
height: 10px;
top: 0;
left:0;
width: 100%;
background: #000;
}
.blue-bar:hover {
opacity: 1.0;
transition: transform 1.5s;
}
.blue-juice{
height:10px;
background-color: #ff0000;
}

Related

Add a button to change to dark mode in html website

I have added a button on my site which let's the users change to dark or light mode whenever they want. I added the button with a moon icon on it, but the problem is that I want that the moon icon changes to sun icon when the user is in dark mode. And changes to moon icon when user is in light mode.
function myfunction(e) {
console.log("you clicked");
document.documentElement.classList.toggle("dark-mode");
document.querySelectorAll(".inverted").forEach((result) => {
result.classList.toggle("invert");
});
}
const btn = document.querySelector('.btn')
btn.addEventListener('click', myfunction);
.dark-mode {
filter: invert(1) hue-rotate(180deg);
}
.invert {
filter: invert(1) hue-rotate(180deg);
}
<button class="btn"><img src='moon.png'></img></button>
The .inverted class in js is because I don't want the images to invert their colors.. so I gave all the images a class='inverted'
So, this is what I've done and someone please let me know how I should change the icon to moon and sun depending on the current mode (light or dark)
Thanks!
You could add the sun as another image to the button and change the visibility of the two images via your .dark-mode css class.
So whenever the .dark-mode class is present the moon gets hidden and the sun gets shown.
function myfunction(e) {
console.log("you clicked");
document.documentElement.classList.toggle("dark-mode");
document.querySelectorAll(".inverted").forEach((result) => {
result.classList.toggle("invert");
});
}
const btn = document.querySelector('.btn')
btn.addEventListener('click', myfunction);
.dark-mode {
filter: invert(1) hue-rotate(180deg);
}
.invert {
filter: invert(1) hue-rotate(180deg);
}
/* button handling */
.moon {
display: block;
}
.sun {
display: none;
}
.dark-mode .moon {
display: none;
}
.dark-mode .sun {
display: block;
}
<button class="btn">
<img class="moon" src="moon.png" alt="moon"></img>
<img class="sun" src="sun.png" alt="sun"></img>
</button>
You could go with the CSS approach as in #Fabian's answer. If you would like to go with JS, you could simply use a flag to indicate whether or not the user switched to dark mode, and dynamically set the icon based on it.
let isDarkMode = document.documentElement.classList.contains("dark-mode");
function myfunction(e) {
document.documentElement.classList.toggle("dark-mode");
document.querySelectorAll(".inverted").forEach((result) => {
result.classList.toggle("invert");
});
e.currentTarget.querySelector("img").src = isDarkMode ? "sun.png" : "moon.png";
}
You can use the below reference for the toggle button from light mode to dark mode and dark mode to light mode.
body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.toggle-checkbox {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
.toggle-slot {
position: relative;
height: 10em;
width: 20em;
border: 5px solid #e4e7ec;
border-radius: 10em;
background-color: white;
box-shadow: 0px 10px 25px #e4e7ec;
transition: background-color 250ms;
}
.toggle-checkbox:checked ~ .toggle-slot {
background-color: #374151;
}
.toggle-button {
transform: translate(11.75em, 1.75em);
position: absolute;
height: 6.5em;
width: 6.5em;
border-radius: 50%;
background-color: #ffeccf;
box-shadow: inset 0px 0px 0px 0.75em #ffbb52;
transition: background-color 250ms, border-color 250ms, transform 500ms cubic-bezier(.26,2,.46,.71);
}
.toggle-checkbox:checked ~ .toggle-slot .toggle-button {
background-color: #485367;
box-shadow: inset 0px 0px 0px 0.75em white;
transform: translate(1.75em, 1.75em);
}
.sun-icon {
position: absolute;
height: 6em;
width: 6em;
color: #ffbb52;
}
.sun-icon-wrapper {
position: absolute;
height: 6em;
width: 6em;
opacity: 1;
transform: translate(2em, 2em) rotate(15deg);
transform-origin: 50% 50%;
transition: opacity 150ms, transform 500ms cubic-bezier(.26,2,.46,.71);
}
.toggle-checkbox:checked ~ .toggle-slot .sun-icon-wrapper {
opacity: 0;
transform: translate(3em, 2em) rotate(0deg);
}
.moon-icon {
position: absolute;
height: 6em;
width: 6em;
color: white;
}
.moon-icon-wrapper {
position: absolute;
height: 6em;
width: 6em;
opacity: 0;
transform: translate(11em, 2em) rotate(0deg);
transform-origin: 50% 50%;
transition: opacity 150ms, transform 500ms cubic-bezier(.26,2.5,.46,.71);
}
.toggle-checkbox:checked ~ .toggle-slot .moon-icon-wrapper {
opacity: 1;
transform: translate(12em, 2em) rotate(-15deg);
}
<head>
<script src="https://code.iconify.design/1/1.0.4/iconify.min.js"> </script>
</head>
<label>
<input class='toggle-checkbox' type='checkbox'>
<div class='toggle-slot'>
<div class='sun-icon-wrapper'>
<div class="iconify sun-icon" data-icon="feather-sun" data-inline="false"></div>
</div>
<div class='toggle-button'></div>
<div class='moon-icon-wrapper'>
<div class="iconify moon-icon" data-icon="feather-moon" data-inline="false"></div>
</div>
</div>
</label>
function myfunction(e) {
const doc = document.documentElement
doc.classList.toggle("dark-mode");
document.querySelectorAll(".inverted").forEach((result) => {
result.classList.toggle("invert");
});
const img = e.currentTarget.querySelector('img')
const label = e.currentTarget.querySelector('span')
if (doc.classList.contains('dark-mode')) {
img.src = 'sun.png'
label.innerHTML = 'Light mode'
} else {
img.src = 'moon.png'
label.innerHTML = 'Dark mode'
}
}
const btn = document.querySelector('.btn')
btn.addEventListener('click', myfunction);
.dark-mode {
filter: invert(1) hue-rotate(180deg);
}
.invert {
filter: invert(1) hue-rotate(180deg);
}
'
<button class="btn">
<img src='moon.png' alt="" />
<span>Dark mode</span>
</button>

Text inside a button is not acting like part of the button?

Soon I'm releasing an album, so I decided to make a promo website for it. The website will be very simple: basically a list of buttons, each with the title of a song and a play button for playing a preview of that song. Also, when any button is clicked I want a popup to open. I'm pretty unexperienced, but I've managed to achieve all this. The only problem I have is that when I click on the title of any song in a button, which is inside a P tagg, the popup doesn't open. It only seems to work if I click on the background of the button, and I don't want that.
Also, something similar happens when de popup does open: I have programmed the popup to close if the user clicks outside the popup. And it works! But it also closes if I click on the text inside the popup.
I'm not sure why this is happening (maybe because of the way I used event listeners in my JS), but I would really appreciate if anyone could tell me how to make the text in the button act like part of the button, and how to avoid that clicking any text in the popup closes it.
I will leave a snippet here with all my code.
var song1 = document.getElementById("SoloYoPreview");
var playbutton1 = document.getElementById("playbutton1");
var button1 = document.getElementById("button1");
var toggle1 = 0;
var song2 = document.getElementById("LaNocheEnteraPreview");
var playbutton2 = document.getElementById("playbutton2");
var button2 = document.getElementById("button2");
var toggle2 = 0;
var song3 = document.getElementById("QueTalSiVamosPreview");
var playbutton3 = document.getElementById("playbutton3");
var button3 = document.getElementById("button3");
var toggle3 = 0;
var song4 = document.getElementById("EsUnRegaloPreview");
var playbutton4 = document.getElementById("playbutton4");
var button4 = document.getElementById("button4");
var toggle4 = 0;
var song5 = document.getElementById("NoMeQuieroMentirPreview");
var playbutton5 = document.getElementById("playbutton5");
var button5 = document.getElementById("button5");
var toggle5 = 0;
function ctrl_song(number, command = "") {
var thissong = window["song"+number];
var thisplaybutton = window["playbutton"+number];
var thisbutton = window["button"+number];
var thistoggle = window["toggle"+number];
if (command == "stop") {
window["toggle"+number] = 2;
thisbutton.style.animationPlayState = "paused";
thisplaybutton.src = "../../Icons/replay_circle_filled_black_48dp.svg";
/*
console.log("stopping");
*/
} else if (command == "pause" || thistoggle == 1 ) {
window["toggle"+number] = 0;
thisbutton.style.animationPlayState = "paused";
thissong.pause();
thisplaybutton.src = "../../Icons/play_circle_filled_black_48dp.svg";
/*
console.log("pausing");
*/
} else if (command == "restart" || thistoggle == 2) {
window["toggle"+number] = 1;
thisbutton.style.animationPlayState = "running";
thissong.currentTime = 0;
thissong.play();
thisplaybutton.src = "../../Icons/pause_circle_filled_black_48dp.svg";
/*
console.log("restarting");
*/
} else if (command == "play" || thistoggle == 0) {
for (var i = 1;; i++) {
try {
window["toggle"+i] = 0;
var fbutton = window["button"+i];
fbutton.style.animationPlayState = "paused";
var fsong = window["song"+i];
fsong.pause();
var fplaybutton = window["playbutton"+i];
fplaybutton.src = "../../Icons/play_circle_filled_black_48dp.svg";
} catch (e) {
break;
}
}
window["toggle"+number] = 1;
thisbutton.style.animationPlayState = "running";
thissong.play();
thisplaybutton.src = "../../Icons/pause_circle_filled_black_48dp.svg";
/*
console.log("playing");
*/
}
}
document.addEventListener("click", function(e){
var sindex = e.target.dataset.sindex;
ctrl_song(sindex);
});
document.addEventListener("animationiteration", function(e) {
var sindexb = e.target.dataset.sindexb;
ctrl_song(sindexb, "stop");
});
var popup = document.getElementById("popupid");
var popupshadow = document.getElementById("popupshadow");
function togglePopup(songtitle = "") {
document.querySelector("#popuptitle").innerHTML = songtitle;
popup.classList.toggle("show");
popupshadow.classList.toggle("show");
}
window.onclick = function(event) {
if (popup.className == "popup show" && event.target !== popup && event.target.className !== "songbuttons") {
togglePopup();
}
}
#import url('https://fonts.googleapis.com/css2?family=Montserrat&display=swap');
/* width */
::-webkit-scrollbar {
width: 10px;
}
/* Track */
::-webkit-scrollbar-track {
background: #f1f1f1;
}
/* Handle */
::-webkit-scrollbar-thumb {
background: #888;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
background: #555;
}
body {
margin: 0px;
background-color: #f1f1f1;
font-family: 'Montserrat', sans-serif;
font-size: 25px;
position: relative;
}
#blurredbanner {
width: auto;
background-image: url("InflamaArtworkBlur.jpg");
background-size: 100%;
background-position: center;
}
#albumcover {
width: 350px;
display: block;
margin-left: auto;
margin-right: auto;
padding-top: 50px;
padding-bottom: 50px;
}
p {
margin-block-start: 0.67em;
color: #111111;
}
h1 {
margin-block-start: 0.67em;
margin-bottom: 0px;
letter-spacing: 15px;
color: #111111;
}
#title {
text-align: center;
}
#links {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
button {
text-decoration: none;
cursor: pointer;
display: flex;
align-items: center;
text-align: center;
position: relative;
border: 1px solid #111111;
background-repeat: no-repeat;
color: #111111;
border-radius: 50px;
font-size: 0.67em;
margin-block-start: 45px;
height: 60px;
width: 50%;
transition: 0.4s;
background-image: linear-gradient( rgba(200,200,200,0.75), rgba(174,174,174,0.75) );
-webkit-animation: progressbar 30s linear;
animation: progressbar 30s linear infinite;
}
button:hover {
transform: translate(0px, -8px);
}
#keyframes progressbar {
0% {
background-size: 0%;
}
100% {
background-size: 100%;
}
}
#button1 {
animation-play-state: paused;
}
#button2 {
animation-play-state: paused;
}
#button3 {
animation-play-state: paused;
}
#button4 {
animation-play-state: paused;
}
#button5 {
animation-play-state: paused;
}
.songtitle {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
margin-block-start: 0px;
}
.popup {
position: fixed;
z-index: 2;
visibility: hidden;
top: 150%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #ffffffaf;
border-radius: 10px;
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
width: 25%;
height: 50%;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
transition: 0.4s;
}
.popup h1 {
}
.popup.show {
visibility: visible;
top: 50%;
width: 75%;
}
.popupshadow {
background-color: #1111118f;
position: fixed;
width: 100%;
height: 100%;
z-index: 1;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
visibility: hidden;
opacity: 0;
transition: 0.6s;
}
.popupshadow.show {
opacity: 1;
visibility: visible;
}
<!DOCTYPE html>
<HEAD>
<TITLE>Inflama by Dherrera</TITLE>
<LINK rel="stylesheet" href="genericpromo.css">
</HEAD>
<BODY>
<DIV class="popupshadow" id="popupshadow"></DIV>
<DIV id="blurredbanner">
<IMG id="albumcover" src="InflamaArtwork.jpg">
</DIV>
<DIV id="title">
<H1>Inflama</H1>
<P>by Dherrera</P>
</DIV>
<DIV class="popup" id="popupid">
<H1 id="popuptitle"></H1>
<P>by Dherrera</P>
</DIV>
<DIV id="links">
<button class="songbuttons" id="button1" data-sindexb="1" onclick="togglePopup('Solo Yo')">
<audio id="SoloYoPreview">
<source src="audio/SoloYoPreview.mp3" type="audio/mpeg">
</audio>
<img id="playbutton1" data-sindex="1" src="../../Icons/play_circle_filled_black_48dp.svg" >
<P class="songtitle">Solo Yo</P>
</button>
<button class="songbuttons" id="button2" data-sindexb="2" onclick="togglePopup('La Noche Entera')">
<audio id="LaNocheEnteraPreview">
<source src="audio/LaNocheEnteraPreview.mp3" type="audio/mpeg">
</audio>
<img id="playbutton2" data-sindex="2" src="../../Icons/play_circle_filled_black_48dp.svg">
<P class="songtitle">La Noche Entera</P>
</button>
<button class="songbuttons" id="button3" data-sindexb="3" onclick="togglePopup('Que Tal Si Vamos')">
<audio id="QueTalSiVamosPreview">
<source src="audio/QueTalSiVamosPreview.mp3" type="audio/mpeg">
</audio>
<img class="playbtns" id="playbutton3" data-sindex="3" src="../../Icons/play_circle_filled_black_48dp.svg">
<P class="songtitle">Que Tal Si Vamos</P>
</button>
<button class="songbuttons" id="button4" data-sindexb="4" onclick="togglePopup('Es Un Regalo')">
<audio id="EsUnRegaloPreview">
<source src="audio/EsUnRegaloPreview.mp3" type="audio/mpeg">
</audio>
<img id="playbutton4" data-sindex="4" src="../../Icons/play_circle_filled_black_48dp.svg">
<P class="songtitle">Es Un Regalo</P>
</button>
<button class="songbuttons" id="button5" data-sindexb="5" onclick="togglePopup('No Me Quiero Mentir')">
<audio id="NoMeQuieroMentirPreview">
<source src="audio/NoMeQuieroMentirPreview.mp3" type="audio/mpeg">
</audio>
<img id="playbutton5" data-sindex="5" src="../../Icons/play_circle_filled_black_48dp.svg">
<P class="songtitle">No Me Quiero Mentir</P>
</button>
</DIV>
<!--SCRIPT-->
<SCRIPT src="genericpromov2.js"></SCRIPT>
</BODY>
</html>
Thanks in advance!
The only problem I have is that when I click on the title of any song
in a button, which is inside a <p> tag, the popup doesn't open
You need to add this style to your CSS:
.songtitle {
pointer-events: none;
}
This means that if anyone clicks on the <p> inside the <button>, it will be the <button> underneath which registers the click, rather than the <p>.
Further Reading:
https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

Make dots active on Slider

I have this Slider example created with pure JS.
The slider is working great. The only thing left to do would be to activate the three dots so when the 1st slide opens, 1st dot activates, showing different color than the other dots, and so on. Also, you should be able to open the correct slide when clicking dots, so 1st dot opens 1st slide, 2nd dot 2nd slide, and so on.
Could you help me to achieve this? You can find the source code below.
const nextBtn = document.querySelector('.nextBtn');
const prevBtn = document.querySelector('.prevBtn');
const container = document.querySelector('.images');
const offers = document.getElementById('offers');
const link = document.getElementById('links');
let colors = ['#7f86ff', '#2932d1', '#00067f'];
let currentSlide = 0;
let texts = ['Change1', 'Change2', 'Change3'];
let currentText = 0;
let links = ['Link1', 'Link2', 'Link3'];
let currentLink = 0;
function updateSlide(direction) {
currentSlide =
(colors.length + currentSlide + direction)
% colors.length;
container.style.backgroundColor = colors[currentSlide];
container.animate([{opacity:'0.1'}, {opacity:'1.0'}],
{duration: 200, fill:'forwards'})
}
function updateText(direction) {
currentText =
(texts.length + currentText + direction)
% texts.length;
offers.innerHTML = texts[currentText];
offers.animate([{transform:'translateY(-50px)', opacity:'0.0'}, {transform:'translateY(0)', opacity:'1.0'}],
{duration: 200, fill:'forwards'})
}
function updateLink(direction) {
currentLink =
(links.length + currentLink + direction)
% links.length;
link.innerHTML = links[currentLink];
link.animate([{transform:'scale(0,0)'}, {transform:'scale(1.1)'}],
{duration: 200, fill:'forwards'})
}
updateSlide(0);
updateText(0);
updateLink(0);
nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);
function nextSlide() {
updateSlide(+1);
updateText(+1);
updateLink(+1);
clearInterval(myInterval);
}
function prevSlide() {
updateSlide(-1);
updateText(-1);
updateLink(-1);
clearInterval();
clearInterval(myInterval);
}
var myInterval = window.setInterval(function(){
updateSlide(+1),updateText(+1),updateLink(+1); },
8000);
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: lightblue;
}
.images {
background-color: #4047c9;
flex: 0 0 80%;
min-height: 70vh;
border-radius: 10px;
position: relative;
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: center;
color: white;
}
#links {
text-decoration: none;
color: white;
border: solid 2px white;
border-radius: 3px;
padding: 5px 10px;
}
#links:hover {
background-color: #000238;
}
a {
color: white;
text-decoration: none;
}
.dots {
display: flex;
margin-top: 120px;
margin-bottom: 50px;
}
#dot1, #dot2, #dot3 {
width: 20px;
height: 20px;
background-color: rgb(147, 151, 249);
border-radius: 50%;
margin: 0px 5px;
cursor: pointer;
}
#dot1:active, #dot2:active, #dot3:active {
background-color: #fff;
}
.btn {
display: inline-block;
background: white;
color: black;
padding: 10px;
border: none;
cursor: pointer;
}
.prevBtn {
position: absolute;
top: 50%;
left: 0;
transform: translate(-50%, -50%);
}
.nextBtn {
position: absolute;
top: 50%;
right: 0;
transform: translate(50%, -50%);
}
.btn:active {
background-color: grey;
color: white;
}
.btn:hover {
background-color: grey;
color: white;
}
<body>
<div class="images">
<button type="button" class="btn prevBtn">Prev Btn</button>
<button type="button" class="btn nextBtn">Next Btn</button>
<h1 id="offers">Changing text</h1>
Links
<div class="dots">
<span id="dot1"></span>
<span id="dot2"></span>
<span id="dot3"></span>
</div>
</div>
</body>
First off, according to
https://developer.mozilla.org/en-US/docs/Web/CSS/:active
The :active CSS pseudo-class represents an element (such as a button) that is being activated by the user.
So if you want your dots to be active, you’ll have to write a different way of giving them an active state since they are currently <span> tags, I would recommend giving them a class of .active, and adding in Javascript code to add that class on to them, or adding in that style programmatically within the Javascript function.
Based on your other request though, you will most likely also have to make the dots an <a> tag or something along those lines so you can add functionality on to them to let clicking on the dots bring you to any slide. Something probably along the lines of:
function dot1Click() {
updateSlide(1);
updateText(1);
updateLink(1);
dot1.style.backgroundColor = #fff;
}
Then you should have something along the lines of what you want. I'll return to this question when I have more time to iron out a code snippet, but I wanted to give you something to help you get started!

How to change color of multiple webpages at once by javascript?

I'm trying to change color of a html webpage and it's working without any problem. But I've several webpages, and I want the colors of all pages to be changed on a press of a button, not just the one. There will a settings page where color options will be there where user can change the color of all webpages by choosing any color.
Code for changing color of single page:
$(document).ready(function() {
$(".btn").click(function() {
if ($(".container").hasClass("night")) {
$(".container").removeClass("night");
$(".btn").removeClass("btn-night").text("Night Mode Off");
$(".text").removeClass("text-night");
$(".p-sm").text("Turn on the night mode to change the background to dark.");
} else {
$(".container").addClass("night");
$(".btn").addClass("btn-night").text("Night Mode On");
$(".text").addClass("text-night");
$(".p-sm").text("Night mode is active. Turn off the night mode to change the background to light.");
}
});
});
body,
.container {
height: 100vh;
}
.container {
width: 100%;
display: flex;
justify-content: center;
animation-name: daytransition;
animation-duration: 3s;
}
#keyframes daytransition {
from {
background-color: #040018;
}
to {
background-color: #fff;
}
}
.text {
position: absolute;
top: 30%;
font-size: 20px;
text-align: center;
}
.p-lg {
font-size: 28px;
}
.p-sm {
margin: 30px;
}
.night {
animation-name: nighttransition;
animation-duration: 3s;
background-color: #040018 !important;
}
#keyframes nighttransition {
from {
background-color: #fff;
}
to {
background-color: #040018;
}
}
.text-night {
color: #c5b2cc;
}
.btn {
margin: 30px;
background-color: #6f6f8e !important;
color: #FBFFC9 !important;
}
.btn-night {
background-color: #FBFFC9 !important;
color: #6f6f8e !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<html>
<body>
<div class="container">
<div class="text">
<p class="p-lg">Demo of Day and Night Themes</p>
<button class="btn btn-lg">Night Mode Off</button>
<p class="p-sm">Turn on the night mode to change the background to dark.</p>
</div>
</div>
</body>
</html>
You want to persist state between different pages. You can do it with a session storage
sessionStorage.setItem('key', 'value');
sessionStorage.getItem('key');

Setting conditions for classList.toggle

I have a function that's triggered by onClick. Here's the example. I want to only be able to trigger the function 'slide1' when 'slide2' is not triggered. I tried setting up a conditional statement like this:
function slide1() {
btn1.classList.toggle('slide', btn2.className != 'slide');
}
I also tried an if statement like this:
function slide1() {
if(btn2.className != 'slide') {
btn1.classList.toggle('slide');
}
}
That didn't work either.
I just need a simple way to toggle classes if certain conditions are met; without jQuery or a library. Thanks.
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
function slide1() {
btn1.classList.toggle('slide');
}
function slide2() {
btn2.classList.toggle('slide');
}
* {
margin: 0;
transition: 1s ease;
-webkit-transition: 1s ease;
}
div {
width: 50%;
height: 100vh;
display: block;
position: absolute;
text-align: center;
cursor: pointer;
}
#btn1 {
background: blue;
}
#btn2 {
background: red;
left: 50%;
}
#btn1.slide {
width: 80%;
z-index: 999;
}
#btn2.slide {
width: 80%;
z-index: 999;
left: 20%;
}
<div id="btn1" onClick="slide1();">
left
</div>
<div id="btn2" onClick="slide2();">
right
</div>
UPDATE: Here is an expanded example of the problem I'm dealing with. There are several elements with classes that need to be toggled only under certain circumstances. If 'panel1' is triggered when 'panel2' has already been triggered, then 'panel1' will cover 'panel2'. and the same with 'panel3'.
To answer your question, the proper way to check if an element has a class in JavaScript is element.classList.contains.
So, in your example, you should replace the condition with
if(btn2.className.contains('slide')) {
...
}
As a sidenote, having different functions doing the exact same thing on different elements should be avoided, where possible. Instead of having two functions, you should have only one and use the click event's target:
let halves = document.querySelectorAll("div");
function slide(event) {
// remove `slide` class from both divs:
[].map.call(halves, function(half){
half.classList.remove('slide');
});
// add `slide` class to currently clicked div:
event.target.classList.add('slide')
}
* {
margin: 0;
transition: 1s ease;
-webkit-transition: 1s ease;
}
div {
width: 50%;
height: 100vh;
display: block;
position: absolute;
text-align: center;
cursor: pointer;
}
#btn1 {
background: blue;
}
#btn2 {
background: red;
left: 50%;
}
#btn1.slide {
width: 80%;
z-index: 999;
}
#btn2.slide {
width: 80%;
z-index: 999;
left: 20%;
}
<div id="btn1" onClick="slide(event);">
left
</div>
<div id="btn2" onClick="slide(event);">
right
</div>
On a different note, I assume you're aware the selectors used in both your question and my answer are outrageously generic and should never be used in production ready code.
And as a last note, your CSS is quite faulty but I'm not considering fixing it here, as it wouldn't help anyone except yourself, which goes against the first principle of SO: one answer should help multiple users having the same problem. Here's how I'd have coded your example:
let br = document.querySelector('#blueRed');
br.addEventListener('click', function(event) {
event.target.classList.toggle('slide');
[].map.call(br.querySelectorAll('div'), function(div) {
if (div !== event.target) {
div.classList.remove('slide');
}
});
})
body {
margin: 0;
}
#blueRed {
height: 100vh;
display: flex;
}
#blueRed div {
text-align: center;
display: flex;
align-items: center;
justify-content: center;
transition: flex-grow 1s cubic-bezier(0.4, 0, 0.2, 1);
flex-grow: 1;
background-color: blue;
color: white;
cursor: pointer;
}
#blueRed div:last-child {
background-color: red;
}
#blueRed div.slide {
flex-grow: 3;
}
<div id="blueRed">
<div>left</div>
<div>right</div>
</div>
Fiddle here. Should be prefixed.
I think I understand your objective...
I condensed the functions into one and start off one button with the className = 'slide'. If one button is clicked then the class slide always alternates between the two buttons.
Demo
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
function slide() {
btn1.classList.toggle('slide');
btn2.classList.toggle('slide');
}
* {
margin: 0;
transition: 1s ease;
-webkit-transition: 1s ease;
}
div {
width: 50%;
height: 100vh;
display: block;
position: absolute;
text-align: center;
cursor: pointer;
}
#btn1 {
background: blue;
}
#btn2 {
background: red;
left: 50%;
}
#btn1.slide {
width: 80%;
z-index: 999;
}
#btn2.slide {
width: 80%;
z-index: 999;
left: 20%;
}
<div id="btn1" onClick="slide();" class='slide'>
left
</div>
<div id="btn2" onClick="slide();">
right
</div>

Categories