CSS Transition/Transform not working on clicking play button - javascript

I am following a tutorial(https://www.youtube.com/watch?v=QTHRWGn_sJw&t=119s) and I am unable to do the transition. The music-info box must pop up when the play button is clicked. The music-info has the title and the progress bar. I am very new to JS, would appreciate any help. Thank you
HTML is as
<div class="music-container" id="music-container">
<div class="music-info">
<h4 id="title">Alone
</h4>
<div class="progress-container" id="progress-container">
<div class="progress" id="progress">
</div>
</div>
</div>
<audio src="~/music/Alone.mp3" id="audio"></audio>
<div class="img-container">
<img src="~/image/Alone.jpg" alt="music-cover" id="cover" />
</div>
<div class="navigation">
<button id="prev" class="action-btn">
<i class="fas fa-backward"></i>
</button>
<button id="play" class="action-btn action-btn-big">
<i class="fas fa-play"></i>
</button>
<button id="next" class="action-btn">
<i class="fas fa-forward"></i>
</button>
</div>
</div>
CSS for the transition is as
.music-info {
background-color: rgba(255,255,255,0.5);
border-radius: 15px 15px 0 0;
position: absolute;
top: 0;
left: 20px;
padding: 10px 10px 10px 60px;
width: calc(100% - 40%);
opacity: 0;
transform: translateY(0%);
transition: transform 0.3s ease-in, opacity 0.3s ease-in;
text-align: center;
}
.music-info h4{
margin :0;
}
.music-container .play .music-info{
opacity:1;
transform: translateY(-100%);
}
.progress-container{
background:white;
border-radius: 5px;
cursor: pointer;
margin: 10px 0;
height:4px;
width:100%;
}
.progress{
background-color:#fe8daa;
border-radius:5px;
height:100%;
width:0;
transition: width 0.1s linear;
}
JS is as
function playSong() {
musicContainer.classList.add('play')
playBtn.querySelector('i.fas').classList.remove('fa-play')
playBtn.querySelector('i.fas').classList.add('fa-pause')
audio.play();
}
function pauseSong() {
musicContainer.classList.remove('play')
playBtn.querySelector('i.fas').classList.add('fa-play')
playBtn.querySelector('i.fas').classList.remove('fa-pause')
audio.pause();
}
//get duration in current time
function updateProgress(e) {
const {duration, currentTime} = e.srcElement
const progressPercent = (currentTime / duration) * 100
progress.style.width = '${progressPercent}%'
}
//pass an event object e
function setProgress(e) {
const width = this.clientWidth
const clickX = e.offsetX
alert("hi");
//console.log(clickX)
const duration = audio.duration
audio.currentTime = (clickX / width) * duration
}
//Event listeners
//play
playBtn.addEventListener('click', () => {
const isPlaying = musicContainer.classList.contains('play')
if (isPlaying) {
pauseSong()
}
else {
playSong()
}
})
//change song
prevBtn.addEventListener('click', prevSong)
nextBtn.addEventListener('click', nextSong)
audio.addEventListener('timeupdate', updateProgress)
progressContainer.addEventListener('click' , setProgress)

I found the error . It was in the
.music-container .play .music-info{
opacity:1;
transform: translateY(-100%);
}
There should not be any space between the .music-container and .play class. It should be like this
.music-container.play .music-info{
opacity:1;
transform: translateY(-100%);
}
Also I would add that ${progress-container}% should have backticks , which was a new concept for me. Otherwise the progress-container won't work.

Related

How can I get each of my modals to show correctly?

I know this code won't work in the current state because it will just select the first modal class. I have tried many variations of using querySelectorAll and forEach loops in the functions and event listeners but I can't seem to get it right.
How can I convert the current code to work with the different project card modals?
// Project card modals
const modal = document.querySelector('.modal')
const trigger = document.querySelector('.trigger')
const closeButton = document.querySelector('.close-button')
const body = document.querySelector('body')
function toggleModal() {
modal.classList.toggle('show-modal')
showModal()
}
function windowOnClick(event) {
if (this.event.target === modal) {
toggleModal()
showModal()
}
}
trigger.addEventListener('click', toggleModal)
closeButton.addEventListener('click', toggleModal)
window.addEventListener('click', windowOnClick)
// Disable body scroll with modal open
const showModal = function (e) {
if (modal.classList.contains('show-modal')) {
// Disable scroll
body.style.overflow = 'hidden'
} else {
// Enable scroll
body.style.overflow = 'auto'
}
}
<div class="projects-container">
<div class="projects-grid">
<div class="project-cell">
<div class="project-tile trigger">
<img Card Image />
</div>
<div class="modal">
<div class="modal-content">
<div class="close-button">×</div>
Modal Content
</div>
</div>
</div>
</div>
</div>
.modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(68, 71, 90, 0.8);
backdrop-filter: blur(20px) saturate(180%);
opacity: 0;
visibility: hidden;
transform: scale(1.1);
transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
z-index: 5;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 1rem 2rem;
width: 70%;
background-color: rgb(40, 42, 54, 0.8);
border-radius: 5px;
backdrop-filter: blur(20px) saturate(180%);
border: 2px solid transparent;
box-shadow: 0 0 5px 1px var(--dracula-background);
}
.close-button {
width: 1.5rem;
line-height: 1.5rem;
text-align: center;
border-radius: 3px;
color: black;
font-weight: 500;
background-color: rgba(255, 85, 85, 0.7);
cursor: url('../assets/images/icons/cursor-hand-white.png'), auto;
position: absolute;
right: 0;
top: 0;
transition: ease all 0.1s;
}
.show-modal {
opacity: 1;
visibility: visible;
transform: scale(1);
transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
You can use unique id attributes on your modal elements to differentiate them, and then use data attributes to target modals.
// Project card modals
const body = document.querySelector('body')
function toggleModal(modal) {
modal.classList.toggle('show-modal')
showModal(modal)
}
document.addEventListener('click', function(event) {
if (event.target.classList.contains('modal')) {
toggleModal(event.target)
showModal(event.target)
} else if (event.target.classList.contains('trigger')) {
toggleModal(document.getElementById(event.target.getAttribute('data-target')))
} else if (event.target.classList.contains('close-button')) {
toggleModal(document.getElementById(event.target.getAttribute('data-target')))
}
})
// Disable body scroll with modal open
const showModal = function(modal) {
if (modal.classList.contains('show-modal')) {
// Disable scroll
body.style.overflow = 'hidden'
} else {
// Enable scroll
body.style.overflow = 'auto'
}
}
.modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(68, 71, 90, 0.8);
backdrop-filter: blur(20px) saturate(180%);
opacity: 0;
visibility: hidden;
transform: scale(1.1);
transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
z-index: 5;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 1rem 2rem;
width: 70%;
background-color: rgb(40, 42, 54, 0.8);
border-radius: 5px;
backdrop-filter: blur(20px) saturate(180%);
border: 2px solid transparent;
box-shadow: 0 0 5px 1px var(--dracula-background);
}
.close-button {
width: 1.5rem;
line-height: 1.5rem;
text-align: center;
border-radius: 3px;
color: black;
font-weight: 500;
background-color: rgba(255, 85, 85, 0.7);
position: absolute;
right: 0;
top: 0;
transition: ease all 0.1s;
}
.show-modal {
opacity: 1;
visibility: visible;
transform: scale(1);
transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
<div class="projects-container">
<div class="projects-grid">
<div class="project-cell">
<div class="project-tile trigger" data-target="modal1">
<img Card Image /> trigger1
</div>
<div class="modal" id="modal1">
<div class="modal-content">
<div class="close-button" data-target="modal1">×</div>
Modal Content 1
</div>
</div>
</div>
<div class="project-cell">
<div class="project-tile trigger" data-target="modal2">
<img Card Image /> trigger2
</div>
<div class="modal" id="modal2">
<div class="modal-content">
<div class="close-button" data-target="modal2">×</div>
Modal Content 2
</div>
</div>
</div>
<div class="project-cell">
<div class="project-tile trigger" data-target="modal3">
<img Card Image /> trigger3
</div>
<div class="modal" id="modal3">
<div class="modal-content">
<div class="close-button" data-target="modal3">×</div>
Modal Content 3
</div>
</div>
</div>
</div>
</div>
I can definitely refactor this, but I was able to get it working by using the IDs. I also had to switch the querySelectorAll to getElementsByClassName because querySelectorAll will return a static collection, while getElementsByClassName returns a live collection.
// Project card modals
const body = document.querySelector('body')
const modal = document.getElementsByClassName('modal')
const trigger = document.getElementsByClassName('trigger')
const closeButton = document.getElementsByClassName('close-button')
// When the user clicks the project image, open the modal
trigger[0].onclick = function () {
modal[0].classList.toggle('show-modal')
if (modal[0].classList.contains('show-modal')) {
// Disable scroll
body.style.overflow = 'hidden'
} else {
// Enable scroll
body.style.overflow = 'auto'
}
}
trigger[1].onclick = function () {
modal[1].classList.toggle('show-modal')
if (modal[1].classList.contains('show-modal')) {
// Disable scroll
body.style.overflow = 'hidden'
} else {
// Enable scroll
body.style.overflow = 'auto'
}
}
trigger[2].onclick = function () {
modal[2].classList.toggle('show-modal')
if (modal[2].classList.contains('show-modal')) {
// Disable scroll
body.style.overflow = 'hidden'
} else {
// Enable scroll
body.style.overflow = 'auto'
}
}
trigger[3].onclick = function () {
modal[3].classList.toggle('show-modal')
if (modal[3].classList.contains('show-modal')) {
// Disable scroll
body.style.overflow = 'hidden'
} else {
// Enable scroll
body.style.overflow = 'auto'
}
}
// When the user clicks on (x), close the modal
closeButton[0].onclick = function () {
modal[0].classList.toggle('show-modal')
body.style.overflow = 'auto'
}
closeButton[1].onclick = function () {
modal[1].classList.toggle('show-modal')
body.style.overflow = 'auto'
}
closeButton[2].onclick = function () {
modal[2].classList.toggle('show-modal')
body.style.overflow = 'auto'
}
closeButton[3].onclick = function () {
modal[3].classList.toggle('show-modal')
body.style.overflow = 'auto'
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal[0]) {
modal[0].classList.toggle('show-modal')
body.style.overflow = 'auto'
}
if (event.target == modal[1]) {
modal[1].classList.toggle('show-modal')
body.style.overflow = 'auto'
}
if (event.target == modal[2]) {
modal[2].classList.toggle('show-modal')
body.style.overflow = 'auto'
}
if (event.target == modal[3]) {
modal[3].classList.toggle('show-modal')
body.style.overflow = 'auto'
}
}

