Remove a DIV with a delay Javascript - javascript

this is my first question so forgive me if I don't apply the correct etiquette.
I have a javascript function that hides a div with a fade.
function fadeOut(cloudChatHide)
{
"use strict";
cloudChatHide.onclick = function()
{
if(cloudChatHide.className)
{
cloudChatHide.className = '';
}
else
{
cloudChatHide.className = 'fadeout';
RemoveCloudChat();
}
};
}
However this code doesn't remove the DIV which is the RemoveCloudChat Function. Which looks like this:-
function RemoveCloudChat()
{
"use strict";
cloudChatHide.remove();
cloudChatHide.className ='fadeout';
}
What I really want to do is fade the div automatically after a few seconds and then REMOVE it.
The reason I need to REMOVE the div from the window is that its an overlaid div and I need to access the content underneath the 'cloudChatHide' div.
Any help / instruction wouild be gratefully received as I am not the greatest Javascript developer.
Thanks.

You can use CSS transitions to smoothly fade out the element and listen for the transitionend event to remove the element when the transition has finished.
See this jsFiddle.
The transition is defined with this CSS:
div {
opacity: 1;
transition: opacity 1s;
}
div.fade-out {
opacity: 0;
}
As soon as you add the fade-out class to a div it will smoothly reduce its opacity over a period of 1 second. This can be done with the following JavaScript, no jQuery required:
function fadeOutAndRemove(element) {
element.classList.add('fade-out');
element.addEventListener('transitionend', function () {
element.parentNode.removeChild(element);
});
}
If you want to start the fadeout transition automatically after a fixed delay you could call fadeOutAndRemove after a timeout
window.setTimeout(fadeOutAndRemove.bind(this, elementToHide), 3000)
or add a delay to the transition
transition: opacity 1s 3s;
and initalise the element with the fade-out class
<div class="fade-out"></div>

If you could use JQuery, it will really simple, see following:
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery.min.js"></script>
</head>
<body>
<div class="fadeout">I'LL DISAPPEAR IN 3 SECONDS</div>
</body>
<script>
function fadeOut()
{
$(".fadeout").fadeToggle(500, "swing",function(){
this.remove();
});
}
var delay = 3000; //3 seconds
setTimeout(fadeOut, delay);
</script>
</html>
When the fade action is completed the div will be removed.
I hope it helps you, bye.

Brilliant result from Alessandro Maglioccola
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery.min.js"></script>
</head>
<body>
<div class="fadeout">I'LL DISAPPEAR IN 3 SECONDS</div>
</body>
<script>
function fadeOut()
{
$(".fadeout").fadeToggle(500, "swing",function(){
this.remove();
});
}
var delay = 3000; //3 seconds
setTimeout(fadeOut, delay);
</script>
</html>

Here's a way to do it without Jquery. I'm setting the opacity to 0 waiting 300ms using a setTimeout then do the reverse if it's already hidden.
hideMe = function(selector, self) {
var elem = document.querySelector(selector);
if (self.innerHTML == "Hide") {
elem.classList.add("fade");
setTimeout(function() {
elem.classList.add("hidden");
self.innerHTML = "Show";
}, 300)
} else {
elem.classList.remove("hidden");
setTimeout(function() {
elem.classList.remove("fade");
self.innerHTML = "Hide";
}, 300)
}
}
body {
margin: 0;
}
.header {
height: 100px;
width: 100%;
background: steelblue;
}
#vanish {
transition: all 300ms cubic-bezier(.25, .8, .25, 1);
}
.redsquare {
width: 100%;
height: 225px;
background: tomato;
opacity: 1;
}
.hidden {
height: 0px;
width: 0px;
}
.fade {
opacity: 0;
}
button {
width: 100%;
height: 25px;
border: 0px;
outline: none;
cursor: pointer;
}
<div class="header"></div>
<button onclick='hideMe("#vanish",this)'>Hide</button>
<div id="vanish" class="redsquare"></div>
<div class="header"></div>

Related

Why am i getting this behaviour in js where I apply style changes through js. Shouldn't in both cases transition take place? [duplicate]

