jQuery loading screen into pure JavaScript - javascript

I have this loading screen script that I'd like to implement into a project.
However it requires jQuery. And since none of the elements in the page need jQuery, I'd like to save some space and avoid adding it.
Is there any way I can deliver the exact same function with pure JavaScript?
HTML:
<body onload="hide_preloader();">
<div class="preloader"> <div class="loader"></div> </div>
</body>
jQuery:
jQuery(window).load(function() { rotate = 0; $(".preloader").fadeOut(250); });
Thanks

Yes, this is actually surprisingly easy. You can do the fade with CSS transitions instead.
First, let's define some CSS:
.preloader {
transition: opacity 0.25s linear; /* when we change the opacity, use these transition settings */
}
.preloader.fade {
opacity: 0; /* when we add the class fade, set the opacity to 0 using the above transition */
}
Now we simply have to add the fade class with Javascript:
window.onload = function() {
var preloader = document.getElementsByClassName('preloader')[0];
preloader.className += ' fade';
setTimeout(function(){
preloader.style.display = 'none';
}, 300);
};
Browsers that don't understand transition will set opacity to 0 immediately, while as an absolute failsafe (e.g. for browsers that don't understand opacity) we set display to none after a second for everyone.
jsFiddle showing this effect. (Obviously you will style .preloader differently.)

Try something like this:
// taken from http://stackoverflow.com/q/13733912/2332336
function fade(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
and this html:
<body onload="fade(document.getElementById('preloader'));">
<div id="preloader"> <div class="loader"></div> </div>
</body>

This should work:
window.onload = function(){
var preloader = document.querySelector('.preloader');
var startTime = new Date().getTime();
function fadeOut(){
var passedTime = new Date().getTime() - startTime;
var opacity = Math.max(250 / (250 - passedTime), 0);
preloader.style.opacity = opacity;
if(opacity){
setTimeout(fadeOut, 0);
}
}
setTimeout(fadeOut, 0);
}

Related

Adding a fade between JavaScript slideshow? [duplicate]

I have created a JavaScript Slideshow, but I don't know how to add the fade effect. Please tell me how to do it, and please tell in JavaScript only, no jQuery!
Code:
var imgArray = [
'img/slider1.jpg',
'img/slider2.jpg',
'img/slider3.jpg'],
curIndex = 0;
imgDuration = 3000;
function slideShow() {
document.getElementById('slider').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();
Much shorter than Ninja's solution and with hardware accelerated CSS3 animation. http://jsfiddle.net/pdb4kb1a/2/ Just make sure that the transition time (1s) is the same as the first timeout function (1000(ms)).
Plain JS
var imgArray = [
'http://placehold.it/300x200',
'http://placehold.it/200x100',
'http://placehold.it/400x300'],
curIndex = 0;
imgDuration = 3000;
function slideShow() {
document.getElementById('slider').className += "fadeOut";
setTimeout(function() {
document.getElementById('slider').src = imgArray[curIndex];
document.getElementById('slider').className = "";
},1000);
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout(slideShow, imgDuration);
}
slideShow();
CSS
#slider {
opacity:1;
transition: opacity 1s;
}
#slider.fadeOut {
opacity:0;
}
As an alternative. If you are trying to make a slider.
The usual approach is to animate a frame out and animate a frame in.
This is what makes the slide effect, and the fade effect work. Your example fades in. Which is fine, but maybe not what you really want once you see it working.
If what you really want is to animate images in and ...OUT you need something a little more complex.
To animate images in and out you must use an image element for each, then flip one out and flip one in. The images need to be placed on top of each other in the case of a fade, if you want to slide you lay them beside each other.
Your slideshow function then works the magic, but before you can do that you need to add all those images in your array into the dom, this is called dynamic dom injection and it's really cool.
Make sure you check the fiddle for the full working demo and code it's linked at the bottom.
HTML
<div id="slider">
// ...we will dynamically add your images here, we need element for each image
</div>
JS
var curIndex = 0,
imgDuration = 3000,
slider = document.getElementById("slider"),
slides = slider.childNodes; //get a hook on all child elements, this is live so anything we add will get listed
imgArray = [
'http://placehold.it/300x200',
'http://placehold.it/200x100',
'http://placehold.it/400x300'];
//
// Dynamically add each image frame into the dom;
//
function buildSlideShow(arr) {
for (i = 0; i < arr.length; i++) {
var img = document.createElement('img');
img.src = arr[i];
slider.appendChild(img);
}
// note the slides reference will now contain the images so we can access them
}
//
// Our slideshow function, we can call this and it flips the image instantly, once it is called it will roll
// our images at given interval [imgDuration];
//
function slideShow() {
function fadeIn(e) {
e.className = "fadeIn";
};
function fadeOut(e) {
e.className = "";
};
// first we start the existing image fading out;
fadeOut(slides[curIndex]);
// then we start the next image fading in, making sure if we are at the end we restart!
curIndex++;
if (curIndex == slides.length) {
curIndex = 0;
}
fadeIn(slides[curIndex]);
// now we are done we recall this function with a timer, simple.
setTimeout(function () {
slideShow();
}, imgDuration);
};
// first build the slider, then start it rolling!
buildSlideShow(imgArray);
slideShow();
Fiddle:
http://jsfiddle.net/f8d1js04/2/
you can use this code
var fadeEffect=function(){
return{
init:function(id, flag, target){
this.elem = document.getElementById(id);
clearInterval(this.elem.si);
this.target = target ? target : flag ? 100 : 0;
this.flag = flag || -1;
this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
this.elem.si = setInterval(function(){fadeEffect.tween()}, 20);
},
tween:function(){
if(this.alpha == this.target){
clearInterval(this.elem.si);
}else{
var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);
this.elem.style.opacity = value / 100;
this.elem.style.filter = 'alpha(opacity=' + value + ')';
this.alpha = value
}
}
}
}();
this is how to use it
fadeEffect.init('fade', 1, 50) // fade in the "fade" element to 50% transparency
fadeEffect.init('fade', 1) // fade out the "fade" element
Much shorter answer:
HTML:
<div class="js-slideshow">
<img src="[your/image/path]">
<img src="[your/image/path]" class="is-shown">
<img src="[your/image/path]">
</div>
Javascript:
setInterval(function(){
var $container = $('.js-slideshow'),
$currentImage = $container.find('.is-shown'),
currentImageIndex = $currentImage.index() + 1,
imagesLength = $container.find('img').length;
$currentImage.removeClass('is-shown');
$currentImage.next('img').addClass('is-shown');
if ( currentImageIndex == imagesLength ) {
$container.find('img').first().addClass('is-shown');
}
}, 5000)
SCSS
.promo-banner {
height: 300px;
width: 100%;
overflow: hidden;
position: relative;
img {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0;
z-index: -10;
transition: all 800ms;
&.is-shown {
transition: all 800ms;
opacity: 1;
z-index: 10;
}
}
}