How to make copy buttons alert for many button?

Hey am new to javascript but putting my all efforts I have written a javascript to copy the text inside a <p></p> element.
My javascript
function copyToClipboard(var1){
let val = document.getElementById(var1).innerHTML;
const selBox = document.createElement('textarea');
selBox.style.position = 'fixed';
selBox.style.left = '0';
selBox.style.top = '0';
selBox.style.opacity = '0';
selBox.value = val;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
}
But I needed a custom alert button when text is copied.
My html
<div class="Engstatus">
<h2 class="statusheading">Latest English Status</h2>
<div id="englishstatus">
<div class="latestatus">
<p id="p1">life os good when hou have books</p>
<button class="copystatus btn" onclick="copyToClipboard('p1')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
<div class="latestatus">
<p id="p2">Google is a open source library. It is a open source by lary page and sergy brime</p>
<button class="copystatus btn" onclick="copyToClipboard('p2')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
<div class="latestatus">
<p id="p3">Cat is better than dog</p>
<button class="copystatus btn" onclick="copyToClipboard('p3')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
</div>
</div>
I needed the <span class="copystatusalert">Copied!</span> to be visible for a few seconds when clicked the respective copy button and become vanished.
For more reference My Css
.copystatusalert{
position: relative;
background-color: var(--primary-color);
color: #ffffff;
margin-left: 10px;
padding: 3px 3px;
border-radius: 5px;
z-index: 2;
opacity: 1;
pointer-events: auto;
transition: opacity 0.4s, margin-top 0.4s;
}
.copystatusalert:before{
content:"";
position: absolute;
height: 10px;
width: 10px;
background-color: var(--primary-color);
left: -5px;
transform: translateY(50%) rotate(45deg);
z-index: -1;
top: 17%;
}
Here is a short addition to the copyToClipboard function in order to just change the .copystatusalert color...
function copyToClipboard(var1) {
let val = document.getElementById(var1).innerHTML;
const selBox = document.createElement('textarea');
selBox.style.position = 'fixed';
selBox.style.left = '0';
selBox.style.top = '0';
selBox.style.opacity = '0';
selBox.value = val;
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
document.body.removeChild(selBox);
// to change the color of .copystatusalert
let copyStatus = document.getElementById(var1).closest(".latestatus").querySelector(".copystatusalert")
copyStatus.style.color = "black";
// Change the color again in 800 milliseconds
setTimeout(function(){
copyStatus.style.color = "white";
},800)
}
.copystatusalert {
position: relative;
background-color: var(--primary-color);
color: #ffffff;
margin-left: 10px;
padding: 3px 3px;
border-radius: 5px;
z-index: 2;
opacity: 1;
pointer-events: auto;
transition: opacity 0.4s, margin-top 0.4s;
}
.copystatusalert:before {
content: "";
position: absolute;
height: 10px;
width: 10px;
background-color: var(--primary-color);
left: -5px;
transform: translateY(50%) rotate(45deg);
z-index: -1;
top: 17%;
}
<div class="Engstatus">
<h2 class="statusheading">Latest English Status</h2>
<div id="englishstatus">
<div class="latestatus">
<p id="p1">life os good when hou have books</p>
<button class="copystatus btn" onclick="copyToClipboard('p1')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
<div class="latestatus">
<p id="p2">Google is a open source library. It is a open source by lary page and sergy brime</p>
<button class="copystatus btn" onclick="copyToClipboard('p2')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
<div class="latestatus">
<p id="p3">Cat is better than dog</p>
<button class="copystatus btn" onclick="copyToClipboard('p3')">Copy</button>
<span class="copystatusalert">Copied!</span>
</div>
</div>
</div>
Now... Since you are "new to javascript", I suggest you to close look at this solution.
The intend is to create ONE function which will apply to as many as you want status elements... and avoid managing the unique id for all <p>... And to "reduce" the redondant HTML markup (buttons and alert spans).
Please look at the comments below for step-by-step details and feel free for questions. ;)
// The animation delay for the "copied" alert
let copyAlertAnimationDelay = 400; // ms
// Get all the status elements
let status = document.querySelectorAll(".status");
// For each status, add a button with its event listener
status.forEach(function(elem) {
// Create the button
let btn = document.createElement('button');
btn.setAttribute("class", "copystatus btn");
btn.innerText = "Copy";
// Append the button
elem.after(btn);
// Set the button event listener
btn.addEventListener("click", function() {
// Get the status
let statusToCopy = elem.innerText;
// Create the temporary textarea to copy the text
const selBox = document.createElement('textarea');
// Use a class instead of multiple element.style.property changes
selBox.setAttribute("class", "hiddenCopy");
selBox.value = statusToCopy;
// Append, copy and remove.
document.body.appendChild(selBox);
selBox.focus();
selBox.select();
document.execCommand('copy');
selBox.remove();
// create a "Copied!" element.
let alert = document.createElement("span");
alert.innerText = "Copied!";
alert.setAttribute("class", "copystatusalert");
// Use the copyAlertAnimationDelay variable to set the CSS transition
// So it matches the setTimeout delay below
alert.style.transition = `all ${copyAlertAnimationDelay/1000}s`;
// The animation timeouts
// Show
this.after(alert);
setTimeout(function() {
alert.style.opacity = 1;
}, 1)
// Hide
// Change opacity
setTimeout(function() {
alert.style.opacity = 0;
// Remove element
setTimeout(function() {
document.querySelector(".copystatusalert").remove();
}, copyAlertAnimationDelay);
}, copyAlertAnimationDelay * 3) // 3 times the animation delay...
});
});
body {
--primary-color: #a7d8f2; /* ADDED */
}
.copystatusalert {
position: relative;
background-color: var(--primary-color);
/*color: #ffffff; REMOVED */
margin-left: 10px;
padding: 3px 3px;
border-radius: 5px;
z-index: 2;
opacity: 0;
/* opacity was 1 */
pointer-events: auto;
/*transition: opacity 0.4s, margin-top 0.4s; REMOVED */
}
.copystatusalert:before {
content: "";
position: absolute;
height: 10px;
width: 10px;
background-color: var(--primary-color);
left: -5px;
transform: translateY(50%) rotate(45deg);
z-index: -1;
top: 17%;
}
/* ADDED */
.hiddenCopy {
position: "fixed";
left: 0;
top: 0;
opacity: 0;
}
<div class="Engstatus">
<h2 class="statusheading">Latest English Status</h2>
<div id="englishstatus">
<div class="latestatus">
<p class="status">life os good when hou have books</p>
</div>
<div class="latestatus">
<p class="status">Google is a open source library. It is a open source by lary page and sergy brime</p>
</div>
<div class="latestatus">
<p class="status">Cat is better than dog</p>
</div>
</div>
</div>
Toast is used to display tasks like this.
Use this code
function myFunction() {
var x = document.getElementById("message");
x.className = "show";
// you can set the time here//
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
body {
font-family: 'Oswald', sans-serif;
}
#message {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
left: 50%;
bottom: 30px;
font-size: 17px;
}
#message.show {
visibility: visible;
-webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
/* The animation*/
#-webkit-keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
#keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
#-webkit-keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
#keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
<button onclick="myFunction()">Copy</button>
<!-- This is the toast message -->
<div id="message">Text is copied!!</div>

