Using Buttons To Show Particular Divs and hide the rest - javascript

OK, I'm still mind boggled. I've done a ton here, and still can't see why the things aren't loading. I thought maybe it had to do with CORS, so I added a cookies rule to the script, but even then I find this weird, because I was able to display the podcast player locally just fine when I wasn't trying to hide and activate one or the other.
The code seems to be just fine however, I can't seem to pick out the problem.
document.cookie = "cookiename=cookievalue; SameSite=None; Secure; path="
// Add active class to default player and button
document.getElementById("player1-button").classList.add("active");
document.getElementById("player1").classList.add("active");
// Add event listeners to the buttons to listen for clicks and execute a function
document.getElementById("player1-button").addEventListener("click", function() {
//Remove active class from the current player and button
document.getElementById("player2-button").classList.remove("active");
document.getElementById("player2").classList.remove("active");
// Add active class to player1 and player1-button
document.getElementById("player1").classList.add("active");
this.classList.add("active");
});
document.getElementById("player2-button").addEventListener("click", function() {
//Remove active class from the current player and button
document.getElementById("player1-button").classList.remove("active");
document.getElementById("player1").classList.remove("active");
// Add active class to player2 and player2-button
document.getElementById("player2").classList.add("active");
this.classList.add("active");
});
This is my new javascript.
Furthermore, here's the related CSS:
.podcast-player div:not(.active) {
display: none;
}
.podcast-player div.active {
display: block;
}
and as well, the HTML for the player element:
<div class="podcast-player">
<!-- add the 2 embedded players here -->
<div id="player1">
<div id='buzzsprout-small-player'></div>
<script type='text/javascript' charset='utf-8' src='https://www.buzzsprout.com/2107108.js?container_id=buzzsprout-small-player&player=small'></script>
</div>
<div id="player2">
<div id='buzzsprout-large-player'></div>
<script type='text/javascript' charset='utf-8' src='https://www.buzzsprout.com/2107108.js?container_id=buzzsprout-large-player&player=large'></script>
</div>
</div>
I've been combing through this for the past few hours, and to me it all seems like it should work. I'm baffled.

Can you check the following code, and let me know if this is what you were looking for?
<!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>
<style>
.player {
display: none;
}
.player.active {
display: block;
}
</style>
</head>
<body>
<div class="player active" id='buzzsprout-small-player'></div>
<div class="player" id='buzzsprout-large-player'></div>
<button disabled id="small-player-button">Activate Player Small</button>
<button id="large-player-button">Activate Player Large</button>
<script type='text/javascript' charset='utf-8'
src='https://www.buzzsprout.com/2107108.js?container_id=buzzsprout-large-player&player=large'></script>
<script type='text/javascript' charset='utf-8'
src='https://www.buzzsprout.com/2107108.js?container_id=buzzsprout-small-player&player=small'></script>
<script>
// Add event listeners to the buttons to listen for clicks and execute a function
document.getElementById("small-player-button").addEventListener("click", function () {
//Remove active class from the large player
document.getElementById("buzzsprout-large-player").classList.remove("active");
// Add active class to small player
document.getElementById("buzzsprout-small-player").classList.add("active");
// Enable large player button
document.getElementById("large-player-button").disabled = false;
// Disable small player button
this.disabled = true;
});
document.getElementById("large-player-button").addEventListener("click", function () {
//Remove active class from the small player
document.getElementById("buzzsprout-small-player").classList.remove("active");
// Add active class to large player
document.getElementById("buzzsprout-large-player").classList.add("active");
// Enable small player button
document.getElementById("small-player-button").disabled = false;
// Disable large player button
this.disabled = true;
});
</script>
</body>
</html>

Related

Trying to animate dynamically created elements with GSAP

