How to display elements after button has been clicked? - javascript

I am creating a timer app, and when I click the start button I have the timer starting, but I want it to display the pause and play buttons. Pretty much I'm trying to do the reverse of what I did with the start button.
I have already tried setting it to
middlebuttons.style.display= "block"
but that doesn't work.
Javascript
var startButton = document.getElementById("start");
var startSound = document.getElementById("audio");
var timerSound = document.getElementById("timer");
var counter = document.getElementById("counter");
var middlebuttons = document.getElementsByClassName("middlebuttons");
function playAudio(){
startSound.play();
}
// Start button will disappear after click and countDown method will begin
function startTimer(){
startButton.style.display="none";
middlebuttons.style.display = "block";
countDown(1);
}
startButton.addEventListener('click', startTimer, playAudio);
HTML
<div class="container">
<div class="buttons">
<button id ="start" type="button" onclick="playAudio()">Start</button>
<audio id="audio">
<source src="clicksound.wav" type="audio/ogg ">
</audio>
<audio id="timer">
<source src="gong.mp3" type="audio/ogg ">
</audio>
</div>
<div id="counter">
</div>
<div class="middlebuttons" style="display: none">
<div class="row mr-3">
<button id="pause" >
<i class="fas fa-pause" style="font-size: 40px"></i>
</button>
<button id="play">
<i class="fas fa-play" style="font-size: 40px"></i>
</button>
</div>
</div>
</div>

You should iterate over the buttons and update the display property for each button :
for (var i = 0; i < middlebuttons.length; i++) {
middlebuttons[i].style.display = "block";
}
// or
middlebuttons.forEach(function(btn) {
btn.style.display = "block";
});

middlebuttons is a HTMLCollection (like an array) so you need to loop through it and apply the styles to each element:
[...middlebuttons].forEach(button => button.style.display = "block");
Older browsers:
Array.prototype.slice.call(middlebuttons).forEach(function(button) {
button.style.display = "block";
});
Also on older browsers (thanks connexo):
Array.prototype.forEach.call(middlebuttons, function(button) {
button.style.display = "block";
});

Related

pause the other playing video when play a new video jquery