How to fade out a colored box slowly?

New to javascript and I got this working, a box turning white, but tried various way to set a fade out time unsuccessfully.
document.getElementById("button3").addEventListener("click", function(){
document.getElementById("box").style.backgroundColor = "white"; });
Thanks
You can use your code and add some css to animate the transitions:
document.getElementById("button3").addEventListener("click", function(){
document.getElementById("box").style.backgroundColor = "white";
})
#box{
background: gold;
width: 300px;
height: 300px;
transition: all 1s;
}
<button id="button3">click</button>
<div id="box">
test
</div>
If you include transition: all 1s; to your class every css change will be animate, you can configure duration change 1s to desired transition duration.
Try This Method
<style>
body {
transition: background-color 2s cubic-bezier(1, 1, 1, 1);
transition-delay: 0s;
}
</style>
<script>
var colors = ["red", "orange", "yellow", "green", "blue", "purple"];
var currentIndex = 0;
setInterval(function() {
document.body.style.cssText = "background-color: " + colors[currentIndex];
currentIndex++;
if (currentIndex == undefined || currentIndex >= colors.length) {
currentIndex = 0;
}
}, 1000);
</script>
To fade out a colored box slowly follow the below 2 steps:
Use CSS transition property (allows the changes in CSS property values to occur smoothly over a specified duration).
Use JavaScript (element.style.display = "none") to remove the fadeout element from document flow.
// Get all elements with class="close"
let close = document.querySelectorAll(".close");
for (let i = 0; i < close.length; i++) {
close[i].onclick = function() {
// Get the parent of <span class="close"> (<div class="alert">)
let div = this.parentElement;
// Set the opacity of div to 0
div.style.opacity = "0";
// Hide the div after 600ms (the same amount of milliseconds it takes to fade out)
setTimeout(function() { div.style.display = "none"; }, 600);
}
}
* {box-sizing: border-box;}
/* Style Alert Message */
.alert {
position: relative;
padding: 1rem 1.9rem 1rem 1rem;
margin-bottom: 1rem;
font-size: 1rem;
font-family: sans-serif;
border: 1px solid transparent;
border-radius: .25rem;
transition: opacity .6s linear;
}
/* Contextual Classes for alert */
.alert-primary {
color: #004085;
background-color: #cce5ff;
border-color: #b8daff;
}
.alert-secondary {
color: #383d41;
background-color: #e2e3e5;
border-color: #d6d8db;
}
.alert-warning {
color: #856404;
background-color: #fff3cd;
border-color: #ffeeba;
}
.alert-danger {
color: #721c24;
background-color: #f8d7da;
border-color: #f5c6cb;
}
/* Style Close Button */
.close {
position: absolute;
top: 0;
right: 0;
padding: 1rem;
color: inherit;
cursor: pointer;
font-size: inherit;
font-weight: 900;
background-color: transparent;
border: 0;
}
<p>Click on the × icon to fadeout the box:</p>
<div class="alert alert-primary">
<b>Primary!</b> This alert box indicates an important action.
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="alert alert-warning">
<b>Warning!</b> This alert box could indicate a warning that might need attention.
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="alert alert-danger">
<b>Danger!</b> This alert box could indicate a dangerous or potentially negative action.
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="alert alert-secondary">
<b>Secondary!</b> This alert box indicates a less important action.
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>

