Rotating Background Image with jQuery - javascript

I am trying to rotate the background image of a div with jquery. It works fine but the content within the div disappears when the image rotates. How can i prevent the content from disappering and make it such the it is always present:
Code:
jQuery(document).ready(function($) {
$(window).load(function() {
var i =0;
var images = ['http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image2.png','http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image3.png','http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image1.png'];
var image = $('#slideit');
image.css('background-image', 'url(http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image1.png)');
setInterval(function(){
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images [i++] +')');
image.fadeIn(1000);
});
if(i == images.length)
i = 0;
}, 5000);
})
});
Fiddle HERE

You can make it like this http://jsfiddle.net/frzssoyw/3/
<div id="slideit">
<div id="slideit-bg"></div>
<div id="slideit-content">
some content
</div>
</div>

You can use position: absolute; on images.
I edited your JSFiddle using position: absolute;.
HTML:
<div id="slideit" style="width:700px;height:391px;">
<div class="slideit-content">some content</div>
<img class="img-rotate active" src="http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image2.png" />
<img class="img-rotate" src="http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image3.png" />
<img class="img-rotate" src="http://dl.dropboxusercontent.com/u/96099766/ChangeBackgroundJQuery/image1.png" />
</div>
CSS:
.img-rotate {
position: absolute;
top: 0;
left: 0;
width: 700px;
height: 391px;
opacity: 0;
z-index: 0;
-webkit-transition: opacity 1s linear;
-moz-transition: opacity 1s linear;
transition: opacity 1s linear;
}
.img-rotate.active {
opacity: 1;
}
.slideit-content {
z-index: 10;
position: relative;
}
JS:
jQuery(function($) {
var i = 0,
image = $('#slideit'),
images = image.find(".img-rotate"),
images_count = images.length,
next_image;
setInterval(function(){
i = (i+1) % images_count;
next_image = images.eq(i);
images.filter(".active").removeClass("active");
next_image.addClass("active");
}, 5000);
});

Related

Jquery slidetoggle code to vanilla Javascript that ahndle multiple elements toggle