I am trying to animate elements that are added to the DOM via javascript with GSAP.
Here is the MRE:
HTML
<!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">
<link rel="stylesheet" href="css/style.css">
<title>Recipe Search</title>
</head>
<body>
<section id="searchBackgroundImage">
<section id="searchSection">
<h1>What's In The Fridge</h1>
<button type="button" id="btn">Seach!</button>
<div id="recipeContainer"></div>
<div id="test"><h2>Test</h2></div>
</section>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.4/gsap.min.js"></script>
<script text="text/javascript" src="js/main.js"></script>
</body>
</html>
CSS
h2 {
opacity: 0.1;
}
JS
document.querySelector('#btn').addEventListener('click',() => {
getRecipe();
timeline.play();
});
function getRecipe(){
let recipeTitles = `<h2>Cheese Burger</h2><h2>Ham Sandwich</h2>`
document.querySelector('#recipeContainer').innerHTML = recipeTitles
}
const timeline = gsap.timeline({
duration: 1,
paused: true
});
timeline
.to(
'#recipeContainer h2', {
opacity: 1
}
)
So I would like to change the opacity of the h2s.
It is not working because the h2s don't exist when the page first loads.
I was hoping that setting it to paused and only having it play on click would fix the problem, but unfortunately not.
If I change
timeline
.to(
'#recipeContainer h2', {
opacity: 1
}
)
to
timeline
.to(
'#test h2', {
opacity: 1
}
)
Then it works fine for that element.
So it has to be the element being dynamically created but I haven't been able to find a solution.
I've been reading the docs and it seems like I might be able to use TimelineMax and onComplete but I can't figure out how to implement it here.
Here is the codepen:
https://codepen.io/acodeaday/pen/RwJbrWa
Thank you for any help.
The problem here is that the javascript file is compiled before the click event. This means that the browser encounters the following error before the event listener is called.
Solution: Defining the timeline.to() properties inside the event listener will circumvent this problem.
document.querySelector("#btn").addEventListener("click", () => {
getRecipe();
timeline.to("#recipeContainer h2", {
opacity: 1,
});
timeline.play();
});

Implementing buttons using css and jQuery

