Different Zoom effect on Desktop and Mobile - javascript

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

Related

How do I add FadeIn/FadeOut javascript effect during images change after a few seconds

I have 2 images that changes after a few seconds. I want to add a FadeIn/FadeOut effect when these images changes.
<script>
var img_tracker = "icon1";
function changeImg()
{
var pic = document.getElementById("img1");
if (img_tracker == "icon1") {
pic.src = "images/icon1.png";
img_tracker = "icon2.png";
} else {
pic.src = "images/icon2.png";
img_tracker = "icon1";
}
}
setInterval("changeImg()", 2000);
</script>
<img src="images/icon1.png" id="img1">
That is my current code, is there any way I can add fadeOut/fadeIn on every image change?
One possible solution is to use CSS transitions. Then, you can fade-out the current image periodically with setInterval(). Once the image is completely fade-out you can change the image source and fade-in. To detect the fade-out transition you can use addEventListener() over the "transitionend" event.
Example:
var img_tracker = "icon1";
var pic = document.getElementById("img1");
function changeImg()
{
if (img_tracker == "icon1")
{
pic.src = "https://via.placeholder.com/150/FF0000";
img_tracker = "icon2";
}
else
{
pic.src = "https://via.placeholder.com/150/0000FF";
img_tracker = "icon1";
}
}
function fadeIn()
{
pic.classList.remove("fade-out");
pic.classList.add("fade-in");
}
function fadeOut()
{
pic.classList.remove("fade-in");
pic.classList.add("fade-out");
// Add listener to the "transitionend" event.
pic.addEventListener("transitionend", function x()
{
// Remove the previously added listener, change
// the image and fade-in the new image.
pic.removeEventListener("transitionend", x);
changeImg();
fadeIn();
});
}
setInterval(fadeOut, 5000);
.fade {
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
.fade-out {
opacity: 0;
}
.fade-in {
opacity: 1;
}
<img id="img1" src="https://via.placeholder.com/150/0000FF" class="fade">

Include a fadeIn(Slow) on this changeable background Image javascript

I have a Javascript code to change the background image randomly and works fine, but is very rough. I would like to make some kind of transition between images, I would like to use fadeIn(slow) but don't know how to incorporate it to my code, can someone help me? Cheers!
JAVASCRIPT
window.onload = function () {
// Array of Images
var backgroundImg=["https://image1.com",
"https://image2.com",
"https://image3.com",
"https://image4.com"
]
setInterval(changeImage, 5000);
function changeImage() {
var i = Math.floor((Math.random() * 3));
document.getElementById("sectionAbout").style.backgroundImage = "url('"+backgroundImg[i]+"')";
}
}
Easy solution is to pass the transition handling to your browser, and all you should care about is the background changing.
Say we want to animate the body background.
Here's working example with colors, but can be done with images as well just use backgroundImage insead of backgroundColor
var arr = ['blue', 'red', 'pink', 'yellow', 'brown']
var i = 0;
document.getElementById('l').addEventListener('click', function() {
document.body.style.backgroundColor = arr[i];
i++
if (i == arr.length)
i = 0;
});
body {
transition: background ease 2s;
}
<button id="l">OK</button>
EDIT : In case of Images, You would want to avoid, the jerky animations caused by the images not being loaded.
var arr = ["https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyB57zuc4bms-hDtWMa-4BZvscIlJDm4r7a9WLaO4SAxUvKM-DDA", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQBinSpWOvAtkxjmkf709O3rjH2ObRbWAEn9s0JcWaeL6LMtCbOrQ", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRKY4J2qIFqkuDnABMzeypywbMSZL1cleS8vpySz0KD02wOYORU1g", "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRQkdQT0zN0xDVP-VuvwojSbS5dOstX14eZvJCOWNPxKJ5dWTIc"];
var i = 1;
var img = new Image();
img.onload = function() {
document.body.style.backgroundImage = 'url(' + img.src + ')';
i++;
if (i == arr.length)
i = 0;
setTimeout(function() {
img.src = arr[i];
}, 5000);
};
img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyB57zuc4bms-hDtWMa-4BZvscIlJDm4r7a9WLaO4SAxUvKM-DDA";
body {
transition: background ease 2s;
}
Try to use https://greensock.com/gsap, it is really efficient in transitions and animation handling. Many experts use it for efficient transition or animation management.
When you change the backgroundImage via javascript the image is loaded the moment the script is executed, so there will be a noticable lag. A solution is to load the images in css or to preload via js.
In below solution I added the images via css so there is no lag. Because Firefox doesn't support transition of background-image the script z-indexes the images in the right order and fades them (with a css animation on opacity).
html:
<div id="sectionAbout">
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
</div>
css:
#sectionAbout {
height: 100vh;
}
.img {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-size: cover;
}
.fadeIn {
animation: fadeIn 2s;
}
#keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.img:nth-of-type(1) {
z-index: 1;
background-image: url(http://picsum.photos/400/300?image=1);
}
etc..
js:
var imgDivs = document.querySelectorAll(".img");
setInterval(changeImage, 2000);
var i = 0;
function changeImage() {
i++;
el = imgDivs[i%4];
el.classList.remove("fadeIn");
// force css animation restart
// (https://css-tricks.com/restart-css-animation/)
void el.offsetWidth;
el.style.zIndex = i;
el.classList.add("fadeIn");
}
For a working example see here:
https://jsfiddle.net/tfc0kyp3/3/