I have few elements I need to slide, but I don't want to attach whole jQ lib. I like jQ a lot, but whole lib is just overkill in this example.
How to convert jq slideUp/slideDown/toggle to vanilla JS with support of multiple elements passed to function?
JQ code:
var $context = getContext(context);
$($context).on('click', '.menu', function () {
$('.nav').slideToggle();
});
JS code:
var list = document.getElementsByClassName("class1", "class2", "class3");
//or
var list = document.querySelectorAll("class1", "class2", "class3");
var slideUp = function(targets, duration){
// execution
};
slideUp(list, 500);
SO wizards make it happen! :)
I wasn't happy with the last solution I gave you it was rushed and buggy totally unacceptable, Hope you can forgive me...so this is a better version with the clicks of each item working too
const clicker = document.getElementsByClassName("clicker")[0];
clicker.addEventListener("click", function() {
process(document.querySelectorAll(".js-toggle"));
});
[...document.querySelectorAll(".js-toggle")].forEach((element) =>
element.addEventListener("click", function() {
process(this)
})
)
const container = [];
function process(linkToggle) {
container.length = 0
if (linkToggle.length > 0) {
for (let i = 0; i < linkToggle.length; i++) {
container.push(
document.getElementById(linkToggle[i].dataset.container))
animate(container[i])
}
} else {
container.push(
document.getElementById(linkToggle.dataset.container))
animate(container[0])
}
}
function animate(element) {
if (!element.classList.contains("active")) {
element.classList.add("active");
element.style.height = "auto";
let height = parseInt(element.clientHeight || 0)
element.style.height = "0px";
setTimeout(function() {
for (let t = 0; t < container.length; t++) {
do {
container[t].style.height =
parseInt(container[t].style.height || height) +
1 + 'px'
} while (parseInt(container[t].style.height || height) < height);
}
}, 0);
} else {
element.style.height = "0px";
element.addEventListener(
"transitionend",
function() {
element.classList.remove("active");
}, {
once: true
}
);
}
}
.clicker {
cursor: pointer;
background: red;
}
.box {
width: 300px;
border: 1px solid #000;
margin: 10px;
cursor: pointer;
}
.toggle-container {
transition: height 0.35s ease-in-out;
overflow: hidden;
}
.toggle-container:not(.active) {
display: none;
}
<div class="clicker">CLICK ME</div>
<div class="box">
<div class="js-toggle" data-container="toggle-1">Click1</div>
<div class="toggle-container" id="toggle-1">I have an accordion and am animating the the height for a show reveal - the issue is the height which i need to set to auto as the information is different lengths.<br><br> I have an accordion and am animating the the height fferent lengths.
</div>
</div>
<div class="box">
<div class="js-toggle" data-container="toggle-2">Click2</div>
<div class="toggle-container open" id="toggle-2">I have an accordion and am animating the the height for a show reveal - the issue is the height which i need to set to auto as the information is different lengths.<br><br> I have an accordion and am animating the the height fferent lengths.
</div>
</div>
<div class="box">
<div class="js-toggle" data-container="toggle-3">Click3</div>
<div class="toggle-container" id="toggle-3">I have an accordion and am animating the the height for a show reveal - the issue is the height which i need to set to auto as the information is different lengths.<br><br> I have an accordion and am animating the the height fferent lengths.
</div>
</div>
I hope this helps
you could just use css like so ( wasn't sure witch way you wanted to slid but this gives you an idea of how to do it):
var $slider = document.getElementById('slider');
var $toggle = document.getElementById('toggle');
$toggle.addEventListener('click', function() {
var isOpen = $slider.classList.contains('slide-in');
$slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');
});
#slider {
position: absolute;
width: 100px;
height: 100px;
background: blue;
transform: translateX(-100%);
-webkit-transform: translateX(-100%);
}
.slide-in {
animation: slide-in 0.5s forwards;
-webkit-animation: slide-in 0.5s forwards;
}
.slide-out {
animation: slide-out 0.5s forwards;
-webkit-animation: slide-out 0.5s forwards;
}
#keyframes slide-in {
100% {
transform: translateX(0%);
}
}
#-webkit-keyframes slide-in {
100% {
-webkit-transform: translateX(0%);
}
}
#keyframes slide-out {
0% {
transform: translateX(0%);
}
100% {
transform: translateX(-100%);
}
}
#-webkit-keyframes slide-out {
0% {
-webkit-transform: translateX(0%);
}
100% {
-webkit-transform: translateX(-100%);
}
}
<div id="slider" class="slide-in">
<ul>
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor</li>
</ul>
</div>
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
I can't take credit for this its lifted from:
CSS 3 slide-in from left transition
I hope this helps
Could you not simply include the css in the page header so wouldn't need to edit any style sheets, well in any case then how about this:
function SlideDown() {
const element = document.getElementById("slider");
let top = 0;
const up = setInterval(MoveDown, 10);
function MoveDown() {
if (top == 50) {
clearInterval(up);
} else {
top++;
element.style.top = top + '%';
}
}
}
function SlideUp() {
const element = document.getElementById("slider");
let top = parseInt(element.style.top);
const down = setInterval(MoveUp, 10);
function MoveUp() {
if (top == -100) {
clearInterval(down);
} else {
top--;
element.style.top = top + '%';
}
}
}
<!DOCTYPE html>
<html>
<body>
<div id="slider" style="position:absolute; top: -100px;">
<ul>
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor</li>
</ul>
</div>
<button onclick="SlideDown()">Slide Down</button>
<button onclick="SlideUp()">Slide Up</button>
</body>
</html>
I hope this helps

how to make a flip animation horizontal with CSS and Javascript

