Set display none after transition has finished with pure JS - javascript

How would I set display to none (and vice versa) only after the CSS transition has finished?
This is my current code but it doesn't work nicely – the transition isn't visible because I'm adding/removing display:none; straightaway.
<script type="text/javascript">
var mobile_menu = document.querySelector('#mobile-menu');
var mobile_menu_open = document.querySelector('#open-mobile-menu');
var mobile_menu_close = document.querySelector('#close-mobile-menu');
mobile_menu_open.addEventListener('click', function (event) {
mobile_menu.classList.remove('duration-100', 'ease-in', 'opacity-0', 'scale-95');
mobile_menu.classList.add('duration-200', 'ease-out', 'opacity-100', 'scale-100');
mobile_menu.removeAttribute('style');
});
mobile_menu_close.addEventListener('click', function (event) {
mobile_menu.classList.remove('duration-200', 'ease-out', 'opacity-100', 'scale-100');
mobile_menu.classList.add('duration-100', 'ease-in', 'opacity-0', 'scale-95');
mobile_menu.style.display = "none";
});
</script>
I can only think of setTimeout(); but in most cases it's not considered a proper solution but rather a dirty hack. Do I have any other options here?

You can use the transitionend event listener.
mobileMenu.addEventListener('transitionend', setDisplayNone);
After the animation is finished, it will execute setDisplayNone(). If you only want to run this once, you can add this at the end of the setDisplayNone function:
mobileMenu.removeEventListener('transitionend', setDisplayNone);
Example:
var div = document.querySelector('div')
function setDisplayNone() {
div.style.display = 'none'
}
document.querySelector('button').onclick = function() {
div.addEventListener('transitionend', setDisplayNone);
div.classList.add('transition')
}
.transition {
transition-duration: 3s;
opacity: 0;
}
<button>Click me!</button>
<br>
<div id='someDiv'>
Click the button!
</div>
This text will shift upwards once the div has display:none

Related

How to replicate jquery animation sequence in vanilla js/css

As the title says, I would like to replicate the animation bellow. the jquery API https://api.jquery.com/toggle/ decibels this default behavior as so:
easing (default: swing)
Type: String
A string indicating which easing function to use for the transition.
but I don't understand how the transition works. I have tried changing the opacity, translating the element, ect, but obviously no luck. If it is impossible to do this in a simple way without jquery, an answer for the transition effect without the toggle function is also acceptable (but not hide() and show() as I have already tried those and couldn't get it to work properly). And yes, I would prefer a swing transition if possible. any help is appreciated.
document.addEventListener('click', ()=>{
$('#elem').toggle('.hide');
});
.hide{
display:none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='elem' class= 'hide'>
easing text transion
</div>
I don´t know if I understood your question correctly but you want
document.addEventListener('click', ()=>{
$('#elem').toggle('.hide');
});
in normal JS?
You have two options: set an data attribute to #elem or you check if #elem has the class
.hide. But its easier to just add the css to the element
With data attribute:
<div id='elem' data-status='inv' class='hide'>
easing text transion
</div>
let toggleFunction = function() {
let elem = document.querySelector('#elem');
if (elem.dataset.status == "inv") {
elem.className = "";
elem.dataset.status = "vis";
} else if (elem.dataset.status == "vis") {
elem.className = "hide";
elem.dataset.status = "inv";
}
}
document.addEventListener('click', toggleFunction);
Or with css:
<div id='elem' style='display: none;'>
easing text transion
</div>
let toggleFunction = function() {
let elem = document.querySelector('#elem');
if (elem.style.display == 'none') {
elem.style.display = 'inherit';
} else {
elem.style.display = 'none';
}
}
document.addEventListener('click', toggleFunction);
If you still want the animation:
<div id='elem' style='height: 0px;'>
easing text transion
</div>
#elem {
transition: 1s ease-in-out all;
overflow-y: hidden;
}
let toggleFunction = function() {
let elem = document.querySelector('#elem');
if (elem.style.height == '0px') {
elem.style.height = '18px';
} else {
elem.style.height = '0px';
}
}
document.addEventListener('click', toggleFunction);
I hope I could help
You can toggle a class and use a css transition to do it
document.addEventListener('click', () => {
document.getElementById('elem').classList.toggle('no-height')
})
#elem {
max-height: 2em;
transition: max-height 0.5s ease-in-out;
overflow-y: hidden;
}
#elem.no-height {
max-height: 0;
}
<div id='elem'>
easing text transion
</div>

How to add transition into Javascript document.getElementById("myDIV").style.display = "none";