How to add this class on my button click using javascript?

Here, I have done slide code. My when I click on the left and right button.next and previous button.
I want when I click on next button arrow slide show move on the right side with some effect and when I click on previous button arrow is should move left side with some effect.
I used animated fadeInLeft and animated fadeInRight. but i don't know how i add this class ..
I want when i click on left button my class this class (animated fadeInLeft) add and when i click on previous button my class( animated fadeInRight) should add.
What should i do to add these class when i click on left and right button click.
Here, is my code please review it.
var divMain = document.getElementById("slide");
console.log(divMain)
var align = divMain.getAttribute("type");
console.log(align)
if(align == "slideshow") {
var timeline = document.getElementById('slide');
timeline.insertAdjacentHTML("afterbegin",'<a class="left animated fadeInLeft color_arrow carousel-control" href="#myCarousel" onclick = "plusDivs(-1)" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span><span class="sr-only">Previous</span></a>');
timeline.insertAdjacentHTML('afterbegin',' <a class="right color_arrow animated fadeInRight carousel-control" href="#myCarousel" onclick = "plusDivs(1)" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span><span class="sr-only">Next</span></a>');
var slideIndex = 2;
showDivs(slideIndex);
function plusDivs(sliderItem) {
showDivs(slideIndex += sliderItem);
}
function showDivs(sliderItem) {
let i;
let sliderData = document.getElementsByTagName("section");
if (sliderItem > sliderData.length) {slideIndex = 1}
if (sliderItem < 1) {slideIndex = sliderData.length}
for (i = 1; i < sliderData.length; i++) {
sliderData[i].classList.add('hide')
sliderData[i].classList.remove('active')
}
sliderData[slideIndex-1].classList.remove('hide')
sliderData[slideIndex-1].classList.add('active')
}
}
div[type="slideshow"] > section:not(.hide) {
margin: auto;
width: 900px;
z-index: 100;
border-left: 4px solid #00BCD4;
min-height:250px;
background-color: #b3e5fc2b;
border-radius: 4px;
margin-bottom: 55px;
position: relative;
top: 50px;
box-shadow: rgb(136, 136, 136) 3px 3px 1px;
}
div[type="slideshow"] > section:not(.hide) > header {
font-weight: 600;
color: cadetblue;
transform: translate(93px, 32px);
font-size: 34px;
font-family: arial;
position: relative;
}
div[type="slideshow"] > section:not(.hide) > article {
transform: translate(87px,39px);
color: black;
font-size: 22px;
font-family: arial;
position: relative;
padding: 10px;
word-wrap: break-word;
}
.active{
-webkit-animation: fadein 2s
-moz-animation: fadein 2s;
-ms-animation: fadein 2s;
-o-animation: fadein 2s;
animation: fadein 2s;
opacity: 1 !important;
}
.hide{opacity: 0; min-height: 0 !important; margin: 0 !important;}
.hide header, .hide article{display: none;}
#keyframes fadein {
0% { opacity: 0 }
50% { opacity: 0.5 }
100% {opacity: 1}
}
<div type='slideshow' id='slide'>
<section class='sectionDiv'>
<header>Title One</header>
<article>Content</article>
</section>
<section class='sectionDiv'>
<header>Title Two</header>
<article>Content</article>
</section>
<section class='sectionDiv'>
<header>Title Three</header>
<article>Content</article>
</section>
<section class='sectionDiv'>
<header>Title Four</header>
<article>Content</article>
</section>
</div>
These class i want add **animated fadeInLeft and animated fadeInRight**
Help will be aprreciated.
I am not sure about your question... Since there is no fadeInLeft class in there.
But, by just changing the initial slideIndex and the loop start value of i, making it all zero-based, there is an interesting result which probably is what you wish to achieve.
var slideIndex = 1; // Intead of 2
And:
for (i = 0; ... // Instead of 1
See the difference below::
var divMain = document.getElementById("slide");
console.log(divMain)
var align = divMain.getAttribute("type");
console.log(align)
if(align == "slideshow") {
var timeline = document.getElementById('slide');
timeline.insertAdjacentHTML("afterbegin",'<a class="left animated fadeInLeft color_arrow carousel-control" href="#myCarousel" onclick = "plusDivs(-1)" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span><span class="sr-only">Previous</span></a>');
timeline.insertAdjacentHTML('afterbegin',' <a class="right color_arrow animated fadeInRight carousel-control" href="#myCarousel" onclick = "plusDivs(1)" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span><span class="sr-only">Next</span></a>');
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(sliderItem) {
showDivs(slideIndex += sliderItem);
}
function showDivs(sliderItem) {
let i;
let sliderData = document.getElementsByTagName("section");
if (sliderItem > sliderData.length) {slideIndex = 1}
if (sliderItem < 1) {slideIndex = sliderData.length}
for (i = 0; i < sliderData.length; i++) {
sliderData[i].classList.add('hide')
sliderData[i].classList.remove('active')
}
sliderData[slideIndex-1].classList.remove('hide')
sliderData[slideIndex-1].classList.add('active')
}
}
div[type="slideshow"] > section:not(.hide) {
margin: auto;
width: 900px;
z-index: 100;
border-left: 4px solid #00BCD4;
min-height:250px;
background-color: #b3e5fc2b;
border-radius: 4px;
margin-bottom: 55px;
position: relative;
top: 50px;
box-shadow: rgb(136, 136, 136) 3px 3px 1px;
}
div[type="slideshow"] > section:not(.hide) > header {
font-weight: 600;
color: cadetblue;
transform: translate(93px, 32px);
font-size: 34px;
font-family: arial;
position: relative;
}
div[type="slideshow"] > section:not(.hide) > article {
transform: translate(87px,39px);
color: black;
font-size: 22px;
font-family: arial;
position: relative;
padding: 10px;
word-wrap: break-word;
}
.active{
-webkit-animation: fadein 2s
-moz-animation: fadein 2s;
-ms-animation: fadein 2s;
-o-animation: fadein 2s;
animation: fadein 2s;
opacity: 1 !important;
}
.hide{opacity: 0; min-height: 0 !important; margin: 0 !important;}
.hide header, .hide article{display: none;}
#keyframes fadein {
0% { opacity: 0 }
50% { opacity: 0.5 }
100% {opacity: 1}
}
<div type='slideshow' id='slide'>
<section class='sectionDiv'>
<header>Title One</header>
<article>Content</article>
</section>
<section class='sectionDiv'>
<header>Title Two</header>
<article>Content</article>
</section>
<section class='sectionDiv'>
<header>Title Three</header>
<article>Content</article>
</section>
<section class='sectionDiv'>
<header>Title Four</header>
<article>Content</article>
</section>
</div>
These class i want add **animated fadeInLeft and animated fadeInRight**