i made a blackjack game , i want to make the dealer cards flip from back to front everything works expect that when the shown cards appear they apper one under another .. how can i make them appear
in line ??
function TurnDealerCards()
{
DealerCards.innerHTML = "";
for (var i = 0; i < DealerArray.length; i++) {
var Dealercard = document.createElement('img');
var random = Math.floor((Math.random() * 10));
Dealercard.setAttribute("width", 50);
Dealercard.setAttribute("src", (allCards[random])[(DealerArray[i])]);
DealerCards.appendChild(Dealercard);
}
DealerCards.className = 'myDIV';
}
.myDIV {
display:inline-block;
border: 0px;
width: 50px;
background-color:transparent;
color: transparent;
animation: mymove 1s ;
}
#keyframes mymove {
50% {
transform: rotateY(180deg);
}
}
<table border="0" width="100%" height="100%" style="text-align: center">
<tr><th id="NewGame" onclick="MakeAnewGame();" style="float:left">
<img src="media/cards/new game.png" width="100" /><label>change table color</label><input id="changeBGC" type="button" onclick="changeBackground();">
</th></tr>
<tr><td style="height:100pt;width:100%;font-size:100pt;color:white"><div id="dealer"></div></td></tr>
Use display:flex to the wrap (myDiv) and use animation to each img
In js set animation-delay and increase the time one by one
var DealerCards=document.getElementById("cards");
DealerCards.innerHTML = "";
var DealerArray=[1,1,1];
for (var i = 0; i < DealerArray.length; i++) {
var Dealercard = document.createElement('img');
var random = Math.floor((Math.random() * 10));
Dealercard.setAttribute("width", 50);
Dealercard.setAttribute("src","jj");
Dealercard.style.animationDelay=(i + 0.5 )+'s';
DealerCards.appendChild(Dealercard);
}
DealerCards.className = 'myDIV';
.myDIV img{
border: 0px;
width: 50px;
animation: mymove 1s;
background-color:transparent;
color: transparent;
}
myDiv {
display:flex;
}
#keyframes mymove {
50% {
transform: rotateY(180deg);
}
}
<div id="cards"></div>

How to crossfade images in .js slideshow