This question already has answers here:
css transition doesn't work if element start hidden
(5 answers)
CSS transition doesn't start/callback isn't called
(3 answers)
Closed 1 year ago.
Here the transition works just fine. But if I don't use setTimeout and straightforwardly make the transform the div is already at the end of transition.
function move(x, y, delay) {
let el = document.getElementById('myDiv');
el.style.transform = `translateX(${x}%)`
el.style.transition = `transform ${delay}s linear`
setTimeout(() => {
el.style.transform = `translateX(${y}%)`
}, 1000)
}
move(100, 200, 1)
.myDiv {
height: 50px;
width: 50px;
background: blue;
}
<div class="myDiv" id="myDiv">
Content
</div>
In This case div is already at the end of transition. But js being synchronous all these instructions should be executed sequentially then why the entire transition is not taking place in this case?
function move(x, y, delay) {
let el = document.getElementById('myDiv');
el.style.transform = `translateX(${x}%)`
el.style.transition = `transform ${delay}s linear`
el.style.transform = `translateX(${y}%)`
}
move(100, 200, 1)
.myDiv {
height: 50px;
width: 50px;
background: blue;
}
<div class="myDiv" id="myDiv">
Content
</div>
It is kinda weird to me still but you need to "refresh" the CSS changes.
To do that, you need to read an element's property, for example el.innerText, before applying your new style.
function move(x,y,delay){
let el = document.getElementById('myDiv');
el.style.transform = `translateX(${x}%)`
el.style.transition = `transform ${delay}s linear`
el.innerText;
el.style.transform = `translateX(${y}%)`
}
move(100,200,1)
.myDiv{
height: 50px;
width: 50px;
background: blue;
}
<div class="myDiv" id="myDiv">
Content
</div>
I don't know what's causing this however, maybe someone here could explain it.
CSS keyframes can be used here as:
#myDiv{
animation: slidein 1s forwards
}
#keyframes slidein {
from {
transform: translateX(100%);
}
to {
transform: translateX(200%);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.myDiv{
height: 50px;
width: 50px;
background: blue;
}
</style>
</head>
<body>
<div class="myDiv" id="myDiv">
Content
</div>
</body>
</html>

Transitioning Visibility/Opacity w/in JS

I have an alert box that I want to use sessionStorage so that it only appears once. When the user clicks to close the alert, I want the box to disappear (display:none) but fade-out.
I read that you have to use two different functions - one that is activated when clicked and starts the transition and another the adds the 'display' style once transitioned. However, I can't get that to work:
<style>
.ddAlert {
padding: 20px;
box-sizing: border-box;
background-color: #f0ad4e;
color: #fff;
opacity: 1;
transition: opacity 1s;
}
.hide {
opacity: 0;
display: none;
}
</style>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
let dismissed = sessionStorage.getItem("dismissed");
let alertDiv = document.getElementById("alert");
let dismissButton = document.getElementById("dismiss");
if (!dismissed) {
alertDiv.classList.remove("hide");
}
alertDiv.addEventListener("click", function() {
this.style.display = "block";
}.bind(alertDiv));
alertDiv.addEventListener("transitionend", function() {
if (this.className == "hide") {
this.style.display = "none";
}
sessionStorage.setItem("dismissed", true);
}.bind(alertDiv));
});
</script>
<div class="ddAlert hide" id="alert">
SOME ANNOYING ALERT HERE!
<button type="button" id="dismiss">X</button>
</div>
You are on the right track. Instead of listening on click on the alert, use the button as I assume it is there for that reason. When clicking the button the .hide class should be added to the alert. This will start the transition from opacity: 1; to opacity: 0;.
I suggest that instead of using inline-styles, that you stick to classes. Inline styles are hard to overwrite and prevents you from utilizing the full power of CSS. So I've added some classes in there to help you out.
Try out the example below.
<div class="ddAlert hidden" id="alert">
SOME ANNOYING ALERT HERE!
<button type="button" id="dismiss">X</button>
</div>
.ddAlert {
display: block;
transition: opacity 1s;
}
.hide {
opacity: 0;
}
.hidden {
display: none;
}
document.addEventListener("DOMContentLoaded", function() {
let dismissed = sessionStorage.getItem("dismissed");
let alertDiv = document.getElementById("alert");
let dismissButton = document.getElementById("dismiss");
if (!dismissed) {
alertDiv.classList.remove("hidden");
}
dismissButton.addEventListener("click", function() {
alertDiv.classList.add("hide");
});
alertDiv.addEventListener("transitionend", function({ target }) {
if (target.classList.contains("hide")) {
target.classList.add("hidden");
}
sessionStorage.setItem("dismissed", true);
});
});
This answer greatly lends from this SO question titled CSS3 Transition - Fade out effect which notes
When showing the element (by switching to the visible class), we want
the visibility:visible to kick in instantly, so it’s ok to transition
only the opacity property. And when hiding the element (by switching
to the hidden class), we want to delay the visibility:hidden
declaration, so that we can see the fade-out transition first. We’re
doing this by declaring a transition on the visibility property, with
a 0s duration and a delay.
I chose not to mark this question as a duplicate because it also involves the transitionend event. Additionally, I've focused only on the essence of the transition, with a minimal illustration.
The crucial element is the .dismissed-saved class.
let alertDiv = document.getElementById("alert");
let dismissButton = document.getElementById("dismiss");
dismissButton.addEventListener("click", function() {
// kick in the transition
alertDiv.classList.add("dismissed-saved");
// *this is where state should be committed
});
alertDiv.addEventListener("transitionend", function({
target
}) {
if (target === alertDiv) {
// clean up and show a nifty text message illustrating the event handler.
target.classList.add("hidden");
target.classList.remove("dismissed-saved");
document.getElementById("dismissed").classList.remove('hidden');
}
});
.ddAlert {
padding: 20px;
box-sizing: border-box;
background-color: #f0ad4e;
color: #fff;
opacity: 1;
}
.hidden {
display: none;
}
.dismissed-saved {
visibility: hidden;
opacity: 0;
transition: visibility 0s 2s, opacity 2s linear;
}
<div class="ddAlert" id="alert">
SOME ANNOYING ALERT HERE!
<button type="button" id="dismiss">X</button>
</div>
<div id="dismissed" class="hidden">
Dismissed!
</div>
Good luck!

Javascript adding class with transitions

I have a test code like this:
<html>
<head>
<style>
.jeden {
display: none;
color: red;
height: 0px;
}
.dwa {
display: block;
}
.trzy {
color: blue;
opacity: 0.5;
transition: all 2s;
height: 50px;
background-color: yellow;
}
</style>
</head>
<body>
<p class="jeden"> Wczoraj </p>
<button>ddd</button>
<span id="hej">hej</span>
<script>
function dodaj(callback) {
document.getElementsByTagName("p")[0].classList.add("dwa");
alert(1);
alert(2);
callback();
}
function dodajKlase() {
document.getElementsByTagName("p")[0].classList.add("trzy");
}
document.getElementsByTagName("button")[0].addEventListener("click", function() {
dodaj(dodajKlase)
})
</script>
</body>
</html>
which I'm playing with, cause I don't understand a certain mechanism. In the above code the transition in trzy class works fine. But if I delete alert(1) and alert(2) the transition doesn't work.
Generaly, I'm trying to solve an issue:
Add a class with a display: block to an element - element appears,
Then add a class with transitions via callback function.
but this model doesn't work (I'm not quite sure I understand callback functions correctly in that case).
You should force a browser redraw in your dodaj function, there are several ways to do it, one would be: element.getBoundingClientRect()
Read more about it here: gist
<html>
<head>
<style>
.jeden {
display: none;
color: red;
height: 0px;
}
.dwa {
display: block;
}
.trzy {
color: blue;
opacity: 0.5;
transition: all 2s;
height: 50px;
background-color: yellow;
}
</style>
</head>
<body>
<p class="jeden"> Wczoraj </p>
<button>ddd</button>
<span id="hej">hej</span>
<script>
function dodaj(callback) {
var element = document.querySelector("p.jeden");
element.classList.add("dwa");
element.getBoundingClientRect();
callback();
}
function dodajKlase() {
document.getElementsByTagName("p")[0].classList.add("trzy");
}
document.getElementsByTagName("button")[0].addEventListener("click", function() {
dodaj(dodajKlase)
})
</script>
</body>
</html>
Little side note: You should force yourself to code in english, so other people can understand your function and variable names.
Wrap the callback into a setTimeout() and it works.
function dodaj(callback) {
document.getElementsByTagName("p")[0].classList.add("dwa");
setTimeout(callback, 100);
}

Changing the hide show toggle effect?

I have an element that works just fine with the following code. It's an object #obj1 that is hidden when loading the page, but appears when clicking on #obj2.
#obj1{
position:fixed;
width:100px;
bottom:180px;
right:100px;
display:none;
}
$("#obj1").hide();
$("#obj2").show();$('#obj2').toggle(function(){
$("#obj1").slideDown(function(){});
},function(){
$("#obj1").slideUp(function(){});
});
but I would like to have it like this:
$("#obj1").css({"opacity": "0","bottom": "180"})
$("#obj2").toggle(
function () {
$("#obj1").animate({"opacity": "1","bottom": "140"}, "slow");
},function () {
$("#obj1").animate({"opacity": "0","bottom": "180"}, "slow");
});
I would like it to fade in, but how do I add the animation to the first script? (animation ex: .animate({"opacity": "1","bottom": "140"}, "slow");)
Here is a super simple demo of fading in an element using CSS. You can use jQuery to add the class through a click event.
// HTML
<div id="myId" class="hide">
This is div with myId
</div>
// CSS
.hide {
display: none;
}
.myId {
animation: fadein 2s;
}
#keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
// JQUERY
$("#myId").removeClass("hide").addClass("myId");
You can see a working demo here. You'll just have to modify it to trigger on click of obj2 or where you like
EDIT - As per your comment above I have edited the pen, so now the element will be hidden on page load and then the class will be removed and the animation class added.
You would be best keeping the styles within css, and just using js to change the state (add/remove a class). The way you have the javascript is passable, but it'd be better for the class to be toggled based on itself so they can't accidentally get out of sync:
$('#obj2').on('click',function(e){
e.preventDefault();
if($('#obj1').hasClass('js-on'))
$('#obj1').removeClass('js-on');
else
$('#obj1').addClass('js-on');
});
#obj1{
position:absolute;
width:100px;
bottom:10px;
right:20px;
opacity: 0;
background-color: yellow;
padding: 1em;
transition: .5s opacity, .5s bottom;
}
#obj1.js-on {
opacity: 1;
bottom: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="obj2" href="#">Click me</a>
<div id="obj1">Hi</div>
$(document).ready(function() {
$("#obj1").hide();
$("#obj2").show();
});
$('#obj2').toggle(function(){
$("#obj1").slideToggle();
});
This will show obj1 by sliding when obj2 is pressed. To have it fade in instead Try,
$("#obj2").click(function () {
$("#obj1").fadeToggle("slow","swing");
This toggles obj1 fading in and out.
reference:
http://api.jquery.com/fadetoggle/
Slightly confused by the question, but here's my attempt at an answer: hope it helps
$(".obj1").click(function(){
$(".obj2").css('opacity', 0)
.slideDown('slow')
.animate(
{ opacity: 1 },
{ queue: false, duration: 'slow' }
);
});
.obj1 {
display: inline-block;
padding: 10px;
background: lightgrey;
}
.obj2 {
height: 100px;
width: 100px;
background: red;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="obj1">click me</div>
<div class="obj2"></div>

how to make a div slide in from outside of the window, on load (javascript)?

My question pretty basic, it's written up there.
How to make a div slide in from outside of the window onload? For example, it may appear from the right side of the window.
And I actually need basic javascript code, not jQuery.
Thank you
You can do it in pure javascript also.
Create a timer interval. that runs every 1 ms. which modifies the left attribute every time the timer is hit. once the left reaches 0 stop the timer.
--html
var div = document.getElementById("slidingDiv");
div.style.position = "absolute";
var left = document.body.offsetWidth;
div.style.left = left + "px";
var gap = 5;
var timer = window.setInterval(function() {
div.style.left = left + "px";
if (left - gap < 0) {
left = 0;
} else {
left -= gap;
}
if (left == 0) {
clearInterval(timer);
}
}, 1);
<div>
<div id="slidingDiv">this div slides</div>
</div>
watch a demo in this fiddler.
This forum is not for code requests...
Anyway you can position a html element by using its offsetHeight and offsetWidth properties in javascript.
Also you have to use an interval to make the animation.
var target = document.getElementById('div');
var interval = window.setInterval(function () {
target.offsetWidth++;
// When the div moved enough...
if (target.offsetWidth > 300) {
window.clearInterval(interval); // ...clear the interval
}
}, 500); // The animation step will be done every 500ms -> 0.5s
When you are targeting new Browsers (IE9+) you can also look at css transitions with hardware acceleration, which is done like that:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.hw-ac {
transform: translate3d(0, 0, 0); /* This neat css rule says that the html element will be rendered from the GPU */
transition: left 1s linear; /* The animation will take 1 second */
}
.start-pos { /* The start position outside of the screen */
position: absolute;
left: -100px;
}
.target-pos { /* The target poition */
position: absolute;
left: 200px;
}
</style>
</head>
<body>
<div id="div" class="hw-ac start-pos">
</div>
</body>
</html>
Now with javascript just replace the class start-pos with the class target-pos:
var target = document.getElementById('div');
target.className = 'hw-ac target-pos';
Here an example for Firefox:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#div {
position: absolute;
background-color: #f00;
width: 50px;
height: 50px;
}
.hw-ac {
-moz-transform: translate3d(0, 0, 0); /* This neat css rule says that the html element will be rendered from the GPU */
-moz-transition: left 1s linear; /* The animation will take 1 second */
}
.start-pos { /* The start position outside of the screen */
left: -100px;
}
.target-pos { /* The target poition */
left: 200px;
}
</style>
</head>
<body>
<div id="div" class="hw-ac start-pos">
</div>
<script type="text/javascript">
function start() {
var target = document.getElementById('div');
target.className = 'hw-ac target-pos';
}
</script>
<input type="button" onclick="start();" value="PRESS ME" />
</body>
</html>

Categories

Resources