Different Zoom effect on Desktop and Mobile

I'm using this JS and CSS to add a zoom effect to header image. It's perfectly working on desktop.
Problem is on mobile hero image is not "filling" the entire container.
So I would need to have 2 different JS with 2 different % settings to make it work both on desktop and mobile.
Is there a solution to make one script with my 2 differents needs you'll find below based on screen size ? "this function is for desktop, and this function is for mobile" ?
For the one who knows I'm using GeneratePress's Elements feature to display hero header entire site.
Here is the JS + CSS working for desktop :
JS
<script>
var pagehero = document.querySelector('.page-hero');
function hero_animation(){
pagehero.style.backgroundSize = 100+'%';
pagehero.style.opacity = '1';
}
document.onload = hero_animation();
</script>
CSS
.page-hero {
transition: background-size 1s cubic-bezier(0.1, 0.135, 0.15, 0.86), opacity 1s ease-out 0.1s !important;
opacity: 0; background-size: 150% auto;
}
Here is the JS + CSS that I would need to add for mobile :
JS
<script>
var pagehero = document.querySelector('.page-hero');
function hero_animation(){
pagehero.style.backgroundSize = 200+'%';
pagehero.style.opacity = '1';
}
document.onload = hero_animation();
</script>
CSS
.page-hero {
transition: background-size 1s cubic-bezier(0.1, 0.135, 0.15, 0.86), opacity 1s ease-out 0.1s !important;
opacity: 0; background-size: 300% auto;
}
Thanks for your help !
You're calling the function when the document html/body is loaded.
<script>
var pagehero = document.querySelector('.page-hero');
function hero_animation(){
pagehero.style.backgroundSize = 100+'%';
pagehero.style.opacity = '1';
}
document.onload = hero_animation();
</script>
Change it to this:
<script>
var pagehero = document.querySelector('.page-hero');
function hero_animation(){
pagehero.style.backgroundSize = 100+'%';
pagehero.style.opacity = '1';
}
document.onload = hero_animation;
</script>
Or this:
<script>
var pagehero = document.querySelector('.page-hero');
function hero_animation(){
pagehero.style.backgroundSize = 100+'%';
pagehero.style.opacity = '1';
}
document.onload = function() { hero_animation() };
</script>
Second, you should change 100/200 to a string. JavaScript is case-sensitive:
pagehero.style.backgroundSize = '100' + '%';
Or
pagehero.style.backgroundSize = (Number(100).toString()) + '%';

jQuery animate function to pure JavaScript

