jQuery animate function to pure JavaScript - 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>

Related

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()) + '%';

How to start and stop a CSS animation?

I'm having a really hard time figuring out how to start and stop an animation and reverse it.
I've assigned an animation to the element.style.animation property and from what I've read, I decided to use:
element.style.animationPlayState = "running";
to start it and:
element.style.animationPlayState = "paused";
to stop it.
But it reports "running" all the time.
Has anyone figured out how to start and stop an animation?
I have a related question here. The related part is this block of code that I use to make animations start and stop:
var style = element.style;
var animation = null;
style.animationPlayState = "paused";
if (style.animation) {
animation = style.animation;
style.animation = null;
style.animationPlayState = "paused";
element.addEventListener("animationend", function(event) {
log("animation ended");
element.removeEventListener("animationend", arguments.callee);
});
setTimeout(function() {
style.animation = animation;
style.animationPlayState = "paused";
style.animationDirection = "reverse";
style.animationPlayState = "running";
}, 30);
}
The goal is simple:
Display a div when user presses button
div display is none, so set it to display: block
Fade in div
LATER - user presses a close button on div
Fade out div
After fade out set display: none
A method to do something like this:
fadeInElement(element)
fadeOutElement(element)
You can toggle classes with setTimeout, something like this maybe?
var theDiv = document.querySelectorAll('div')[0];
function showDiv() {
theDiv.setAttribute('class', 'fadeIn');
setTimeout(function(){ theDiv.style.opacity = '1'; }, 2000);
}
function hideDiv() {
theDiv.removeAttribute('class');
theDiv.setAttribute('class', 'fadeOut');
setTimeout(function(){ theDiv.style.opacity = '0' }, 2000);
}
div {height: 100px; height: 100px; background: black; opacity: 0;}
.fadeIn {animation: 2s fadein}
.fadeOut {animation: 2s fadeout}
#keyframes fadein { to {opacity: 1;} }
#keyframes fadeout { to {opacity: 0;} }
<div></div>
<button onclick="showDiv()">Show DIV</button>
<button onclick="hideDiv()">Hide DIV</button>
EDIT
I changed the above code to something like this, though i guess you are looking for more modern solution:
var theDiv = document.querySelectorAll('div')[0];
var anBtn = document.querySelector('#animateBtn');
var clicks = 1;
anBtn.addEventListener('click', function() {
anBtn.disabled = true;
if ((clicks/2) != (clicks/2).toFixed()) {
showDiv();
}
else {
hideDiv();
}
clicks += 1;
});
function showDiv() {
theDiv.setAttribute('class', 'fadeIn');
setTimeout(function(){ theDiv.style.opacity = '1'; anBtn.disabled = false; anBtn.textContent = 'Hide Div'; }, 2000);
}
function hideDiv() {
theDiv.removeAttribute('class');
theDiv.setAttribute('class', 'fadeOut');
setTimeout(function(){ theDiv.style.opacity = '0'; anBtn.disabled = false; anBtn.textContent = 'Show Div'; }, 2000);
}
div {height: 100px; height: 100px; background: black; opacity: 0;}
.fadeIn {animation: 2s fadein}
.fadeOut {animation: 2s fadeout}
#keyframes fadein { to {opacity: 1;} }
#keyframes fadeout { to {opacity: 0;} }
<div></div>
<button id="animateBtn">Show DIV</button>
With the Javascript Web Animations API you are able to use things like:
variable.play();
variable.pause();
it is a very powerful tool, here is the documentation
Also able to set the playback speed, including negative numbers which would play the animation in reverse. seems to address all of the issues that you brought up here.
Here is the polyfill which has proven to be very powerful, even works in IE
<script src="https://rawgit.com/web-animations/web-animations-js/master/web-animations.min.js"></script>
Attempting to solve my own question with help provided. This sort of seems to work. But seems to break the edit window console.log. Also seems to break after a few runs. Maybe unrelated.
var fadeInAnimation = "2s fadein";
var fadeOutAnimation = "2s fadein reverse";
function fadeIn() {
var element = document.getElementById('box');
//console.log("element", element);
element.style.animation = fadeInAnimation;
element.style.display = "block";
//element.style.animationPlayState = "running";
}
function fadeOut() {
var element = document.getElementById('box');
element.style.display = "block";
element.style.animationPlayState = "paused";
element.style.animation = fadeOutAnimation;
element.style.animationPlayState = "running";
element.addEventListener("animationend", function(event) {
element.style.display = "none";
console.log("animation ended");
element.removeEventListener("animationend", arguments.callee);
});
}
#box {
width: 100px;
height: 100px;
background: red;
opacity: 1;
display: none;
}
#keyframes fadein { from {opacity: 0 } to {opacity: 1;} }
#keyframes fadeout { from {opacity: 1 } to {opacity: 0;} }
<button onclick="fadeIn()">Fade In</button>
<button onclick="fadeOut()">Fade Out</button>
<div id="box">
</div>

jQuery loading screen into pure 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);
}

Running a javascript function several times onmouseover

I have a function that moves a box when hovering a button. I would like the function to run over and over again every second as long as the mouse hovers over the button. I have tried loops too but I can't get this to work. I would be very thankful if you would look into this.
Here is my code:
<!DOCTYPE html>
<head>
<style>
#box {
position: relative;
top: 20px;
left: 10px;
width: 50px;
height: 50px;
background:#333366;
}
</style>
<script>
function Start() {
setInterval(Move('box'),1000);
}
var value = 0;
function Move(element) {
value += 50;
var box = document.getElementById(element);
box.style.transition = "left 0.2s ease-in-out 0s";
box.style.left = value+'px';
}
</script>
</head>
<body>
<button onmouseover="Start();">Hover to move</button>
<div id="box"></div>
</body>
</html>
Use this:
setInterval(function(){
Move('box')
},1000);
You have to pass a function to setInterval. You were actually calling Move and passing its return value.
something like this maybe?
http://jsfiddle.net/blackjim/HwKb3/1/
var value = 0,
timer,
btn = document.getElementById('btn');
btn.onmouseover = function(){
timer = setInterval(function(){
// your loop code here
Move('box');
}, 1000);
};
btn.onmouseout = function(){
clearInterval(timer);
}
function Move(element) {
value += 50;
var box = document.getElementById(element);
box.style.transition = "left 0.2s ease-in-out 0s";
box.style.left = value + 'px';
}
Try to see jQuery, it might help you in the beginning.
When this line
setInterval(Move('box'),1000);
is executed, Move('box') is evaluated (and executed one), therefore, your argument to setInterval is the return value for it, that is null
Try this:
var value = 0;
function move(element) {
value += 50;
var box = document.getElementById(element);
box.style.transition = "left 0.2s ease-in-out 0s";
box.style.left = value+'px';
// console.log(box);
}
var button = document.getElementById("buttonID");
button.onmouseover = function() {
this.iid = setInterval(function() {
move("boxID");
}, 1000);
};
button.onmouseout = function() {
this.iid && clearInterval(this.iid);
};

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