How can I add transition to document.getElementById("myDIV").style.display = "none"; I am currently working on a registration form in which if one input is of a certain value the other div is hidden but it looks so rough, Is there a way to add transitions into the following JS ?
<script type="text/javascript">
function myFunction() {
document.getElementById("myDIV").style.display = "none";
}
function hideshow(which){
if (!document.getElementById)
return
if (which.style.display=="block")
which.style.display="block"
else
which.style.display="block"
}
function myFunction1() {
document.getElementById("myDIV2").style.display = "none";
}
</script>
Create functions with parameters like
function hideDiv(div_id) {
document.getElementById(div_id).style.display = "none";
}
function showDiv(div_id) {
document.getElementById(div_id).style.display = "block";
}
The way to make a nice transition is to set style.display= "none" after you perform some kind of animation that removes the element from view.
You could:
Fade it out (set opacity to 0 - fade it with transition in CSS)
Slide it up/down/left/right (animation library or fancy CSS)
Do some other fancier animation (like bounce, shrink etc.)
Then, set style.display = "none"
The easiest way to do this (in my opinion) is with an animation library. I personally recommend VelocityJS because you don't need jQuery to run it.
I don't think there is anyway to do that with simple js, however I did it easily using JQuery
<script type="text/javascript">
$(document).ready(function(){
$("#myDIV").show();
$(document).on('click', '.married' , function() {
if (this.value == "never_married"){
$("#myDIV").hide('slow');
} else {
$("#myDIV").show('slow');
}
})
});
The reason is display isn't animated, setting it from block to none won't give you the result you're looking for.
A nice way to do this is to use CSS alongside JavaScript for the transition.
Add Transition to your myDIV style such as:
#myDIV {
opacity: 1;
transition: 1s ease;
}
#myDIV.hidden {
opacity: 0;
transition: 1s ease;
}
Then with JavaScript apply the hidden class to #myDiv and you'll get your animation.
Once the animation has finished then set el.style.display = 'none'; to make it disappear completely from view.

How do I make this fade in/out infinite?

this code fades in and fades out the div #shape while the start variable is true.
when i call the "start" method from event "click" the browser stops working because the while inside method is infinitive and "click" event does not finish until "start" method is done.
i want the method to run after the "click" event is finished.
what should i do?
CSS
#shape {
background-color:red;
width:100px;
height:100px;
display:none;
}
HTML
<div id="shape"></div>
<button id="startButton">start game!</button>
JS
var start = false;
$("#startButon").click(function () {
start = true;
startGame();
});
function startGame() {
while (start == true) {
$("#shape").fadeIn(1000).delay(1000).fadeOut(1000);
}
}
You don't need the flag, just make a recursive function. I changed the time to 300 milliseconds so you can see it easier
http://jsfiddle.net/zfbptz9c/
$("#startButton").click(function () {
startGame();
});
function startGame() {
$("#shape").fadeIn(300, function () {
$("#shape").fadeOut(300, function () {
startGame();
});
});
}
The div will fade in and on complete of the fade in, it will fade out then call the startGame function again and the entire process will repeat infinitely.
Alternatively, this can be achieved with css only if you only need to target modern browsers. I will put this fiddle link here, it is from a different question. I won't paste the code since you did not tag the question with css but the fiddle shows everything. I take no credit for it.
How can I create a looping fade-in/out image effect using CSS 3 transitions?
http://jsfiddle.net/FTLJA/261/
JavaScript runs in a single threaded environment, meaning once you enter an infinite loop, you can only quit the loop from within it. In synchronous execution, like the one you have here, no code outside the loop can affect the loop condition.
As far as your problem, people suggested solutions such as making a recursive function or using CSS3 transitions.
Another possible way could be to use timing functions like setTimeout and/or setInterval
The code bellow will make the fadeIn/Out happen after every second, after start button is clicked and until stop button is clicked.
var toggle = true; // flag for animation direction
var shape = $("#shape"); // so we don't select the shape each time we animate
var duration = 1000; // animation duration
var delay = 1000; // delay between animations
var timerId; // timer id returned by setInterval
// start animating the shape after the delay
$("#startButton").click(function() {
timerId = setInterval(animate, delay);
});
// stop animating the shape and hide it
$("#stopButton").click(function() {
clearInterval(timerId);
shape.css('display', 'none');
});
// function that animates the shape depending on the toggle flag
function animate() {
if (toggle) {
shape.fadeIn(duration);
toggle = false;
} else {
shape.fadeOut(duration);
toggle = true;
}
}
#shape {
background-color: red;
width: 100px;
height: 100px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="shape"></div>
<button id="startButton">start game!</button>
<button id="stopButton">stop game!</button>