I have this simple jQuery logic, How would I convert that into pure JavaScript?
I have no clue where to start unfortunately. Any help would be extremely appreciated.
$(function() {
// OPACITY OF BUTTON SET TO 0%
$(".rollstate").css("opacity", "0");
// ON MOUSE OVER
$(".rollstate").hover(function() {
// SET OPACITY TO 70%
$(this).stop().animate({
opacity: .5
}, "fast");
},
// ON MOUSE OUT
function() {
// SET OPACITY BACK TO 50%
$(this).stop().animate({
opacity: 0
}, "slow");
});
});
EDIT: a CSS solution would probably work best here, but as a learning purpose I would like to see how the pure JS would work in this case.
You can try the code below. The best would be to declare some CSS and call those by javascript or only use CSS. But as you requested I tried a bit using vanilla javascript.
var element = document.getElementById('rollstate');
element.style.opacity = "0";
element.style.filter = 'alpha(opacity=0)';//for IE
document.getElementById("rollstate").onmouseover = function() {mouseOver()};
document.getElementById("rollstate").onmouseout = function() {mouseOut()};
function mouseOver() {
var element1 = document.getElementById('rollstate');
element1.style.opacity = "5";
element1.style.filter = 'alpha(opacity=5)';
element1.className += 'faded';
}
function mouseOut() {
var element2 = document.getElementById('rollstate');
element2.style.opacity = "0";
element2.style.filter = 'alpha(opacity=0)';
element2.className += 'faded';
}
#rollstate {
-webkit-transition: opacity 1s;
opacity: 1;
}
#rollstate.faded {
opacity: 0;
}
<html>
<body>
<p>hover Below</p>
<input type ="button" id="rollstate" value="click me"/>
</body>
</html>

Javascript/jQuery - Animated Background change with fade (infinite)

I am wanting to change the background of a div every 3 seconds. This needs to loop round so once the last background image shows it loops back to the first one and so on and so on. I'm having trouble doing so.
I made a post previous to this which was VERY vague and didn't get help.
function animate() {
change1();
change2();
change3();
}
function change1() {
window.setInterval(function(){
$('.content').css('background-image','url(http://crondon.guko.co.uk/wp-content/uploads/2015/11/bride_groom_baronial_hall1.jpg)');$('.content').css('transition','background 1s linear');
},3000);
}
function change2() {
window.setInterval(function(){
$('.content').css('background-image','url(http://crondon.guko.co.uk/wp-content/uploads/2015/11/confetti.jpg)');$('.content').css('transition','background 1s linear');
},3000);
}
function change3() {
window.setInterval(function(){
$('.content').css('background-image','url(x)');$('.content').css('transition','background 1s linear');
},3000);
}
animate();
You totally overcomplicated this task. Just create an array with the URLs and a function that will set the slide URL, play the transition and set a variable that marks the next slide index. Then call this function with setInterval().
var currentIndex = 0;
var urls = [
'http://crondon.guko.co.uk/wp-content/uploads/2015/11/bride_groom_baronial_hall1.jpg',
'http://crondon.guko.co.uk/wp-content/uploads/2015/11/confetti.jpg',
'http://media.caranddriver.com/images/media/51/dissected-lotus-based-infiniti-emerg-e-sports-car-concept-top-image-photo-451994-s-original.jpg'
];
var length = urls.length - 1;
function slide() {
$('.content').css('background-image', 'url(' + urls[currentIndex] + ')');
$('.content').css('transition', 'background 1s linear');
currentIndex = (currentIndex < length) ? currentIndex + 1 : 0;
}
slide();
window.setInterval(slide, 3000);
.content {
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content"></div>

webkit transition syntax in javascript?

I'm looking for the webkitTransition object reference here
function spawnAnimation(what){
//sets the moving element
var moveingEl = document.getElementById(what);
//gives temp transition property
moveingEl.style.WebkitTransition = "left 2s";
// moveingEl.style.webkitTransition = "top 500ms";
var cLeft = moveingEl.style.left
var cleft = Number(cLeft.slice(0, -2));
var cTop = moveingEl.style.top
var cTop = Number(cTop.slice(0, -2));
moveingEl.style.left = cLeft+200 + "px";
}
This does not work.I would like to give the element a transition property, then make it move to the right. When this code is called it just immediately moves to the right with no animation. bummer :(. I don't want to predefine it in CSS, I would like to dynamically add it and then remove it.
You can use style.setProperty to modify any property using its CSS name as string, including -moz-* and -webkit-* properties.
const style = document.getElementById('my-div').style
const prop = (k, v) => style.setProperty(k, v)
function bounce() {
prop("-webkit-transition", "top .5s ease-in");
prop("top", "50px");
setTimeout(() => {
prop("-webkit-transition", "top .75s cubic-bezier(0.390, 0.575, 0.565, 1.000)");
prop("top", "0px");
}, .5 * 1000)
}
prop("-webkit-transition", "top .5s ease-in");
setInterval(bounce, (.75 + .5) * 1000);
#my-div {
background: red;
border-radius: 50%;
width:50px;
height:50px;
position:absolute;
top: 0px;
}
<div id="my-div"></div>
Allow 1ms for the rendered to get the thread back.
setTimeout(function() {
myElement.style.height = '200px'; /* or whatever css changes you want to do */
}, 1);​
You can use:
element.style.webkitTransition = "set your transition up here"
I know it's a workaround, but can you use jQuery?
$(moveingEl).css('-webkit-transform', 'translateX(200px)');
<script>
$(document).ready(function(){
var x = 100;
var y = 0;
setInterval(function(){
x += 1;
y += 1;
var element = document.getElementById('cube');
element.style.webkitTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for safari and chrome
element.style.MozTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for firefox
},50);
//for other browsers use: "msTransform", "OTransform", "transform"
});
</script>

Categories