I have many videos on one page.
I am using jquery to play and pause the videos
when I click on the play button it should play.
I did this using jquery. now I need to pause the other videos when I press play on the next or previous video. could you help me, please?
a screenshot is here
$('video').each(function(i, el) {
var p = $(el).parent();
$('.play-toggle', p).click(function(e) {
var button = $(this);
if (button.hasClass('playvideo')) {
button.removeClass('playvideo');
$('.play', button).hide();
$('.pause', button).show();
el.play();
} else {
button.addClass('playvideo');
$('.play', button).show();
$('.pause', button).hide();
el.pause();
}
});
});
$('video').each(function(i, el) {
var p = $(el).parent();
$('.sound-toggle', p).click(function(e) {
var button = $(this);
if (button.hasClass('playsound')) {
button.removeClass('playsound');
$('.play-sound', button).hide();
$('.pause-sound', button).show();
el.muted = true;
} else {
button.addClass('playsound');
$('.play-sound', button).show();
$('.pause-sound', button).hide();
el.muted = false;
}
});
});
<div class="video-player">
<video id="video1" width="420">
<source src="<?php echo base_url(); ?>assets/video/video.mp4" type="video/mp4">
Your browser does not support HTML video.
</video>
<div class="controls">
<button class="play-toggle playvideo">
<span class="play"><i class="fa-solid fa-play"></i></span>
<span class="pause" style="display: none;"><i class="fa-solid fa-pause"></i></span>
</button>
<button class="sound-toggle playsound">
<span class="play-sound"><i class="fa-solid fa-volume-high"></i></span>
<span class="pause-sound" style="display: none;"><i class="fa-solid fa-volume-xmark"></i></span>
</button>
</div>
</div>
To do what you require you can create a function which loops through all video elements and calls pause() on then. You can then call this function when a video is played.
In addition, note that instead of looping through the video elements on document.ready, you can instead attach event handlers to the media control buttons which use DOM traversal to find the related content when they are clicked. This has the benefit of simplfying the code, and maknig it easier to maintain. Try this:
let pauseAllVideos = excludeVideo => $('video').not(excludeVideo).each((i, v) => {
v.pause();
$(v).closest('.video-player').find('.play-toggle')
.removeClass('pause').addClass('play')
.find('i').removeClass('fa-pause').addClass('fa-play');
});
$('.play-toggle').on('click', e => {
let $button = $(e.currentTarget);
let video = $button.closest('.video-player').find('video')[0];
pauseAllVideos(video);
$button.toggleClass('play pause').find('i').toggleClass('fa-play fa-pause');
video[video.paused ? 'play' : 'pause']();
});
$('.sound-toggle').on('click', e => {
let $button = $(e.currentTarget);
let video = $button.closest('.video-player').find('video')[0];
$button.toggleClass('play-sound pause-sound').find('i').toggleClass('fa-volume-high fa-volume-xmark');
video.muted = !video.muted;
});
// This is just for this demo, so it doesn't deafen people :)
// it can be removed in your production version
$('video').each((i, v) => v.volume = 0.1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<p>Video #1:</p>
<div class="video-player">
<video id="video1" width="420">
<source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
Your browser does not support HTML video.
</video>
<div class="controls">
<button class="play-toggle playvideo">
<span class="play"><i class="fa-solid fa-play"></i></span>
<span class="pause" style="display: none;"><i class="fa-solid fa-pause"></i></span>
</button>
<button class="sound-toggle playsound">
<span class="play-sound"><i class="fa-solid fa-volume-high"></i></span>
<span class="pause-sound" style="display: none;"><i class="fa-solid fa-volume-xmark"></i></span>
</button>
</div>
</div>
<p>Video #2:</p>
<div class="video-player">
<video id="video2" width="420">
<source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
Your browser does not support HTML video.
</video>
<div class="controls">
<button class="play-toggle playvideo">
<span class="play"><i class="fa-solid fa-play"></i></span>
<span class="pause" style="display: none;"><i class="fa-solid fa-pause"></i></span>
</button>
<button class="sound-toggle playsound">
<span class="play-sound"><i class="fa-solid fa-volume-high"></i></span>
<span class="pause-sound" style="display: none;"><i class="fa-solid fa-volume-xmark"></i></span>
</button>
</div>
</div>

I want to change 2 images at once

I have images in imageBox1 and imageBox2 and when I click button, is there any way that I can change images in both boxes at the same time? with JS?
For instance, I when I click "hello", I want to make image1-1 and image2-1 display together, and when I click "world", they image1-2 and image2-2 should display together.
<div class = "Button">
<button type="button">hello</button>
<button type="button">world</button>
</div>
<div class = "imageBox1">
<img src="image1-1.jpg">
<img src="image1-2.jpg">
</div>
<div class = "imageBox2>
<img src="image2-1.jpg">
<img src="image2-2.jpg">
</div>
You can add an event listener to each button that gets the index of the button relative to the other buttons, loops through each child in each div and shows the img whose index is the same as the button's.
const divs = document.querySelectorAll('.image');
const buttons = document.querySelectorAll('button')
buttons.forEach((e, i) => e.addEventListener('click', function() {
divs.forEach((f) => [...f.children].forEach((g, i1) => g.style.display = i == i1 ? "block" : "none"))
}))
img {
display: none;
}
<div class="Button">
<button type="button">hello</button>
<button type="button">world</button>
</div>
<div class="imageBox1 image">
<img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
<!-- image1-1.jpg -->
<img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=96">
<!-- image1-2.jpg -->
</div>
<div class="imageBox2 image">
<img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=96">
<!-- image2-1.jpg -->
<img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
<!-- image2-2.jpg -->
</div>
It sounds like what you're asking for is a way to show or hide specific images depending on which button the user clicks. If so, you can definitely do this with JavaScript.
Here's a beginner-friendly example using your HTML.
// set up some variables to make the code easier to read
const helloBtn = document.getElementById("hello-button")
const worldBtn = document.getElementById("world-button")
const img1 = document.getElementById("image1")
const img2 = document.getElementById("image2")
const img3 = document.getElementById("image3")
const img4 = document.getElementById("image4")
// When the user clicks the "hello" button, run a function named handleHelloClick
helloBtn.addEventListener("click", handleHelloClick);
// When the user clicks the "world" button, run a function named handleWorldClick
worldBtn.addEventListener("click", handleWorldClick);
// this function handles the "hello" click
function handleHelloClick() {
img1.style.display = "none";
img2.style.display = "block";
img3.style.display = "block";
img4.style.display = "none";
}
// this function handles the "world" click
function handleWorldClick() {
img1.style.display = "block";
img2.style.display = "none";
img3.style.display = "none";
img4.style.display = "block";
}
<div class="buttons">
<button id="hello-button" type="button">hello</button>
<button id="world-button" type="button">world</button>
</div>
<div class="imageBox1">
<img id="image1" src="https://randomuser.me/api/portraits/women/75.jpg">
<img id="image2" src="https://randomuser.me/api/portraits/men/76.jpg">
</div>
<div class="imageBox2">
<img id="image3" src="https://randomuser.me/api/portraits/women/78.jpg">
<img id="image4" src="https://randomuser.me/api/portraits/men/80.jpg">
</div>
first hide them with css
then show them when clicking by js
const hello = document.getElementById("hello")
const world = document.getElementById("world")
hello.onclick= () => {
document.querySelectorAll(".first").forEach(el=> el.style.display = "block")
}
world.onclick= () => {
document.querySelectorAll(".second").forEach(el=> el.style.display = "block")
}
.first, .second {
display : none
}
<div class = "Button">
<button id="hello" type="button">hello</button>
<button id="world" type="button">world</button>
</div>
<div class = "imageBox1">
<img class="first" src="https://dummyimage.com/200x100/000/fff&text=first">
<img class="second" src="https://dummyimage.com/200x100/000/fff&text=second">
</div>
<div class = "imageBox2">
<img class="first" src="https://dummyimage.com/200x100/000/fff&text=first">
<img class="second" src="https://dummyimage.com/200x100/000/fff&text=second">
</div>

Remove appended element

When I type something in the first box, and click Next, the word I typed is inserted on my page. However, if I click Back and then click Next again, it is printed a second time.
I want the keyword appended after I've clicked Next to be deleted if I click Back so that if I click Next again it is printed only once (and updated if I have made any edit).
document.addEventListener("DOMContentLoaded", function() {
var stepOne = document.getElementsByClassName("step-1");
var stepTwo = document.getElementsByClassName("step-2");
var nextButton = document.getElementsByClassName("next");
var backButton = document.getElementsByClassName("back");
nextButton[0].onclick = function() {
stepOne[0].style.display = "none";
stepTwo[0].style.display = "block";
var inputKeyword = document.getElementById("inputJobTitle").value;
var newKeyword = document.createElement("p");
newKeyword.setAttribute("id", "retrievedField-1");
newKeyword.setAttribute("class", "retrievedFieldName");
newKeyword.innerText = inputKeyword;
newKeyword.setAttribute("id", "retrievedField-1");
newKeyword.setAttribute("class", "retrievedFieldName");
document.getElementById("retrievedFields").appendChild(newKeyword);
}
backButton[0].onclick = function() {
stepOne[0].style.display = "block";
stepTwo[0].style.display = "none";
}
})
.step-1 {
display: block;
}
.step-2 {
display: none;
}
<!--STEP 1-->
<div class="main step-1">
<div class="tab" id="tab-1">
<div class="inputFields">
<p id="jobtitle" class="inputFieldName">Job title</p>
<input type="search" id="inputJobTitle" class="inputBar" />
<p class="and">AND</p>
</div>
<div class="button">
<button class="next">Next ></button>
</div>
</div>
</div>
<!--STEP 2-->
<div class="main step-2">
<div class="tab" id="tab-1">
<div class="inputFields">
<div id="retrievedFields"></div>
<input type="search" class="inputBarAlternative" />
<div class="add">
<button class="addButton">+ Add Keyword</button>
<p id="addKeyword">
Add a skill or keyword that must be in your search results
</p>
</div>
</div>
<div class="buttons">
<button class="back">Back</button>
<button class="next">Next</button>
</div>
</div>
</div>
</body>
Each new click on the next button will trigger an append. So you just have to do the opposite of an append on the click on back. Just add this line in your onclick:
document.getElementById("retrievedFields").removeChild(document.getElementById("retrievedFields").lastElementChild);
You could also check to see if the element exists before you create it..
nextButton[0].onclick = function() {
stepOne[0].style.display = "none";
stepTwo[0].style.display = "block";
var inputKeyword = document.getElementById("inputJobTitle").value;
var newKeyword = document.getElementById("retrievedField-1")
if (!newKeyword) {
newKeyword = document.createElement("p");
newKeyword.setAttribute("id", "retrievedField-1");
newKeyword.setAttribute("class", "retrievedFieldName");
document.getElementById("retrievedFields").appendChild(newKeyword);
}
newKeyword.innerText = inputKeyword;
}

Is there a simpler way to write this code?

This code is designed to make the sections display = none/block onclick, is there an easier way to write it so it is simpler and less lines of code.
I feel like I shouldn't need to rewrite it each time per every link and there should be a way to have 1 script that will work with the whole navbar.
HTML
<header>
<img onclick="video()" id="logo" src="https://res.cloudinary.com/dnrojsaks/image/upload/v1587122319/Icons/logo-no-text_yyug8o.svg" alt="Mac Logo" style="width: 10vw;" />
<nav>
<a onclick="contact()">Contact</a>
<a onclick="work()">Work</a>
<a onclick="blog()">Blog</a>
</nav>
</header>
<main>
<section id="main" style="display: block;">
<h1>Mac Hooper</h1>
<p><strong>Developer.</strong><br> Progressive, modern web development.</p>
</section>
<section id="contact" style="display: none;">
macdevh#gmail.com
<div id="social">
<img src="https://res.cloudinary.com/dnrojsaks/image/upload/v1587129314/Icons/insta_maq9f2.svg" alt="Instagram Logo">
<img src="https://res.cloudinary.com/dnrojsaks/image/upload/v1587129314/Icons/glab_jumort.svg" alt="Twitter Logo">
<img src="https://res.cloudinary.com/dnrojsaks/image/upload/v1587129314/Icons/twit_t57gos.svg" alt="Gitlab Logo">
</div>
</section>
<section id="work" style="display: none;">
<div class="container">
<a href="https://lucycull.design" target="_blank" rel="noopener"><div class="card">
<img id="work-img" src="https://res.cloudinary.com/dnrojsaks/image/upload/v1587134668/Portfolio/lucy_ijnjoq.jpg" />
<h2>Lucy Cull</p>
</div></a>
</div>
</section>
<section id="blog" style="display: none;">
<div class="container">
<a href="https://medium.com/#machooper_69036/make-vscode-yours-e362dab48ff6" target="_blank" rel="noopener"><div class="card">
<img src="https://miro.medium.com/max/600/0*ZdpEvxpU6_SFxDzT.gif" />
<h2>Make VSCode Yours</p>
</div></a>
<a href="https://medium.com/#machooper_69036/my-setup-the-desk-5f4ed6824192" target="_blank" rel="noopener"><div class="card">
<img src="https://miro.medium.com/max/700/1*PFXyIbHjkQE-tGzlj6xMEA#2x.jpeg" />
<h2>My Desk</p>
</div></a>
<div class="card">
<img src="https://miro.medium.com/max/1400/1*qXN9PuwTmiHueFoeskJZnw.jpeg" />
<h2>My Tech Stack</p>
</a></div>
<div class="card">
<img src="https://miro.medium.com/max/700/1*PFXyIbHjkQE-tGzlj6xMEA#2x.jpeg" />
<h2>My Computer</p>
</div></a>
</div>
</section>
<section id="video" style="display:none;">
<video autoplay loop muted src="https://res.cloudinary.com/dnrojsaks/video/upload/v1587133353/Video/assets_img_header_bxtgiz.mp4"></video>
</section>
</main>
js
<script>
function video() {
var main = document.getElementById("main");
var video = document.getElementById("video");
var contact = document.getElementById("contact");
var work = document.getElementById("work");
var blog = document.getElementById("blog");
if (
video.style.display === "none") {
main.style.display = "none";
video.style.display = "block";
contact.style.display = "none";
work.style.display = "none";
blog.style.display = "none";
} else {
video.style.display = "none";
}
}
function contact() {
var main = document.getElementById("main");
var video = document.getElementById("video");
var contact = document.getElementById("contact");
var work = document.getElementById("work");
var blog = document.getElementById("blog");
if (
contact.style.display === "none") {
main.style.display = "none";
video.style.display = "none";
contact.style.display = "block";
work.style.display = "none";
blog.style.display = "none";
} else {
contact.style.display = "none";
}
}
function work() {
var main = document.getElementById("main");
var video = document.getElementById("video");
var contact = document.getElementById("contact");
var work = document.getElementById("work");
var blog = document.getElementById("blog");
if (
work.style.display === "none") {
main.style.display = "none";
video.style.display = "none";
contact.style.display = "none";
work.style.display = "block";
blog.style.display = "none";
} else {
work.style.display = "none";
}
}
function blog() {
var main = document.getElementById("main");
var video = document.getElementById("video");
var contact = document.getElementById("contact");
var work = document.getElementById("work");
var blog = document.getElementById("blog");
if (
blog.style.display === "none") {
main.style.display = "none";
video.style.display = "none";
contact.style.display = "none";
work.style.display = "none";
blog.style.display = "block";
} else {
blog.style.display = "none";
}
}
Just write a generic function that takes the section-name as parameter and then compute your style.display.
In such cases, I would always make use of combining classes and Id. Yes I know maybe someone has a better approach but this for me always is easier.
NB: I just wrote this here I didn't test it if it has bugs comment I will check it but it should work 100%.
Your style
<style>
.item
{
display: none;
}
</style
Your HTML
<nav>
<a class="link-item" id="contact">Contact</a>
<a class="link-item" id="work">Work</a>
<a class="link-item" id="blog">Blog</a>
</nav>
<span class="contact item">Put your video here</span>
<span class="work item">Your work content here</span>
<span class="blog item">Your blog content here</span>
Jquery
$(function()
{
$(".link-item").click(function(e)
{
var targetClassName = $(this).attr('id') //get the id of the clicked item so that you can
//display it later
$(".item").hide(function(e) //hide all item
{
$("."+targetClassName).show() //on callback display the item which was clicked using its classname
}
}
}
Disclaimer: I have done it with JQuery, you can convert this Jquery to Javascript. Your question was on Javascript so you might want JQuery or just do it with you Javascript but it should give you same results
I prefer JQuery(Javascript library) it's smaller and thus easily debugable. But if you want JS comment I can do it with Javascript

Show/Hide Div as Overlay

I am trying to create image overlays which can toggle on and off by clicking a button. Basically I have one main image then I want to click button A and have overlay A show up over the main image and click button B and have overlay A go away and show overlay B.
Currently I am trying to do this by creating a hidden div which has a background image on it. The current code works for the first button listed but not for any of the others.
<div class="hide schoolContent" id="schools"
</div>
<div class ="hide recreationContent" id="recreation">
</div>
<div class="hide restaurantsContent"id="restaurants">
</div>
<div class="hide banksContent" id="banks">
</div>
<div class="hide groceriesContent"id="groceries">
</div>
<div class="hide transportationContent"id="transportation">
</div>
<div class="hide libraryContent" id="library"></div>
<div>
<button class="alertName" name="schoolContent">Schools</button>
<button class="alertName" name="recreationContent">Recreation</button>
<button class="alertName" name="restaurantsContent">Restaurants</button>
<button class="alertName" name="banksContent">Banks</button>
<button class="alertName" name="groceriesContent">Groceries</button>
<button class="alertName" name="transportationContent">Study Transportation</button>
<button class="alertName" name="libraryContent">Library</button>
</div>
<script>var alertName = document.getElementsByClassName("alertName");
var myFunction = function() {
var hide = document.getElementsByClassName("hide");
for (var i =< 0; i < hide.length; i++) {
hide[i].style.display = "none";
}
var name = this.getAttribute("name");
var show = document.querySelector('.' + name);
if (show.style.display = "none") {
show.style.display = "block";
}
else {
show.style.display = "none";
}
};
for (var i = 0; i < alertName.length; i++) {
alertName[i].addEventListener('click', myFunction);
}</script>

Categories

Resources