I'm a complete beginner.
I'm trying to implement two buttons that change colors (green to blue) with one click (and once the implementation is completed, integrating it to the actual website).
The buttons need to do the following:
Both the buttons are initially green. Once a button is clicked, it should change its color to blue.
And after that same button is clicked the second time, it should revert back to its original color which is green.
Only one button out of the two can be blue at a time. Which means as soon as the user clicks button-2 after clicking button-1, the button-1 should turn back to green, and button-2 to blue.
So far, I can implement the first and third ones, but not the middle one.
Here are the necessary codes for it:
$(document).ready(function () {
$('#btn1').click(function(){
$('.btn').css('background-color', 'green');
$(this).css('background-color', 'blue');
})
$('#btn2').click(function(){
$('.btn').css('background-color', 'green');
$(this).css('background-color', 'blue');
})
});
.btn {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!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">
<link rel="stylesheet" href="/styles.css">
<title>Document</title>
</head>
<body>
<button id = "btn1" class = "btn">Button</button>
<button id = "btn2" class = "btn">Button</button>
<!--<button id = "btn3" class = "btn" onclick="changeColor()">Button</button>
<button id = "btn4" class = "btn" onclick="changeColor()">Button</button> -->
<script src="/jquery-3.6.1.min.js"></script>
<script src="/index.js"></script>
</body>
</html>
To do what you require you can toggle a class on the clicked element which sets its background to blue. At the same time this class will be removed from all other buttons.
The code can also be simplified by using a single event handler bound to all .btn elements, instead of separate ones for each id.
jQuery($ => {
let $btns = $('.btn').on('click', e => {
let $btn = $(e.target).toggleClass('clicked');
$btns.not($btn).removeClass('clicked');
});
});
.btn {
background-color: green;
}
.btn.clicked {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Button</button>
<button class="btn">Button</button>
Rory's answer is probably the best, but I think this one is more easy to understand for a beginner (although less elegant):
$('.btn').click(function(){
if ($(this).hasClass('clicked')) {$(this).removeClass('clicked');}
else {$('.btn').removeClass('clicked'); $(this).addClass('clicked');}
});
.btn {
background-color: green;
}
.clicked {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Button</button>
<button class="btn">Button</button>

How to still play the video after pausing once but after control is being enabled, the addeventlistener is not working at all?

I am a beginner in JavaScript, I want to play and pause the video whenever the user clicks the video element, but when in my code once user clicks again the video element the video gets paused and control gets enabled but when again user clicks the paused video after the controls being enabled the addEventListener() is not working at all it seems, can anyone please tell why this is happening, I saw that after I remove line videoelement.controls = true; then all works fine, but I want to know why this is happening and is there any way that with controls enabled it works fine enough
let videoelement = document.querySelector('.videos')
videoelement.addEventListener('click', function (e) {
console.log(videoelement.paused)
if (videoelement.paused) {
console.log("pause hai ")
videoelement.play();
videoelement.controls = null;
videoelement.firstChild.nodeValue = 'Play';
} else {
console.log("play ho gya")
videoelement.pause();
videoelement.controls = true;
videoelement.firstChild.nodeValue = 'Pause';
}
e.preventDefault();
})
body
{
background-color: blueviolet
}
.videos
{
width: 50%;
margin:10% 20%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Player</title>
<link rel="stylesheet" href="videplayercss.css">
</head>
<body>
<div class="videoplayer">
<video src="anyvideo.mp4" autoplay class="videos"> </video>
</div>
<script src="videoplayerjs.js"></script>
</body>
</html>

How do you add an eventListener to a htmlCollection that will change the display of another element?

Aim : to click box(x) and it opens pop-up(x);
This is my first javascript project, i've done loads of research but i'm still struggling.
The reason I'm using a getElementByClassList is because it returns an array. I would then take the array and get the corresponding pop-up box and change its display settings in css.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box1 boxes"></div>
<div>
<div class="box2 boxes"></div>
<div class="box3 boxes"></div>
</div>
<div class="popup1"></div>
<div class="popup2"></div>
<div class="popup3"></div>
<script>
const boxes = document.getElementsByClassName('boxes');
// i would like to add an eventlistener for each object in the array
//
</script>
</body>
</html>
document.addEventListener("DOMContentLoaded", () => { // wait till all the DOM is Loaded, since querying objects at this point they are not there yet.
const boxes = document.querySelectorAll(".boxes"); // or use getElementsBy...
boxes.forEach(box => { // we are adding a click event listener to each box
box.addEventListener('click', (e) => {
const boxNumber = e.target.className.match(/box(\d)/)[1]; // through a regex we get the box number of the className
const popup = document.querySelector(`.popup${boxNumber}`);
console.log(popup)
// do whatever you want with the popup, add a className or whatever to open it :)
});
});
});
.boxes {
height: 20px;
width: 50px;
background: red;
margin: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box1 boxes"></div>
<div>
<div class="box2 boxes"></div>
<div class="box3 boxes"></div>
</div>
<div class="popup1"></div>
<div class="popup2"></div>
<div class="popup3"></div>
<script>
const boxes = document.getElementsByClassName('boxes');
// i would like to add an eventlistener for each object in the array
//
</script>
</body>
</html>
The method getElementsByClassName() indicats that return an array of html objects, in case there exists elements with passed css class.
The first step you have to iterate trough the array object:
for (int index = 0; index < boxes.length; index++)
{
}
Within for loop access to each element and assign the eventent handle
boxes[index].addEventListnener('click', function()
{
});
Within the body of declared anonymous function add your code.
You can try :
const boxes = document.getElementsByClassName('boxes');
const popups = document.querySelectorAll(".popups");
boxes.forEach((box,index)=>box.addEventListener("click",()=>{
const popup = popups[index]; // This gets the popup based on the box index so you will have to setup the html so that the popup for box1 is the first then popup for box2 second etc.
// Add styles to popup to display it
// Example
popup.style.opacity = "1";
})
Visit the 'mdn docs' or 'youtube' to learn how the array methods like forEach work

Transition and mouseover

Working with JavaScript it seems there may be an issue where transition causes an issue with the closing of a menu. In this MWE the menu on the left opens as it should by either clicking the menu icon or through mouseover. It also closes properly with mouseout. However, when attempting to close by clicking the close icon there is some discrepancy: it works erratically. Could this be due to the transition effect? It seems to close properly when the transition is removed. How could the transition be retained while also making the menu close properly both by mouseout and clicking the relevant icon?
Thanks.
MVE:
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#title {text-align:right}
#menu {display:block;height:100%;width:180px; position:fixed;top:0;left:-120px; overflow:visible;background:lightgrey;transition:.3s}
#menuicon, #closeicon {position:absolute;top:1em;left:150px;cursor:pointer}
#closeicon {display:none}
</style>
<script>
function menutoggle(x) {
if (x) {
document.getElementById('menu').style.left = '0';
document.getElementById('menuicon').style.display = 'none';
document.getElementById('closeicon').style.display = 'block';
} else {
document.getElementById('menu').style.left = '-120px';
document.getElementById('menuicon').style.display = 'block';
document.getElementById('closeicon').style.display = 'none';
}
}
</script>
</head>
<body>
<div id="menu" onmouseover="menutoggle(1)" onmouseout="menutoggle()">
<span id="closeicon" onclick="menutoggle()">X</span>
<span id="menuicon" onclick="menutoggle(1)">=</span>
</div>
<p id="title">Title</p>
</body></html>``

Categories