how to change the background of a div smoothly? - javascript

I have created on script for changing the background of a div continuously after some time intervals as following
jQuery( function( $ ) {
var images = [ "images/bg-a.jpg","images/bg-b.jpg" , "images/bg-c.jpg" ];
var bg_spans = [ "#bg-a","#bg-b","#bg-c" ];
var currentImage = 0;
function changeBackground() {
$( '#bdy' ).css( { backgroundImage: 'url(' + images[ ++currentImage ] + ')'} );
for(i=0; i<bg_spans.length; i++ ) {
if(i==currentImage) {
$( bg_spans[currentImage]).css ( { background: "#eb5405"} );
$( bg_spans[currentImage]).css ("border-color","#fff" );
}
else {
$( bg_spans[i]).css ( { background: "#000098"} );
$( bg_spans[i]).css ("border-color","#000098" );
}
}
if ( currentImage >= images.length - 1 ) {
currentImage -= images.length;
}
}
setInterval( changeBackground, 6000 ); `});
here the images are changing after some time intervals. I want some animation effects with this transition. for example images should fade smoothly. How can i do this?

I would lay all images on top of eachother. All with opacity 0 except the first. Than jquery animate the opacity from the second to 1 and the first to 0. And so on...

Related

Bi-Directional Infinite Scroll Loop Javascript

I'm working on a website with 5 slides (background pics + text). I want them to be looped when scrolling down and also when scrolling up. I made it work down, but not up. Please help!
document.addEventListener( "DOMContentLoaded", function() {
var div = document.getElementById( "container" );
div.addEventListener( "scroll", function() {
var max_scroll = this.scrollHeight - this.clientHeight;
var current_scroll = this.scrollTop;
var bottom = 100;
if ( current_scroll + bottom >= max_scroll ) {
var content = document.getElementsByTagName( "content" )[ 0 ];
var current = parseInt( content.dataset.current, 10 );
var section = document.getElementsByTagName( "section" )[ current ];
var new_section = section.cloneNode( true );
content.appendChild( new_section );
content.dataset.current = current + 1;
} } );
} );

Javascript: If scrolled to a specific destination fade out, if scrolled back up again, fade back in

I'm trying to fade out something if the user scrolled past 500px. This works fine! But if I want to fade it back in if the user scrolls back up it doesn't work anymore.
Whats am I missing?
var $document = $(document),
$element = $('#some-element'),
className = 'hasScrolled';
$document.scroll(function() {
if ($document.scrollTop() >= 500) {
$( "#thePlayer,#playlist").animate({
opacity: 0,
}, 2000 );
$element.addClass(className);
} else {
$element.removeClass(className);
$( "#thePlayer,#playlist").animate({
opacity: 1,
}, 2000 );
}
});
Ok I fixed it with using fadeIn and fadeOut!
Sorry!
var $document = $(document),
$element = $('#some-element'),
className = 'hasScrolled';
$document.scroll(function() {
if ($document.scrollTop() >= 500) {
$( "#thePlayer,#playlist").fadeOut("slow");
$element.addClass(className);
} else {
$element.removeClass(className);
$( "#thePlayer,#playlist").fadeIn("slow");
}
});

JQuery trigger function if element is in viewport

I'm trying to make a function openAnimation() working, when the element is "in viewport"!
Now, this particular function is GSAP. Every time I run openAnimation() doesn't work as aspected.
Runs twice and repeats each time the in-view class is been added.
-So how can I run my GSAP function with this plug in?
https://codepen.io/davide77/pen/qPLoKP
function inView( opt ) {
if( opt.selector === undefined ) {
console.log( 'Valid selector required for inView' );
return false;
}
var elems = [].slice.call( document.querySelectorAll( opt.selector ) ),
once = opt.once === undefined ? true : opt.once,
offsetTop = opt.offsetTop === undefined ? 0 : opt.offsetTop,
offsetBot = opt.offsetBot === undefined ? 0 : opt.offsetBot,
count = elems.length,
winHeight = 0,
ticking = false;
function update() {
var i = count;
while( i-- ) {
var elem = elems[ i ],
rect = elem.getBoundingClientRect();
if( rect.bottom >= offsetTop && rect.top <= winHeight - offsetBot ) {
elem.classList.add( 'in-view' );
if( once ) {
count--;
elems.splice( i, 1 );
}
} else {
elem.classList.remove( 'in-view' );
}
}
ticking = false;
}
function onResize() {
winHeight = window.innerHeight;
requestTick();
}
function onScroll() {
requestTick();
}
function requestTick() {
if( !ticking ) {
requestAnimationFrame( update );
ticking = true;
}
}
window.addEventListener( 'resize', onResize, false );
document.addEventListener( 'scroll', onScroll, false );
document.addEventListener( 'touchmove', onScroll, false );
onResize();
}
inView({
selector: '.view-poll', // an .in-view class will get toggled on these elements
once: true, // set this to false to have the .in-view class be toggled on AND off
offsetTop: 0, // top threshold to be considered "in view"
offsetBot: 0 // bottom threshold to be considered "in view"
});
// HOW CAN I RUN THIS FUNCTION NOW?
function openAnimation() {
var rotate = $('.rotate.in-view');
var scale = $('.scale.in-view');
var translate = $('.translate.in-view');
//feature Left
TweenLite.from(rotate, 1.2, {y:-400, opacity: 0.0, delay:0.0, }, 0.05);
TweenLite.from(scale, 1.2, {y:-400, opacity: 0.0, delay:0.0, }, 0.05);
TweenLite.from(translate, 1.2, {y:-400, opacity: 0.0, delay:0.0, }, 0.05);
}
You can use the library jQuery-visible. With its help, you can create a window event onScroll and check if your element is "visible", then call your function.
You can use http://scrollmagic.io/. With this you can initiate any function on scroll or when its in view.

Vary div height based on start-end points

I'm trying to make one vertical line what goes from start point (defined by
CSS) to end point (which I didn't define yet).
The idea is; the user scrolls and the line keeps like sticky and/or grows its height until the end point.
But I don't know which logic I should apply.
(Not-working) example: https://jsfiddle.net/uzegqn7f/
That line should go, for example, to the second image's top following the user's scroll position.
<div class="vertical-line line-1"></div>
<img src="https://dummyimage.com/900x300/000000/fff.jpg" alt="" class="line-1-start">
<div class="content"></div>
<img src="https://dummyimage.com/900x300/000000/fff.jpg" alt="" class="line-1-end">
.content {
height:1000px;
}
img {
max-width:100%;
height:auto;
}
.vertical-line {
display: block;
position: absolute;
background: #ee403d;
width: 4px;
height: 10px;
z-index: 999;
}
.line-1 {
margin-left:10%;
margin-top:100px;
}
var distance = $('.line-1-end').offset().top - $('.line-1-start').offset().top;
function line_animation(element,distance) {
$(window).scroll(function(){
element.css("height", distance+"px");
});
}
$(document).on('load resize', function() {
var line1 = $(".line-1");
line_animation(line1,distance);
});
NOTE:
The distance between the elements is not always the same, may vary in responsive.
Try this (comments in code):
var start = $('.line-1-start').offset().top, // get where line starts
end = $('.line-1-end').offset().top, // get where line ends
line = $('#line');
drawLine($(window).scrollTop()); // draw initial line
$(window).scroll(function(){
drawLine($(this).scrollTop()); // draw line on scroll
});
$(document).on('resize', function() { // reset top and bottom and redraw line on window resize
start = $('.line-1-start').offset().top;
end = $('.line-1-end').offset().top;
drawLine($(window).scrollTop());
});
function drawLine(currentPosition) {
if (currentPosition >= start && currentPosition <= end) {
var distance = currentPosition - start;
line.css("height", distance+"px");
} else {
line.css("height", 0);
}
}
Updated fiddle
i didn't get to finish it but it's nearly there if it helps. It dynamically will figure out the height and start/end positions, you might be able to finish it off, it's not calculating the end position quite right, bit of tweaking and it'll be ok though. Checkout the JSfiddle;
https://jsfiddle.net/x4jhLohs/2/
$(document).on('ready', function() {
$(window).scroll(function(){
handleVerticalLine();
});
function handleVerticalLine() {
// Loop through and grab all our Vertical Line Containers, each one will have a Start and an End selector.
$('.vertical-line-container').each(function() {
// Grab our start and end elements.
var $startElement = $( $( this ).data( 'line-start-selector' ) );
var $endElement = $( $( this ).data( 'line-end-selector' ) );
var $verticalLine = $( this ).find( $( '.vertical-line' ) );
if( $startElement.length && $endElement.length && $verticalLine.length ) {
var startElementTopOffsfet = $startElement.offset().top;
var endElementTopOffsfet = $endElement.offset().top + $endElement.height();
var startElementVerticalLineBegin = startElementTopOffsfet;
var endElementVerticalLineBegin = endElementTopOffsfet;
$verticalLine.css( 'top', startElementTopOffsfet + $startElement.height() );
var verticalLinePercentage = startElementVerticalLineBegin / endElementVerticalLineBegin * 100;
verticalLinePercentage += $(window).scrollTop();
$verticalLine.css('height', verticalLinePercentage )
}
});
}
});

How do I change whatever object is in the center of the screen?

I created the following code which will dim any image that is not in the center of the window, but it only runs once. I am using onload to make sure I have the images, before manipulating them. I would like to change the opacity to 1 of any image in the middle of the screen.
$(window).on("load", function scrolldim() {
var xHome = window.innerWidth/2;
var yHome = window.innerHeight/2;
var pElement = document.elementFromPoint(xHome, yHome).id;
$( ".mid img" ).not( document.getElementById("#" + pElement ) )
.fadeTo( "slow", 0.3 );
if($( ".mid img" ).attr('id') == pElement) {
$("#" + pElement).fadeTo( "slow", 1 );
}
Then I tried wrapping the call in a when statement, like below, but that didn't work at all.
$.when(ajaxLoad()).done(function(a1, a2, a3, a4){
var xHome = window.innerWidth/2;
var yHome = window.innerHeight/2;
var pElement = document.elementFromPoint(xHome, yHome).id;
$( ".mid img" ).not( document.getElementById("#" + pElement ) )
.fadeTo( "slow", 0.3 );
if($( ".mid img" ).attr('id') == pElement) {
$("#" + pElement).fadeTo( "slow", 1 );
});
It runs only once, because there is no EventListener.(besides onload)
You basically say: "When the document is loaded set the opacity of the images". And that is what jQuery does(only once).
The thing is I don't know WHEN you want this function to be executed.
When a button is clicked?
When new image is loaded?
Every couple of
seconds?
I will give you a simple example:
You want your function to be executed every 500ms(0.5s)
$(window).on("load", function() {
setInterval(scrolldim, 500); //call the scrolldim function every 0.5sec
});
function scrolldim(){
var xHome = window.innerWidth / 2;
var yHome = window.innerHeight / 2;
var pElement = document.elementFromPoint(xHome, yHome).id;
console.log("500");
$(".mid img").not(document.getElementById("#" + pElement))
.fadeTo("slow", 0.3);
if ($(".mid img").attr('id') === pElement) {
$("#" + pElement).fadeTo("slow", 1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories