Javascript Add fadeIn to the loading Div - javascript

I have this code which loads an external local page into a div:
function load(url) {
document.getElementById("myDiv").innerHTML='<object type="text/html" data="'+url+'"></object>';
return false;
}
How can I make it fadeIn instead of just appearing? I would prefer if it was pure javascript

I found a nice fadeIn function in this answer and applied it to your load function.
Fiddle
function load(url) {
var myDiv = document.getElementById("myDiv");
myDiv.innerHTML='<object type="text/html" data="'+url+'"></object>';
fadeIn(myDiv);
return false;
}
function fadeIn(el) {
el.style.opacity = 0;
var tick = function() {
el.style.opacity = +el.style.opacity + 0.01;
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
}
};
tick();
}
load('foo');

The easiest way to do so is to add to your html jQuery:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
And then in your js file use .fadeIn() method on myDiv.
Remember to link jQuery before you link the .js file

Or if you can't use jQuery create animate classes in css:
#keyframes fadeIn {
to {
opacity: 1;
}
}
.fade-in {
opacity: 0;
animation: fadeIn .5s ease-in 1 forwards;
}
.is-paused {
animation-play-state: paused;
}
and then use this code in js:
var el = document.querySelector('.js-fade');
if (el.classList.contains('is-paused')){
el.classList.remove('is-paused');
}
The last thing you need to do is to add to myDiv classes of js-fade and fade-in is-paused.
The aforementioned code is qute general so adapt it to your needs

Related

I have a js script which should disable a button but it's not working

I have a button which makes an image spin for 3s. I want the button to be disabled during the spinning. But this is not working. Below are the js functions and the css class which creates the spin.
<script>
function spin() {
document.getElementById("spin_switch").disabled = true;
document.getElementById("image-map").classList.toggle("spin");
setTimeout(stop_spin, 3000);
document.getElementById("spin_switch").disabled = false;
}
function stop_spin() {
document.getElementById("image-map").classList.toggle("spin");
}
</script>
<style>
.spin {
transform: rotate(360deg);
webkit-transform: rotate(360deg);
overflow: hidden;
transition-duration: 3s;
transition-property: transform;
}
</style>
You have to move this line
document.getElementById("spin_switch").disabled = false;
into the stop_spin function:
function spin() {
document.getElementById("spin_switch").disabled = true;
document.getElementById("image-map").classList.toggle("spin");
setTimeout(stop_spin, 3000);
}
function stop_spin() {
document.getElementById("image-map").classList.toggle("spin");
document.getElementById("spin_switch").disabled = false;
}
Otherwise the spin_switch will be enabled again immediately. setTimeout does not stop the entire script. It just registers a callback to be executed after the given timeout has expired.

How to Fade Out an element using Javascript

I have a loading page that I used javascript to make. I would like to be able to fade-out the loading page as the index.html fades in. I understand this can easily be done with jQuery, but would like to not use jQuery since I have yet to use it on this site. I understand this may be a common question, but I have not been able to tailor other answers to my solution since most use jQuery.
I am thinking to edit the opacity of the loading element onReady. Or could I do this with simple CSS?
Javascript:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).style.display = value ? 'block' : 'none';
}
onReady(function () {
show('page', true);
show('loading', false);
});
HTML:
<div id="loading">
<div class="logo">
Logo
</div>
<span class="loading-center-cross"></span>
<h3>Loading...</h3>
</div>
<div id="page">
.....
</div>
I expect for the loading screen to fade to the index.html as previously described. Thanks for all the help!
You can do this with CSS, using something like the following:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).classList.toggle('fade-in-out', value);
}
onReady(function () {
show('page', true);
show('loading', false);
});
And have the following CSS:
#page,
#loading {
transition: opacity 1s;
}
.fade-in-out {
opacity: 0;
pointer-events: none;
}
That way, the show() function will toggle a class of fade-in-out based on value, and there will be a transition to 'fade' the div in and out, with an addition of pointer-events: none to make the div non-interactive whist transitioning.

Make a background fade in every time "onclick"

I would like the DIV to show a confirmed message where the css effect "animation" or "fade out" is activated with each click. It works fine on the first click, but not on the clicks that follow.
function clientedetail() {
document.getElementById("guardadoC").innerHTML = "Guardado.";
document.getElementById("guardadoC").style.cssText = "animation: background-fade 3s;padding:5px;";
}
#keyframes background-fade {
0% {
background-color: green;
}
100% {
background-color: none;
}
}
<input type="button" onclick="clientedetail()"></input>
<div id="guardadoC"></div>
You can add a addEventListener('animationend', function() { ... }); to reset the animation so you can run it again.
It's also a good idea to keep your CSS into your CSS file and not write it as a strings in JavaScript. Now, we are adding a class to the element to do what we want.
function clientedetail() {
var el = document.getElementById("guardadoC");
el.innerHTML = "Guardado.";
el.classList.add("animating");
//This function runs when the CSS animation is completed
var listener = el.addEventListener('animationend', function() {
el.classList.remove("animating");
//this removes the listener after it runs so that it doesn't get re-added every time the button is clicked
el.removeEventListener('animationend', listener);
});
}
#keyframes background-fade {
0% {
background-color: green;
}
100% {
background-color: none;
}
}
#guardadoC {
padding:5px;
}
#guardadoC.animating {
animation: background-fade 3s;
}
<button type="button" onclick="clientedetail()">click me</button>
<div id="guardadoC"></div>
You can use the animationend event to reset the animation.
The animationend event is fired when a CSS Animation has completed
(but not if it aborts before reaching completion, such as if the
element becomes invisible or the animation is removed from the
element).
You'll notice in this demo that I'm not using anonymous functions. With anonymous functions, we end up redefining the function over and over, which is not what you want regarding performance. Using a functional reference, we declare a function once and tie an event to it.
const btn = document.querySelector(".myButton");
const guardadoC = document.getElementById("guardadoC");
btn.addEventListener("click", clientedetail);
function clientedetail() {
guardadoC.innerHTML = "Guardado.";
guardadoC.style.cssText = "animation: background-fade 3s;padding:5px;";
}
function resetAnimation() {
guardadoC.innerHTML = "";
guardadoC.style.cssText = "";
}
guardadoC.addEventListener("animationend", resetAnimation);
#keyframes background-fade {
0% {
background-color: green;
}
100% {
background-color: none;
}
}
<input type="button" class="myButton">
<div id="guardadoC"></div>
jsFiddle
More about animationend
You could recreate the element each time you click the button. This will be a complete reset, and so it will even work when you interrupt the previous animation.
function clientedetail() {
var elem = document.getElementById("guardadoC");
var newElem = elem.cloneNode(true);
elem.parentNode.replaceChild(newElem, elem);
newElem.innerHTML = "Guardado.";
newElem.style.cssText = "animation: background-fade 3s;padding:5px;";
}
#keyframes background-fade {
0% {
background-color: green;
}
100% {
background-color: none;
}
}
<input type="button" onclick="clientedetail()"></input>
<div id="guardadoC"></div>
Trigger it based on class if you can, the way you're doing it it will only do it once.
Or you can destroy the element and re-create it kinda like this.
function clientedetail() {
var element = document.getElementById("guardadoC");
if (typeof(element) != 'undefined' && element != null)
{
document.getElementById("guardadoC").remove();
var remakeDiv = document.createElement("div");
remakeDiv.setAttribute("id", "guardadoC");
document.body.appendChild(remakeDiv)
}
document.getElementById("guardadoC").innerHTML = "Guardado.";
document.getElementById("guardadoC").style.cssText = "animation: background-fade 3s;padding:5px;";
}

Translate jQuery click(), hide() and fadeIn() to native JS

So, I'm trying hard to speed up my page (by avoiding some requests) and wonder if anyone knows how to keep the following code working without having to load the whole JQuery library:
$("#div1").click(function () {
$("#div2).hide();
$("#div3").fadeIn();
})
Ofcourse this code needs a JQuery library to work, but it's heavier than my page itself.
Is there a way,somewhere, to just select the code needed from the library and insert it inline (in my html)?
Thank You,
CSS3 #keyframes is a clean way to do what you want without jQuery. Have a look at this thread, which has a demo. It actually runs smoother than jQuery's fadeIn.
Here's an example using CSS for the fade and plain Javascript for triggering the changes:
document.getElementById('div1').onmousedown = function() {
addClass('div2', 'hide');
addClass('div3', 'show');
}
function addClass(id, className) {
var el = document.getElementById(id);
if (el.classList)
el.classList.add(className);
else
el.className += ' ' + className;
}
#div2.hide {
display: none;
}
#div3 {
opacity: 0;
transition: 0.3s opacity ease;
}
#div3.show {
opacity: 1;
}
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
If you aren't set on using jQuery you could just use normal JS, something along these lines:
document.getElementById('div1').onclick(function() {
document.getElementById('div2').style.visibility = 'hidden';
document.getElementById('div3').style.visibility = 'visible';
});
disclaimer there are better ways to do these DOM manipulations, this is an example!
The fadeIn function taken from here.
function fadeIn(el) {
el.style.opacity = 0;
var tick = function() {
el.style.opacity = +el.style.opacity + 0.01;
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
}
};
tick();
}
document.getElementById("div1").onmousedown = function () {
document.getElementById("div2").style.display = 'none';
fadeIn(document.getElementById("div3"));
};
This only works on single selectors and not multiple elements at once, and it's not going to work for any other jQuery functions. For your situation it will allow a drop in replacement so you don't require an extra library.
$ = function(selector) {
return document.querySelector(selector);
}
HTMLElement.prototype.hide = function() {
this.style.visibility = "hidden";
this.style.opacity = 0;
}
HTMLElement.prototype.fadeIn = function() {
this.style.display = "block";
this.style.visibility = "visible";
this.style.opacity = 1;
}
For the fadeIn() animation you can add a CSS property to your element. This is set to 400ms just like jQuery's effect:
transition: opacity .4s ease;

pause and resume setInterval in javascript

I am trying to mimic the typing effect on the codility's home page in JavaScript.I have already achieved the typing and deleting effect
using setInterval().
Here's the jsfiddle of that:
https://jsfiddle.net/yzfb8zow/
var span=document.getElementById("content");
var strings=["hello world","how r u??"];
var index=0; //get string in the strings array
var chIndex=0; //get char in string
var type=true;
setInterval(function(){
if(index===strings.length)
index=0;
if(type){
typeIt();
}
else
deleteIt();
},200);
// type the string
function typeIt(){
if(chIndex<strings[index].length)
span.innerHTML=strings[index].substring(0,chIndex++);
else
type=false;
}
//delete the string
function deleteIt(){
if(chIndex===0){
index++;
type=true;
}
else
span.innerHTML=strings[index].substring(0,chIndex--);
}
the html
<span id="content"></span>
<span id="cursor">|</span>
the css
#cursor{
-webkit-animation: 1s blink step-end infinite;
-moz-animation: 1s blink step-end infinite;
animation: 1s blink step-end infinite;
}
#keyframes blink {
from, to {
opacity:0;
}
50% {
opacity: 1;
}
}
#-moz-keyframes blink {
from, to {
opacity:0;
}
50% {
opacity:1;
}
}
#-webkit-keyframes blink {
from, to {
opacity:0;
}
50% {
opacity:1;
}
}
What I can't get my head around is how could I pause the setInterval function at the beginning of string change and at the end to get a clear blinking cursor.
I have looked up other answers Pause and resume setInterval and How do I stop a window.setInterval in javascript? but I am unable to comprehend how to use it in this context.
Also it would be great if you could tell me how to improve my code.
I edited your code here is your jsfiddle back: https://jsfiddle.net/yzfb8zow/5/
Also a little code explanation
var typingFunction = function() {
if (index === strings.length) {
index = 0;
}
if (type) {
typeIt();
} else {
deleteIt();
}
}
I declared your previous typing function to later be able to use it as desired.
var x = setInterval(typingFunction.bind(typingFunction), 200);
Stored the interval so I can clear it later - stored in a global variable (not necessarily ok and there are other solutions but store it).
function typeIt() {
if (chIndex == -1) {
chIndex += 1;
clearAndRestartInterval(1000);
return;
}
if (chIndex <= strings[index].length) {
span.innerHTML = strings[index].substring(0, chIndex++);
} else {
clearAndRestartInterval(1000);
type = false;
return;
}
}
In the typeIt function I clear interval at the begining at chIndex = -1, wait a while so letting the cursor blink before I restart the interval. Than I clear it again at the end of the string. My chIndex starts from -1 so I know when to blink at the begining.
Rest of the code is self explanatory.
Feel free to edit the parameter of the clearAndRestartInterval function in order to set the time of the blinking at the begining and the end.
function clearAndRestartInterval(timeOfRestart) {
clearInterval(x);
setTimeout(function() {
x = setInterval(typingFunction.bind(typingFunction), 200);
}, timeOfRestart);
}
Last but not least the stop and restart function of the interval. This is quite simple and x - is the previously declared setInterval - globally which I clear and reset with a new interval ofter some time.
Hope this helps.
Cheers
You will have to use nested timeouts.
Call typeIt directly, as its a default action.
In typeIt, add a setTimeout which will call deleteIt on completion.
On completion of deleteIt, call typeIt again.
Sample Fiddle
You typeit will look something like this:
function typeIt() {
var t_interval = setInterval(function() {
if (chIndex <= strings[index].length)
span.innerHTML = strings[index].substring(0, chIndex++);
else {
type = false;
// This is to be executed once action is completed.
window.clearInterval(t_interval);
}
}, 20)
}

Categories