So this is my slideshow div:
<div class="header">
<img name="slide" class="slide">
</div>
the css for it:
.slide{
width: 80%;
height: auto;
filter: brightness(90%);
}
and the javascript:
var i = 0;
var images = [];
var time = 4000;
images[0] = '1.png';
images[1] = '2.png';
images[2] = '3.png';
function changeImg() {
document.slide.src = images[i];
if (i < images.length -1) {
i++;
}
else
{
i = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
Now i want it to crossfade, currently its just switching the images very abruptly, but i want it smooth.
Any help?
You need to add opacity set to 0 on your css class, and then create a new class with opacity set to 1, that way you'll trigger the function to switch opacity after a specific time period has passed
<style>
.slide {
border: none;
opacity: 0;
position: absolute;
top: 0;
left: 0;
-webkit-transition: opacity 2s linear;
-moz-transition: opacity 2s linear;
-o-transition: opacity 2s linear;
transition: opacity 2s linear;
}
.visible {
opacity: 1;
}
</style>
<div class="header">
<img id="img0" class="slide visible" src="1.png">
<img id="img1" class="slide" src="2.png">
<img id="img2" class="slide" src="3.png">
</div>
<script>
var actual = 0;
var total = 3;
function addClass(elem, name) {
elem.className = elem.className + " " + name;
}
function deleteClass(elem, name) {
var c = elem.className;
elem.className = c.replace(name, "").replace(/ /g, " ").replace(/^ | $/g, "");
}
function nextImg() {
var e;
e = document.getElementById("img" + actual);
deleteClass(e, "visible");
actual++;
if (actual > total - 1) actual = 0;
e = document.getElementById("img" + actual);
addClass(e, "visible");
}
var slider = setInterval(nextImg, 4000);
</script>
While I like Joe's answer, here is one that uses JavaScript without adding or removing classes:
I gave the <img> an id for ease of reference here:
<img id='slideShow' name="slide" class="slide">
JavaScript:
function fadeImg(elem, total, step, speed){
step=step||5;
speed=speed||50;
var iter=0;
var fadeOutTime=(100/step)*speed;
var time=total;
var n = 0;
var opacity;
elem.src=images[n];
var fadeInterval=setInterval(function(){
time=time-speed;
opacity=iter/100;
if(time>fadeOutTime&&opacity<1){
iter=iter+step;
} else if(time<=fadeOutTime&&time>0&&opacity>0){
iter=iter-step;
} else if(time<=0){
n<images.length-1?n++:n=0;
elem.src=images[n];
time=total;
}
elem.style.opacity=opacity;
elem.style.filter= 'alpha(opacity=' +opacity*100 + ')';
},speed);
}
window.onload = fadeImg(document.getElementById('slideShow'),time);
I borrowed the interval concept from here: https://stackoverflow.com/a/2207751/6661052

How make slide to auto play and change swap to fade in JavaScript

Hi guys I am new in JavaScript I have a image slider here I want the Image Slider to auto play and change swap to fade effect. How can I change this?
My current JavaScript code is below
$('#banner .banner-bg').each(function() {
var self = $(this),
images = self.find('.banner-bg-item');
// SET BG IMAGES
images.each(function() {
var img = $(this).find('img');
if (img.length > 0) {
$(this).css('background-image', 'url(' + img.attr('src') + ')');
img.hide();
}
});
// INIT SLIDER
if ($.fn.owlCarousel) {
self.owlCarousel({
slideSpeed: 500,
pagination: true,
navigation: true,
paginationSpeed: 200,
singleItem: true,
autoPlay:true,
animateIn: 'fadeIn',
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
addClassActive: true,
afterMove: function() {
// ACTIVATE TAB
var active_index = self.find('.owl-item.active').index();
$('.banner-search-inner .tab-title:eq(' + active_index + ')').trigger('click');
}
});
}
// SET DEFAULT IF NEEDED
var active_tab_index = $('.banner-bg-item.active, .banner-search-inner .tab-title.active').index();
if (active_tab_index !== 0) {
self.trigger('owl.jumpTo', active_tab_index);
}
});
$('.banner-search-inner').each(function() {
var self = $(this),
tabs = self.find('.tab-title'),
contents = self.find('.tab-content');
// TAB CLICK
tabs.click(function() {
if (!$(this).hasClass('active')) {
var index = $(this).index();
tabs.filter('.active').removeClass('active');
$(this).addClass('active');
contents.filter('.active').hide().removeClass('active');
contents.filter(':eq(' + index + ')').fadeToggle().addClass('active');
// CHANGE BG
if ($.fn.owlCarousel) {
$('#banner .banner-bg').trigger('owl.goTo', index);
}
}
});
});
Below Is the HTML code
<div class="banner-bg">
<div class="banner-bg-item active"><img src="img/banner-bg-1.jpg" alt="" class="img-responsive"></div>
<div class="banner-bg-item"><img src="img/banner-bg-2.jpg" alt="" class="img-responsive"></div>
</div>
You can use CSS animation for that and switch between the slides with javascript. I wrote this code for you and you can use play, stop, next and prev button to navigate. You can use img tag inside slide div if you like image inside your slide.
var slideIn = 0;
function prev() {
var slide = document.querySelectorAll('.slide'),
prevSlide = (typeof slide[slideIn-1] !== 'undefined')? slideIn-1 : slide.length-1;
if (slide[prevSlide] && slide[slideIn]){
slide[slideIn].className = 'slide out';
slide[prevSlide].className = 'slide in';
slideIn = prevSlide;
}
}
function next() {
var slide = document.querySelectorAll('.slide'),
nextSlide = (typeof slide[slideIn+1] !== 'undefined')? slideIn+1 : 0;
if (slide[nextSlide] && slide[slideIn]){
slide[slideIn].className = 'slide out';
slide[nextSlide].className = 'slide in';
slideIn = nextSlide;
}
}
var playInterval,
PlayTimer = 1000; // 1 second
function play() {
next();
playInterval = setTimeout(play,PlayTimer);
}
function stop() {
clearTimeout(playInterval);
}
body {
padding: 0;
margin: 0;
font-family: tahoma;
font-size: 8pt;
color: black;
}
div {
height: 30px;
width: 100%;
position: relative;
overflow: hidden;
margin-bottom: 10px;
}
div>div {
opacity: 0;
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
.in {
-webkit-animation: comein 1s 1;
-moz-animation: comein 1s 1;
animation: comein 1s 1;
animation-fill-mode: both;
}
#keyframes comein {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.out {
-webkit-animation: goout 1s 1;
-moz-animation: goout 1s 1;
animation: goout 1s 1;
animation-fill-mode: both;
}
#keyframes goout {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
<div>
<div class="slide in">1st Slide content</div>
<div class="slide">2nd Slide content</div>
<div class="slide">3rd Slide content</div>
<div class="slide">4th Slide content</div>
</div>
<button onclick="prev();">Prev</button>
<button onclick="next();">Next</button>
<button onclick="play();">Play</button>
<button onclick="stop();">Stop</button>

Vertical distribution of elements (and animation) - jQuery

I like to know the cleanest method to distribute elements vertically with jQuery. I nailed it but it's not very clean right >< ? I would like to get to do it without plugin... Thank you in advance ;-)
Here my JSFiddle
jQuery(document).ready(function($) {
var gap = 10;
var firstElem = $('#lorem');
if(firstElem.length){
var heightCall = (firstElem.offset().top)+(firstElem.outerHeight())+(gap);
var middleElem = $('#dolore');
middleElem.offset({top : heightCall});
var lastElem = $('#amet');
var NewHeightCall = (middleElem.offset().top)+(middleElem.outerHeight())+(gap);
lastElem.offset({top : NewHeightCall});
/* Animation */
$('#lorem, #dolore, #amet').hover(
function(){
$(this).stop().animate({left: (($(this).offset().left)-(20))+'px',opacity:'0.5'},'slow')
},
function(){
$(this).stop().animate({left: (($(this).offset().left)+(20))+'px',opacity:'1'},'slow')
});
}
});
I have fiddled around with your code:
This is a simplified version:
HTML:
<div id="lorem" class="vertical-block">My first ID div</div>
<div id="dolore" class="vertical-block">My second ID div.<br>My second ID div. My second ID div.</div>
<div id="amet" class="vertical-block">My third ID div</div>
CSS:
.vertical-block {
position: absolute;
padding:15px;
}
#lorem{
top:20%;
right:40px;
background:#f79673;
}
#dolore{
right:80px;
background:#cd7454;
}
#amet{
right:40px;
background:#a15338;
}
.vertical-block:hover {
opacity: 0.5;
padding-right: 30px;
-webkit-transition: all 2s;
transition: all 0.4s;
}
Javascript:
jQuery(document).ready(function($) {
var gap = 10;
var firstElem = $('#lorem');
var top = 0;
$('.vertical-block').each(function(element){
var $currentElement = $(this);
if (top === 0) {
top = $currentElement.offset().top + $currentElement.outerHeight() + gap;
} else {
$currentElement.offset({top: top});
top = top + $currentElement.outerHeight() + gap;
}
});
});
https://jsfiddle.net/rae2x4e0/1/
Now if you want to go for a purely css solution, then:
HTML:
<div class="container">
<div id="lorem" class="vertical-block">My first ID div</div>
<br />
<div id="dolore" class="vertical-block">My second ID div.<br>My second ID div. My second ID div.</div>
<br />
<div id="amet" class="vertical-block">My third ID div</div>
</div>
CSS:
.container {
position-relative;
text-align: right;
padding-top: 10%;
}
.vertical-block {
padding:15px;
display: inline-block;
margin-top: 20px;
}
#lorem{
right:40px;
background:#f79673;
}
#dolore{
right:80px;
background:#cd7454;
}
#amet{
right:40px;
background:#a15338;
}
.vertical-block:hover {
opacity: 0.5;
padding-right: 30px;
-webkit-transition: all 2s;
transition: all 0.4s;
}
https://jsfiddle.net/ycdwpjxw/1/

Categories

Resources