JavaScript - add transition between display:none and display:block

I am using JavaScript to toggle notification like below.
How can I add transition between display: block and display: none;
I don't want to add an external library like jQuery because I am only going to be using the toggle effect alone.
var btn = document.querySelector('button');
btn.addEventListener('click', function(){
var hint = document.getElementById('hint');
if(hint.style.display == 'none'){
hint.style.display = 'block';
}
else{
hint.style.display = 'none';
}
});
div#hint{
background: gold;
color: orangered;
padding: .5em;
font-weight: bold;
}
<div id='hint'>
<p>This is some hint on how to be safe in this community </p>
<p>This is another hint on how to be safe in this community </p>
</div>
<button> show hint </button>
I know I can use jQuery to achieve this like below.
$(document).ready(function(){
$('button').click(function(){
$('#hint').toggle('slow');
});
});
div#hint{
background: gold;
color: orangered;
padding: .5em;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='hint'>
<p>This is some hint on how to be safe in this community </p>
<p>This is another hint on how to be safe in this community </p>
</div>
<button> show hint </button>
Can I make the button moves up and down gradually while the #hint is being toggle like in the jQuery example above? I don't want the button to jump from one position to another.
#vothaison's suggestion: CSS transitions
Technically, #vothaison wanted to use setInterval as opposed to setTimeout, but I don't see the need for that. It's just more work.
var hint = document.getElementById('hint');
var btn = document.getElementById('btn_show');
btn.addEventListener('click', function(){
var ctr = 1;
hint.className = hint.className !== 'show' ? 'show' : 'hide';
if (hint.className === 'show') {
hint.style.display = 'block';
window.setTimeout(function(){
hint.style.opacity = 1;
hint.style.transform = 'scale(1)';
},0);
}
if (hint.className === 'hide') {
hint.style.opacity = 0;
hint.style.transform = 'scale(0)';
window.setTimeout(function(){
hint.style.display = 'none';
},700); // timed to match animation-duration
}
});
#hint {
background: yellow;
color: red;
padding: 16px;
margin-bottom: 10px;
opacity: 0;
transform: scale(0);
transition: .6s ease opacity,.6s ease transform;
}
<div id="hint" style="display: none;">
<p>This is some hint on how to be safe in this community </p>
<p>This is another hint on how to be safe in this community </p>
</div>
<button id="btn_show"> Show hint </button>
Using CSS animations
var hint = document.getElementById('hint');
var btn = document.getElementById('btn_show');
btn.addEventListener('click', function(){
hint.className = hint.className !== 'show' ? 'show' : 'hide';
if (hint.className === 'show') {
setTimeout(function(){
hint.style.display = 'block';
},0); // timed to occur immediately
}
if (hint.className === 'hide') {
setTimeout(function(){
hint.style.display = 'none';
},700); // timed to match animation-duration
}
});
#-webkit-keyframes in {
0% { -webkit-transform: scale(0) rotate(12deg); opacity: 0; visibility: hidden; }
100% { -webkit-transform: scale(1) rotate(0); opacity: 1; visibility: visible; }
}
#keyframes in {
0% { transform: scale(0) rotate(12deg); opacity: 0; visibility: hidden; }
100% { transform: scale(1) rotate(0); opacity: 1; visibility: visible; }
}
#-webkit-keyframes out {
0% { -webkit-transform: scale(1) rotate(0); opacity: 1; visibility: visible; }
100% { -webkit-transform: scale(0) rotate(-12deg); opacity: 0; visibility: hidden; }
}
#keyframes out {
0% { transform: scale(1) rotate(0); opacity: 1; visibility: visible; }
100% { transform: scale(0) rotate(-12deg); opacity: 0; visibility: hidden; }
}
#hint {
background: yellow;
color: red;
padding: 16px;
margin-bottom: 10px;
}
#hint.show {
-webkit-animation: in 700ms ease both;
animation: in 700ms ease both;
}
#hint.hide {
-webkit-animation: out 700ms ease both;
animation: out 700ms ease both;
}
<div id="hint" style="display: none;">
<p>This is some hint on how to be safe in this community </p>
<p>This is another hint on how to be safe in this community </p>
</div>
<button id="btn_show"> Show hint </button>
Using vanilla JavaScript
There are many, many ways to do this sort of thing with vanilla JavaScript, so here's a quick sketch of one way:
// you may need to polyfill requestAnimationFrame
var hint = document.getElementById('hint');
var btn = document.getElementById('btn_show');
btn.addEventListener('click', function(){
var ctr = 0;
hint.className = hint.className !== 'show' ? 'show' : 'hide';
if (hint.className === 'show') {
window.setTimeout(function(){
hint.style.display = 'block';
fadein();
},0); // do this asap
}
if (hint.className === 'hide') {
fadeout();
window.setTimeout(function(){
hint.style.display = 'none';
},700); // time this to fit the animation
}
function fadein(){
hint.style.opacity = ctr !== 10 ? '0.'+ctr : 1;
hint.style.transform = ctr !== 10 ? 'scale('+('0.'+ctr)+')' : 'scale(1)';
ctr++;
if (ctr < 11)
requestAnimationFrame(fadein);
else
ctr = 0;
}
function fadeout(){
hint.style.opacity = 1 - ('0.'+ctr);
hint.style.transform = 'scale('+(1 - ('0.'+ctr))+')';
ctr++;
if (ctr < 10)
requestAnimationFrame(fadeout);
else
ctr = 0;
}
});
#hint {
background: yellow;
color: red;
padding: 16px;
margin-bottom: 10px;
opacity: 0;
}
<div id="hint" style="display: none;">
<p>This is some hint on how to be safe in this community </p>
<p>This is another hint on how to be safe in this community </p>
</div>
<button id="btn_show"> Show hint </button>
Say what you want about GreenSock, Velocity.js, jQuery, etc — they all trivialise this process of showing and hiding of things. Why not just borrow the show and hide functions from jQuery's source code?
see my example below:
var btn = document.querySelector('button');
var hint = document.getElementById('hint');
var height = hint.clientHeight;
var width = hint.clientWidth;
console.log(width + 'x' + height);
// initialize them (within hint.style)
hint.style.height = height + 'px';
hint.style.width = width + 'px';
btn.addEventListener('click', function(){
if(hint.style.visibility == 'hidden'){
hint.style.visibility = 'visible';
//hint.style.opacity = '1';
hint.style.height = height + 'px';
hint.style.width = width + 'px';
hint.style.padding = '.5em';
}
else{
hint.style.visibility = 'hidden';
//hint.style.opacity = '0';
hint.style.height = '0';
hint.style.width = '0';
hint.style.padding = '0';
}
});
div#hint{
background: gold;
color: orangered;
padding: .5em;
box-sizing: border-box;
overflow: hidden;
font-weight: bold;
transition: height 1s, width 1s, padding 1s, visibility 1s, opacity 0.5s ease-out;
}
<div id='hint'>
<p>This is some hint on how to be safe in this community </p>
<p>This is another hint on how to be safe in this community </p>
</div>
<button> show hint </button>
Hi I dont use display: block to display:none but changing the opacity, height and padding instead
please review this one:
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
var hint = document.getElementById('hint');
if (hint.classList.contains('h-hide')) {
hint.classList.remove('h-hide');
} else {
hint.classList.add('h-hide');
}
});
div#hint {
display: block;
background: gold;
color: orangered;
padding: .5em;
font-weight: bold;
transition: .5s all linear;
opacity: 1;
overflow: hidden;
height: 100px;
}
#hint.h-hide {
padding: 0;
opacity: .25;
height: 0;
}
<div id='hint'>
<p>This is some hint on how to be safe in this community</p>
<p>This is another hint on how to be safe in this community</p>
</div>
<button>show hint</button>
the drawback for this approach is we have to keep tract of the div#hint height and change it using javascript if needed.
var btn = document.querySelector('button');
btn.addEventListener('click', function(){
var hint = document.getElementById('hint');
if(hint.style.visibility == 'hidden'){
hint.style.visibility = 'visible';
hint.style.opacity = '1';
}
else{
hint.style.visibility = 'hidden';
hint.style.opacity = '0';
}
});
div#hint{
background: gold;
color: orangered;
padding: .5em;
font-weight: bold;
transition: visibility 1s, opacity 0.5s linear;
}
<div id='hint'>
<p>This is some hint on how to be safe in this community </p>
<p>This is another hint on how to be safe in this community </p>
</div>
<button> show hint </button>
I think using visibility over display is better option
Without using css3 transition, you can use js setInterval to change some css property of the div, such as:
Change opacity from 0 to 1
Change height from 0 to full height
Change width from 0 to full width
Initially, you should have display: none; opacity: 0; height: 0; width: 0'
Then you have to change display: none to display: block; before you use setInterval to change other properties.
(I guess you know how to hide the div)
You can also use setTimeout(), with a trick of recursive.
Try something like this:
var btn = document.querySelector('button');
btn.addEventListener('click', function(){
var hint = document.getElementById('hint');
hint.classList.toggle("hide");
});
.hint{
background: gold;
color: orangered;
padding: .5em;
font-weight: bold;
visibility: visible;
opacity: 1;
max-height: 500px;
transition: visibility 0s, opacity 0.3s, max-height 0.6s linear;
}
.hide {
visibility: hidden;
opacity: 0;
max-height: 0px;
transition: max-height 0.3s, opacity 0.3s, visibility 0.3s linear;
}
<div id='hint' class="hint">
<p>This is some hint on how to be safe in this community </p>
<p>This is another hint on how to be safe in this community </p>
</div>
<button> show hint </button>
I have also tried to do this
please have a look if it can help you
var btn = document.querySelector('button');
var hint = document.getElementById('hint');
hint.style.opacity = 1;
hint.style.transition = "opacity 1s";
btn.addEventListener('click', function(){
if(hint.style.opacity == 0 || hint.style.opacity==''){
hint.style.opacity = 1;
}
else{
hint.style.opacity = 0;
}
});
let redBox = document.getElementById('redBox');
let blueBox = document.getElementById('blueBox');
let [redButton, blueButton] = document.querySelectorAll('button'); //Destructuring
redButton.addEventListener('click', () => {
smoothDisplayNone(redBox);
});
blueButton.addEventListener('click', () => {
smoothDisplayNone(blueBox);
});
//By using smoothDisplayNone() function, you can add this effect to whatever element you want.
function smoothDisplayNone(selectedElement){
if(!selectedElement.classList.contains('animationDisplayNone')){
selectedElement.classList.add('animationDisplayNone');
selectedElement.classList.remove('animationDisplayBlock');
}
else{
selectedElement.classList.remove('animationDisplayNone');
selectedElement.classList.add('animationDisplayBlock');
}
}
#redBox{
width: 200px;
height: 200px;
background-color: red;
}
#blueBox{
width: 200px;
height: 200px;
background-color: blue;
}
.animationDisplayNone{
animation: smoothDisplayNone 0.5s linear forwards;
}
.animationDisplayBlock{
animation: smoothDisplayBlock 0.5s linear forwards;
}
/*You should set the width and height according to the size of your element*/
#keyframes smoothDisplayBlock{
0% { opacity: 0; width: 0px; height: 0px; }
25% { opacity: 0.25; }
50% { opacity: 0.50; }
75% { opacity: 0.75; }
100% { opacity: 1; width: 200px; height: 200px; }
}
#keyframes smoothDisplayNone {
0% { opacity: 1; width: 200px; height: 200px; }
25% { opacity: 0.75; }
50% { opacity: 0.50; }
75% { opacity: 0.25; }
100% { opacity: 0; width: 0px; height: 0px; }
}
<div id="redBox"></div>
<div id="blueBox"></div>
<button type="button" style="margin-top:10px;">Red</button>
<button type="button" style="margin-top:10px;">Blue</button>
The code looks long at first glance but it is actually very simple to understand. I used the power of css animation to create a smooth effect.
You can use smoothDisplayNone() function easily.

Categories