Javascript hide and show a div in a loop for a text "blink" effect

I recently wanted to make a element in a div with the ID of "test" to have a "blink" effect like most text editors have where the cursor is hidden and then shown, then hidden and shown....(in a loop) I tried to recreate this effect but just couldn't get it to work. Please help!
Here is some code:
<div id="test">
<p> _ </p>
</div>
Something like this?
setInterval(function(){
$("#test p").toggle();
},3000);
blinks every 3 seconds.
Here's a concise, pure JavaScript way.
blink = setInterval(function () {
element = document.querySelector("#test p");
element.style.opacity = (element.style.opacity == 1 ? 0 : 1);
}, 500);
If you want to stop it, run clearInterval(blink).
Here's a working fiddle.
FIDDLE
setInterval(function(){
$("#test p").toggle();
},300);
Here is an example using Javascript
setInterval(function(){
var elem = document.querySelector("#test p");
if(isVisible(elem)) {
elem.style.display = 'none';
} else {
elem.style.display = 'block';
}
},500);
function isVisible(elem) {
return elem.offsetWidth > 0 || elem.offsetHeight > 0;
}
(Though knouroozi's answer will stop the contents from shifting around, so I'd suggest that.)
With JQuery it becomes simpler:
setInterval(function(){
$('#test p').toggle();
},500);
(stckrboy's answer covers toggling visibility, rather than 'display', which will prevent the content from shifting around.)
Here's an example using jQuery and setInterval
$(".crsr").each(function(){
var elem=$(this);
setInterval( function() {
if(elem.css('visibility')=='hidden') {
elem.css('visibility','visible')
} else {
elem.css('visibility','hidden')
}
},500)
});
jSFiddle
Throwing my approach into the ring. :) Set up a class that changes the visibility to hidden and then use setInterval and toggleClass to toggle the class off and on.
HTML
<div id="blinkingText">
Blink for me!
</div>
CSS
<style>
.blinkOn {visibility: hidden;}
</style>
JS
<script type="text/javascript">
$(document).ready(function(){
setInterval(function() {
$("#blinkingText").toggleClass("blinkOn");
},1000);
});
</script>

Showing/hiding <div> using javascript

For example I have a function called showcontainer. When I click on a button activating it, I want a certain div element, in this case <div id="container">, to fade in. And when I click it again, fade out.
How do I achieve this?
Note: I am not accustomed with jQuery.
So you got a bunch of jQuery answers. That's fine, I tend to use jQuery for this kind of stuff too. But doing that in plain JavaScript is not hard, it's just a lot more verbose:
var container = document.getElementById('container');
var btn = document.getElementById('showcontainer');
btn.onclick = function() {
// Fade out
if(container.style.display != 'none') {
var fade = setInterval(function(){
var opacity = parseFloat(container.style.opacity);
opacity = isNaN(opacity) ? 100 : parseInt(opacity * 100, 10);
opacity -= 5;
container.style.opacity = opacity/100;
if(opacity <= 0) {
clearInterval(fade);
container.style.opacity = 0;
container.style.display = 'none';
}
}, 50);
// Fade in
} else {
container.style.display = 'block';
container.style.opacity = 0;
var fade = setInterval(function(){
var opacity = parseFloat(container.style.opacity);
opacity = isNaN(opacity) ? 100 : parseInt(opacity * 100, 10);
opacity += 5;
container.style.opacity = opacity/100;
if(opacity >= 100) {
clearInterval(fade);
container.style.opacity = 1;
}
}, 50);
}
};
Check the working demo.
Provided you're not opposed to using jQuery per se, you can achieve this easily:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#showcontainer').click(function() {
$('#container').fadeToggle();
});
});
</script>
...
<div id="container">
...
</div>
...
<input type="button" id="showcontainer" value="Show/hide"/>
...
Note the missing http: in the beginning of the source of jQuery. With this trick the browser will automatically use http: or https: based on whether the original page is secure.
The piece of code after including jQuery assigns the handler to the button.
Best thing you could do is start now and get accustomed to jQuery.
The page http://api.jquery.com/fadeIn/ has all the example code that could be written here. Basically you want to have the call to fadeIn in your showcontainer function.
function showcontainer() {
$('#container').fadeIn();
}
You can have a look at jQuery UI Toggle.
The documentation turns the use of the library very simple, and they have many code examples.
You'd be as well off learning jQuery as it makes it a lot easier to do things!
From the sounds of it, you could have the container div already in the HTML but with a style of "display:none;", and then simply show it in your click event using (jQuery):
$('#container').fadeIn('slow', function() {
//Any additional logic after it's visible can go here
});

Categories

Resources