How to fade a background image in and out on hover with Javascript?

I'm looking to fade in and out my background image when hovering over a button on my website. I'm able to get the background image to display with the correct properties but I'm not able to figure out how to fade it in and out (to make the image feel smooth) and how to fade the all boxes other than the one thats currently hovered over. If there's any advice I can get it'd be greatly appreciated!
Codepen: https://codepen.io/chriskaram/pen/ZXjjqj
Site: https://mydietgoal.com/mydietgoal-features-and-plans
document.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('btn1'),
outerContainer = document.getElementsByClassName('Main-content')[0];
var btnTwo = document.getElementById('btn2'),
outerContainer2 = document.getElementsByClassName('Main-content')[0];
var btnThree = document.getElementById('btn3'),
outerContainer3 = document.getElementsByClassName('Main-content')[0];
btn.addEventListener('mouseenter', hover);
btn.addEventListener('mouseleave', noHover);
btnTwo.addEventListener('mouseenter', hover2);
btnTwo.addEventListener('mouseleave', noHover2);
btnThree.addEventListener('mouseenter', hover3);
btnThree.addEventListener('mouseleave', noHover3);
function hover() {
outerContainer.style.backgroundImage = 'url(https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/59dbd720f5e2317170edb5bf/1507579681913/vegetables-fresh-healthy-food-my-diet-goal-hd.jpg)';
outerContainer.style.backgroundAttachment = "fixed";
outerContainer.style.backgroundPosition = "bottom";
outerContainer.style.backgroundRepeat = "no-repeat";
outerContainer.style.transition = "opacity .25s ease-in";
}
function hover2() {
outerContainer2.style.backgroundImage = 'url(https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/59dbd7358fd4d2e11c887fc1/1507579706733/deadlift-workout-compound-work-hard-my-diet-goal-hd.jpg)';
outerContainer.style.backgroundAttachment = "fixed";
outerContainer.style.backgroundPosition = "bottom";
outerContainer.style.backgroundRepeat = "no-repeat";
outerContainer.style.transition = "opacity .25s ease-in";
}
function hover3() {
outerContainer3.style.backgroundImage = 'url(https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/59dbd7514c0dbffb014a14c0/1507579730115/strong-powerful-motivation-healthy-body-my-diet-goal-hd.jpg)';
outerContainer.style.backgroundAttachment = "fixed";
outerContainer.style.backgroundPosition = "bottom";
outerContainer.style.backgroundRepeat = "no-repeat";
outerContainer.style.transition = "opacity .25s ease-in";
}
function noHover() {
outerContainer.style.backgroundImage = '';
}
function noHover2() {
outerContainer2.style.backgroundImage = '';
}
function noHover3() {
outerContainer3.style.backgroundImage = '';
}
});
You won't be able to fade a background image in and out separately from the element's content, but you can place the image in its own element that is behind all the other content in the element and then fade that element that contains the image:
var button = document.querySelector(".button");
var back = document.getElementById("backImg");
// Set up event handlers to change the opacity of the
// image container when mousing in and out:
button.addEventListener("mouseover", function(){
back.style.opacity = 0;
});
button.addEventListener("mouseout", function(){
back.style.opacity = 1;
});
.main {
text-align:center;
font-size:3em;
font-weight:bold;
color:#ff0;
}
#backImg {
position:absolute; /* Allow the image container to be placed into its own layer */
z-index:-1; /* Make sure that container is behind other content */
transition:all 1s; /* Configure all property changes to transition over 1 second */
}
<div class="main">
<div id="backImg">
<img src="http://www.planwallpaper.com/static/images/23-3d-beach-sand-wallpaper.jpg">
</div>
<button class="button">Hover over me!</button>
</div>

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>

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);
}

Categories