I have problem with jquery animation. It's not working in IE9 and older. I think problem is somewhere with css because as I can see in a ie there is opacity set to 0.
Javascript
var $lead = $('.lead');
var height = $lead.height();
var totalHeight = height * numOfLeads;
function bounce() {
var time = 400;
var counter1 = 1;
$($(".lead").get().reverse()).each(function() {
setTimeout(function(el, counter1, height, totalHeight) {
$(el).css({
top: "-" + (totalHeight - (counter1 * height) + height) + "px",
opacity: 0,
display: "block",
position: "relative"
}).animate({
top: "+=" + (totalHeight - (counter1 * height) + height) + "px",
opacity: 1
}, 1000, "easeOutBounce")
;
}, time, this, counter1, height, totalHeight);
time += 400;
counter1 += 1;
});
}
bounce();
HTML
<div class="lead">
<div class="progress-bar">
<div>
<span class="first green end"></span>
<span class="middle"></span>
<span class="middle"></span>
<span class="last"></span>
</div>
<span>Accepted</span>
</div>
<div class="product">Hypotek</div>
<div class="county">Ustecky</div>
<div class="change">
<span>Changed</span>
<div>22</div>
<div>29</div>
<div>38</div>
</div>
CSS
#leads{position: absolute;}
#leads, #leads div { z-index: 5;}
.lead { background: url("../images/lead_back_stripe.png") repeat-x scroll 0 0 transparent; height: 65px;}
.lead > div { float: left; padding-left: 20px; padding-top: 21px; width: 180px;}
.lead > div.progress-bar{width: 185px;}
.lead > div.product {width: 175px;}
You can see the whole thing here
Does anybody know where the problem is?
long story short: opacity won't work in ie and the only method to set an opacity in ie is, as far as i know, filter: alpha(opacity = X); with 0 < X > 100 ....which won't work with an jquery animation
except, maybe this works:
$(el).animate({
opacity:1
},{
step: function( now, fx ) {
var X = 100 * now; //like at half the animation, opacity is 0.5, so X becomes 50
$(fx.elem).css("filter","alpha(opacity="+X+")");
}
});
Related
I have created a very basic animated percentage bar with HTML, CSS, and JS the only problem is that I am trying to devise a way to also animate the increase and/or decrease of the percentage output to go along with an animated percentage bar. In the example below and in this JsFiddle I have successfully created that with the only problem being that it doesn't seem to be the most efficient or effective way of doing it.
In the code snippet directly below I'm creating this animated effect by...
Setting x equal to setInterval
Capturing the width of percent bar on the left and removing the px from the end of the string.
Capturing the width of percent bar on the right and removing the px from the end of the string.
Displays the percent value for the left (blue) bar inside the tooltip that can be seen when hovered over.
Displays the percent value for the right (red) bar inside the tooltip that can be seen when hovered over.
Displays the percent value of the left (blue) bar below the percent bar.
Displays the percent value of the right (red) bar below the percent bar.
All of this code below will run every 64 Milliseconds.
This code will only run for 2000 Milliseconds which is the same amount of time that I have set the transition for the percent bars.
Note: The whole point of the code below is to give the illusion that the percent values are increasing as either of the percent bars are increasing. In short, the goal is to make it seem more animated rather than the number all of a sudden seeing the number jump from one number to the next.
There just has to be a better way of achieving the same effect (or better) rather than pulling data from the DOM every 64 Milliseconds. There are tons of real-time graph's out on the web that achieve the same effect but I can't figure out how so I came up with my own and don't really think that they do it this way either. Any ideas??? I would only like to use pure Javascript with no libraries such as jQuery.
var x = setInterval(function() {
var left = parseInt(window.getComputedStyle(p_bar_left).getPropertyValue('width').replace(/px/i, '')) / (parseInt(window.getComputedStyle(p_bar_left).getPropertyValue('width').replace(/px/i, '')) + parseInt(window.getComputedStyle(p_bar_right).getPropertyValue('width').replace(/px/i, ''))) * 100;
var right = parseInt(window.getComputedStyle(p_bar_right).getPropertyValue('width').replace(/px/i, '')) / (parseInt(window.getComputedStyle(p_bar_left).getPropertyValue('width').replace(/px/i, '')) + parseInt(window.getComputedStyle(p_bar_right).getPropertyValue('width').replace(/px/i, ''))) * 100;
p_bar_left.querySelector('.percent-value').innerText = left.toFixed(2) + '%';
document.querySelector('#blue').querySelector('.percent-amount').innerText = left.toFixed(2) + '%';
p_bar_right.querySelector('.percent-value').innerText = right.toFixed(2) + '%';
document.querySelector('#red').querySelector('.percent-amount').innerText = right.toFixed(2) + '%';
}, 64);
setTimeout(function() {
clearInterval(x)
}, 2000);
var good = document.querySelector('#good');
var bad = document.querySelector('#bad');
var p_bar_left = document.querySelector('#progressbar-left');
var p_bar_right = document.querySelector('#progressbar-right');
var counter_left = 0;
var counter_right = 0;
var percent_left = 0;
var percent_right = 0;
function changePercent(increment, which) {
if (which == 'left') {
counter_left += increment;
} else if (which == 'right') {
counter_right += increment;
} else {
throw "Don't know which value to increase.";
}
percent_left = (counter_left / (counter_left + counter_right)) * 100;
percent_right = (counter_right / (counter_left + counter_right)) * 100;
p_bar_left.style.width = percent_left + '%';
p_bar_right.style.width = percent_right + '%';
document.querySelector('#total-amount').innerText = counter_right + counter_left;
var x = setInterval(function() {
var left = parseInt(window.getComputedStyle(p_bar_left).getPropertyValue('width').replace(/px/i, '')) / (parseInt(window.getComputedStyle(p_bar_left).getPropertyValue('width').replace(/px/i, '')) + parseInt(window.getComputedStyle(p_bar_right).getPropertyValue('width').replace(/px/i, ''))) * 100;
var right = parseInt(window.getComputedStyle(p_bar_right).getPropertyValue('width').replace(/px/i, '')) / (parseInt(window.getComputedStyle(p_bar_left).getPropertyValue('width').replace(/px/i, '')) + parseInt(window.getComputedStyle(p_bar_right).getPropertyValue('width').replace(/px/i, ''))) * 100;
p_bar_left.querySelector('.percent-value').innerText = left.toFixed(2) + '%';
document.querySelector('#blue').querySelector('.percent-amount').innerText = left.toFixed(2) + '%';
p_bar_right.querySelector('.percent-value').innerText = right.toFixed(2) + '%';
document.querySelector('#red').querySelector('.percent-amount').innerText = right.toFixed(2) + '%';
}, 64);
setTimeout(function() {
clearInterval(x)
}, 2000);
}
good.addEventListener('click', function() {
changePercent(1, 'left');
});
bad.addEventListener('click', function() {
changePercent(1, 'right');
});
var tooltip = document.querySelectorAll('.tooltip');
var tooltipelement = document.querySelectorAll('#progressbar-left, #progressbar-right');
for (var x = tooltipelement.length; x--;) {
tooltipelement[x].addEventListener('mousemove', function(e) {
for (var i = tooltip.length; i--;) {
tooltip[i].style.left = e.pageX + 20 + 'px';
tooltip[i].style.top = e.pageY + 'px';
}
});
}
#progressbar-container {
display: flex;
position: relative;
width: 50vw;
height: 32px;
border: 2px solid black;
background-color: #ccc;
justify-content: space-between;
}
#progressbar-left {
position: relative;
height: 100%;
background-color: blue;
transition: width 2s;
align-items: center;
justify-content: center;
}
#progressbar-right {
position: relative;
height: 100%;
background-color: red;
transition: width 2s;
align-items: center;
justify-content: center;
}
.tooltip {
display: none;
position: fixed;
width: auto;
height: auto;
padding: 6px;
background-color: black;
text-align: center;
border-radius: 6px;
z-index: 1;
}
.object {
display: inline-block;
color: #fff;
}
.percent-value {
display: inline-block;
color: #fff;
}
#progressbar-left:hover .tooltip {
display: block;
}
#progressbar-right:hover .tooltip {
display: block;
}
#total {
display: block;
font-weight: bold;
}
#total-amount {
display: inline-block;
font-weight: normal;
}
#blue,
#red {
display: block;
font-weight: bold;
}
.percent-amount {
display: inline-block;
font-weight: normal;
}
<body>
<input type="button" value="Good" id="good">
<input type="button" value="Bad" id="bad">
<div id="progressbar-container">
<div id="progressbar-left">
<div class="tooltip">
<span class="tooltiptext">
<span class="object">Blue</span>
<span class="percent-value"></span>
</span>
</div>
</div>
<div id="progressbar-right">
<div class="tooltip">
<span class="tooltiptext">
<span class="object">Red</span>
<span class="percent-value"></span>
</span>
</div>
</div>
</div>
<span id="total">Total: <p id="total-amount">0</p></span>
<span id="blue">Percent Blue: <p class="percent-amount">0%</p></span>
<span id="red">Percent Red: <p class="percent-amount">0%</p></span>
</body>
JsFiddle
Live example: https://jsfiddle.net/b8vLg0ny/
It's possible to use the CSS scale and translate functions to zoom into element.
Take this example, of 4 boxes in a 2x2 grid.
HTML:
<div id="container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
</div>
</div>
CSS:
* { margin: 0; }
body, html { height: 100%; }
#container {
height: 100%;
width: 50%;
margin: 0 auto;
}
#zoom-container {
height: 100%;
width: 100%;
transition: all 0.2s ease-in-out;
}
.box {
float: left;
width: 50%;
height: 50%;
color: white;
text-align: center;
display: block;
}
.red { background: red; }
.blue { background: blue; }
.green { background: green; }
.black { background: black; }
JavaScript:
window.zoomedIn = false;
$(".box").click(function(event) {
var el = this;
var zoomContainer = $("#zoom-container");
if (window.zoomedIn) {
console.log("resetting zoom");
zoomContainer.css("transform", "");
$("#container").css("overflow", "auto");
window.zoomedIn = false;
} else {
console.log("applying zoom");
var top = el.offsetTop;
var left = el.offsetLeft - 0.25*zoomContainer[0].clientWidth;
var translateY = 0.5*zoomContainer[0].clientHeight - top;
var translateX = 0.5*zoomContainer[0].clientWidth - left;
$("#container").css("overflow", "scroll");
zoomContainer.css("transform", "translate(" + 2 * translateX + "px, " + 2 * translateY + "px) scale(2)");
window.zoomedIn = true;
}
});
By controlling the value of translateX and translateY, you can change how the zooming works.
The initial rendered view looks something like this:
Clicking on the A box will zoom you in appropriately:
(Note that clicking D at the end is just showing the reset by zooming back out.)
The problem is: zooming to box D will scale the zoom container such that scrolling to the top and left doesn't work, because the contents overflow. The same happens when zooming to boxes B (the left half is cropped) and C (the top half is cropped). Only with A does the content not overflow outside the container.
In similar situations related to scaling (see CSS3 Transform Scale and Container with Overflow), one possible solution is to specify transform-origin: top left (or 0 0). Because of the way the scaling works relative to the top left, the scrolling functionality stays. That doesn't seem to work here though, because it means you're no longer repositioning the contents to be focused on the clicked box (A, B, C or D).
Another possible solution is to add a margin-left and a margin-top to the zoom container, which adds enough space to make up for the overflowed contents. But again: the translate values no longer line up.
So: is there a way to both zoom in on a given element, and overflow with a scroll so that contents aren't cropped?
Update: There's a rough almost-solution by animating scrollTop and scrollLeft, similar to https://stackoverflow.com/a/31406704/528044 (see the jsfiddle example), but it's not quite a proper solution because it first zooms to the top left, not the intended target. I'm beginning to suspect this isn't actually possible, because it's probably equivalent to asking for scrollLeft to be negative.
Why not just to reposition the TransformOrigin to 0 0 and to use proper scrollTop/scrollLeft after the animation?
https://jsfiddle.net/b8vLg0ny/7/
Updated: https://jsfiddle.net/b8vLg0ny/13/
If you do not need the animation, the TransformOrigin can always stays 0 0 and only the scrolling is used to show the box.
To make the animation less jumpy use transition only for transform porperty, otherwise the transform-origin gets animated also. I have edited the example with 4x4 elements, but I think it makes sense to zoom a box completely into view, thats why I changed the zoom level. But if you stay by zoom level 2 and the grid size 15x15 for instance, then with this approach really precise origin should be calculated for transform, and then also the correct scrolling.
Anyway I don't know, if you find this approach useful.
Stack snippet
var zoomedIn = false;
var zoomContainer = $("#zoom-container");
$(".box").click(function(event) {
var el = this;
if (zoomedIn) {
zoomContainer.css({
transform: "scale(1)",
transformOrigin: "0 0"
});
zoomContainer.parent().scrollTop(0).scrollLeft(0);
zoomedIn = false;
return;
}
zoomedIn = true;
var $el = $(el);
animate($el);
zoomContainer.on('transitionend', function(){
zoomContainer.off('transitionend');
reposition($el);
})
});
var COLS = 4, ROWS = 4,
COLS_STEP = 100 / (COLS - 1), ROWS_STEP = 100 / (ROWS - 1),
ZOOM = 4;
function animate($box) {
var cell = getCell($box);
var col = cell.col * COLS_STEP + '%',
row = cell.row * ROWS_STEP + '%';
zoomContainer.parent().css('overflow', 'hidden');
zoomContainer.css({
transition: 'transform 0.2s ease-in-out',
transform: "scale(" + ZOOM + ")",
transformOrigin: col + " " + row
});
}
function reposition($box) {
zoomContainer.css({
transition: 'none',
transform: "scale(" + ZOOM + ")",
transformOrigin: '0 0'
});
zoomContainer.parent().css('overflow', 'auto');
$box.get(0).scrollIntoView();
}
function getCell ($box) {
var idx = $box.index();
var col = idx % COLS,
row = (idx / ROWS) | 0;
return { col: col, row: row };
}
* { margin: 0; }
body, html { height: 100%; }
#container {
height: 100%;
width: 50%;
margin: 0 auto;
overflow: hidden;
}
#zoom-container {
height: 100%;
width: 100%;
will-change: transform;
}
.box {
float: left;
width: 25%;
height: 25%;
color: white;
text-align: center;
}
.red { background: red; }
.blue { background: blue; }
.green { background: green; }
.black { background: black; }
.l { opacity: .3 }
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
<div class="box red l">E</div>
<div class="box blue l">F</div>
<div class="box green l">G</div>
<div class="box black l">H</div>
<div class="box red">I</div>
<div class="box blue">J</div>
<div class="box green">K</div>
<div class="box black">L</div>
<div class="box red l">M</div>
<div class="box blue l">N</div>
<div class="box green l">O</div>
<div class="box black l">P</div>
</div>
</div>
I'm answering my own question, since I'm fairly confident that it's actually not possible with the given requirements. At least not without some hackery that would cause problems visually, e.g., jumpy scrolling by animating scrollTop after switching transform-origin to 0, 0 (which removes the cropping by bringing everything back into the container).
I'd love for someone to prove me wrong, but it seems equivalent to asking for scrollLeft = -10, something that MDN will tell you is not possible. ("If set to a value less than 0 [...], scrollLeft is set to 0.")
If, however, it's acceptable to change the UI from scrolling, to zooming and dragging/panning, then it's achievable: https://jsfiddle.net/jegn4x0f/5/
Here's the solution with the same context as my original problem:
HTML:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<button id="zoom-out">Zoom out</button>
<div id="container">
<div id="inner-container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
</div>
</div>
</div>
JavaScript:
//
// credit for the approach goes to
//
// https://stackoverflow.com/questions/35252249/move-drag-pan-and-zoom-object-image-or-div-in-pure-js#comment58224460_35253567
//
// and the corresponding example:
//
// https://jsfiddle.net/j8kLz6wm/1/
//
// in a real-world setting, you
// wouldn't keep this information
// on window. this is just for
// the demonstration.
window.zoomedIn = false;
// stores the initial translate values after clicking on a box
window.translateY = null;
window.translateX = null;
// stores the incremental translate values based on
// applying the initial translate values + delta
window.lastTranslateY = null;
window.lastTranslateX = null;
// cursor position relative to the container, at
// the time the drag started
window.dragStartX = null;
window.dragStartY = null;
var handleDragStart = function(element, xCursor, yCursor) {
window.dragStartX = xCursor - element.offsetLeft;
window.dragStartY = yCursor - element.offsetTop;
// disable transition animations, since we're starting a drag
$("#zoom-container").css("transition", "none");
};
var handleDragEnd = function() {
window.dragStartX = null;
window.dragStartY = null;
// remove the individual element's styling for transitions
// which brings back the stylesheet's default of animating.
$("#zoom-container").css("transition", "");
// keep track of the translate values we arrived at
window.translateY = window.lastTranslateY;
window.translateX = window.lastTranslateX;
};
var handleDragMove = function(xCursor, yCursor) {
var deltaX = xCursor - window.dragStartX;
var deltaY = yCursor - window.dragStartY;
var translateY = window.translateY + (deltaY / 2);
// the subtracted value here is to keep the letter in the center
var translateX = window.translateX + (deltaX / 2) - (0.25 * $("#inner-container")[0].clientWidth);
// fudge factor, probably because of percentage
// width/height problems. couldn't really trace down
// the underlying cause. hopefully the general approach
// is clear, though.
translateY -= 9;
translateX -= 4;
var innerContainer = $("#inner-container")[0];
// cap all values to prevent infinity scrolling off the page
if (translateY > 0.5 * innerContainer.clientHeight) {
translateY = 0.5 * innerContainer.clientHeight;
}
if (translateX > 0.5 * innerContainer.clientWidth) {
translateX = 0.5 * innerContainer.clientWidth;
}
if (translateY < -0.5 * innerContainer.clientHeight) {
translateY = -0.5 * innerContainer.clientHeight;
}
if (translateX < -0.5 * innerContainer.clientWidth) {
translateX = -0.5 * innerContainer.clientWidth;
}
// update the zoom container's translate values
// based on the original + delta, capped to the
// container's width and height.
$("#zoom-container").css("transform", "translate(" + (2*translateX) + "px, " + (2*translateY) + "px) scale(2)");
// keep track of the updated values for the next
// touchmove event.
window.lastTranslateX = translateX;
window.lastTranslateY = translateY;
};
// Drag start -- touch version
$("#container").on("touchstart", function(event) {
if (!window.zoomedIn) {
return true;
}
var xCursor = event.originalEvent.changedTouches[0].clientX;
var yCursor = event.originalEvent.changedTouches[0].clientY;
handleDragStart(this, xCursor, yCursor);
});
// Drag start -- mouse version
$("#container").on("mousedown", function(event) {
if (!window.zoomedIn) {
return true;
}
var xCursor = event.clientX;
var yCursor = event.clientY;
handleDragStart(this, xCursor, yCursor);
});
// Drag end -- touch version
$("#inner-container").on("touchend", function(event) {
if (!window.zoomedIn) {
return true;
}
handleDragEnd();
});
// Drag end -- mouse version
$("#inner-container").on("mouseup", function(event) {
if (!window.zoomedIn) {
return true;
}
handleDragEnd();
});
// Drag move -- touch version
$("#inner-container").on("touchmove", function(event) {
// prevent pull-to-refresh. could be smarter by checking
// if the page's scroll y-offset is 0, and even smarter
// by checking if we're pulling down, not up.
event.preventDefault();
if (!window.zoomedIn) {
return true;
}
var xCursor = event.originalEvent.changedTouches[0].clientX;
var yCursor = event.originalEvent.changedTouches[0].clientY;
handleDragMove(xCursor, yCursor);
});
// Drag move -- click version
$("#inner-container").on("mousemove", function(event) {
// prevent pull-to-refresh. could be smarter by checking
// if the page's scroll y-offset is 0, and even smarter
// by checking if we're pulling down, not up.
event.preventDefault();
// if we aren't dragging from anywhere, don't move
if (!window.zoomedIn || !window.dragStartX) {
return true;
}
var xCursor = event.clientX;
var yCursor = event.clientY;
handleDragMove(xCursor, yCursor);
});
var zoomInTo = function(element) {
console.log("applying zoom");
var top = element.offsetTop;
// the subtracted value here is to keep the letter in the center
var left = element.offsetLeft - (0.25 * $("#inner-container")[0].clientWidth);
var translateY = 0.5 * $("#zoom-container")[0].clientHeight - top;
var translateX = 0.5 * $("#zoom-container")[0].clientWidth - left;
$("#container").css("overflow", "scroll");
$("#zoom-container").css("transform", "translate(" + (2*translateX) + "px, " + (2*translateY) + "px) scale(2)");
window.translateY = translateY;
window.translateX = translateX;
window.zoomedIn = true;
}
var zoomOut = function() {
console.log("resetting zoom");
window.zoomedIn = false;
$("#zoom-container").css("transform", "");
$("#zoom-container").css("transition", "");
window.dragStartX = null;
window.dragStartY = null;
window.dragMoveJustHappened = null;
window.translateY = window.lastTranslateY;
window.translateX = window.lastTranslateX;
window.lastTranslateX = null;
window.lastTranslateY = null;
}
$(".box").click(function(event) {
var element = this;
var zoomContainer = $("#zoom-container");
if (!window.zoomedIn) {
zoomInTo(element);
}
});
$("#zoom-out").click(function(event) {
zoomOut();
});
CSS:
* {
margin: 0;
}
body,
html {
height: 100%;
}
#container {
height: 100%;
width: 50%;
margin: 0 auto;
}
#inner-container {
width: 100%;
height: 100%;
}
#zoom-container {
height: 100%;
width: 100%;
transition: transform 0.2s ease-in-out;
}
.box {
float: left;
width: 50%;
height: 50%;
color: white;
text-align: center;
display: block;
}
.red {
background: red;
}
.blue {
background: blue;
}
.green {
background: green;
}
.black {
background: black;
}
I pieced this together from another question (Move (drag/pan) and zoom object (image or div) in pure js), where the width and height are being changed. That doesn't quite apply in my case, because I need to zoom into a specific element on the page (with a lot boxes than in a 2x2 grid). The solution from that question (https://jsfiddle.net/j8kLz6wm/1/) shows the basic approach in pure JavaScript. If you have jQuery available, you can probably just use jquery.panzoom.
Update
I got stuck on scroll bars not showing all the time, so I need to investigating that part, so that code is commented out and instead I use a delay to move the clicked box into view.
Here is my fiddle demo, which I use to play with, to figure out how to solve the scroll bar issue.
Side note: In a comment made by #AVAVT, I would like to link to his post here, as that might help someone else, which I find as an interesting alternative in some cases.
(function(zoomed) {
$(".box").click(function(event) {
var el = this, elp = el.parentElement;
if (zoomed) {
zoomed = false;
$("#zoom-container").css({'transform': ''});
} else {
zoomed = true;
/* this zooms correct but show 1 or none scroll for B,C,D so need to figure out why
var tro = (Math.abs(elp.offsetTop - el.offsetTop) > 0) ? 'bottom' : 'top';
tro += (Math.abs(elp.offsetLeft - el.offsetLeft) > 0) ? ' right' : ' left';
$("#zoom-container").css({'transform-origin': tro, 'transform': 'scale(2)'});
*/
$("#zoom-container").css({'transform-origin': '0 0', 'transform': 'scale(2)'});
/* delay needed before scroll into view */
setTimeout(function() {
el.scrollIntoView();
},250);
}
});
})();
* { margin: 0; }
body, html { height: 100%; }
#container {
height: 100%;
width: 50%;
overflow: auto;
margin: 0 auto;
}
#zoom-container {
height: 100%;
width: 100%;
transition: all 0.2s ease-in-out;
}
.box {
float: left;
width: 50%;
height: 50%;
color: white;
text-align: center;
display: block;
}
.red {
background: red;
}
.blue {
background: blue;
}
.green {
background: green;
}
.black {
background: black;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="container">
<div id="zoom-container">
<div class="box red">A</div>
<div class="box blue">B</div>
<div class="box green">C</div>
<div class="box black">D</div>
</div>
</div>
have 3 images using JavaScript am making them to slide from left to right for the body background of html but the images are just appearing is there any thing i have to do so that they smoothly slide.
FYI: I have added a div to Preview.
Hear is the
JSFiddle
var bgArr = [
"http://foxarc.com/en/cfxs/images/masks.jpg",
"http://foxarc.com/en/cfxs/images/brushes.jpg",
"http://foxarc.com/en/cfxs/images/text.jpg"
];
var i = 0;
// Start the slide show
setInterval(function() {
$("#demo").css("background-image", "url(" + bgArr[i] + ")");
(i < bgArr.length - 1) ? i++ : i = 0
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div
id="demo"
style="text-align:center;
width:90%;
height:310px;
overflow:hidden;
border-style:dashed;
border-width:1px;">
<p style="margin-top:83px;"></p>
</div>
I think the best solution is to create 2 divs inside of body
<div class="background-1"></div>
<div class="background-2"></div>
and put them under it
body {
position: relative;
background: transparent;
overflow-x: hidden;
}
.background-1, .background-2 {
position: absolute;
z-index: -1;
width: 100%;
height: 100%;
}
Then create a custom slider
$(document).ready(function(){
var bgArr = ["http://foxarc.com/en/cfxs/images/masks.jpg",
"http://foxarc.com/en/cfxs/images/brushes.jpg",
"http://foxarc.com/en/cfxs/images/text.jpg"];
var i = 0;
var $bg1 = $('.background-1').css('background-image', 'url('+bgArr[0]+')')
.css('left', '0%');
var $bg2 = $('.background-2').css('background-image', 'url('+bgArr[1]+')')
.css('left', '-100%');
var bgSlide = function($bg) {
$bg.animate({ left: '+=100%' }, 600, function(){
if(parseInt($bg.css('left')) > 0) {
$bg.css('left', '-100%');
(i < bgArr.length-1) ? i++ : i=0;
$bg.css("background-image", "url("+bgArr[i]+")");
}
} );
}
setInterval(function() {
bgSlide($bg1);
bgSlide($bg2);
}, 2000);
});
Example: jsfiddle
See this example https://jsfiddle.net/kevalbhatt18/0Lr9uvt0/1/ with animate()
without animate() : https://jsfiddle.net/kevalbhatt18/0Lr9uvt0/2/
What is .animate()
See this example https://jsfiddle.net/kevalbhatt18/0Lr9uvt0/5/ in this example i use jquery ui for left right effect
$('.test').css({
'background-image': "url('" + bgArr[i] + "')"
});
(i < bgArr.length - 1) ? i++ : i = 0
}, 2000);
And apply css
.test{
-webkit-transition: background-image 0.2s ease-in-out;
transition: background-image 0.2s ease-in-out;
}
I have an image with a box shadow one it, but when I animate it, the box shadow seems to take on a life of its own, as seen here:
example
It happens the same way in both chrome, firefox, and IE.
I am perplexed and, more importantly at a loss at how to fix it so it looks pretty.
Thanks for any thoughts or answers about to fix this or why it is happening.
html/js:
<div id="sliderPane">
<div id="slider0" class="slider"><img src="1.jpg"/></div>
<div id="slider1" class="slider"><img src="2.jpg"/></div>
<div id="slider2" class="slider"><img src="3.jpg"/></div>
<div id="numSliders">3</div>
</div>
<script type="text/javascript">
var numsliders;
var currentSlider = 0;
var interval;
var slideWidth;
$('#slider0').css('opacity',1);
$(document).ready(function(){
numsliders = parseInt( $('#numSliders').html() );
$('#slider0').css('left', '62px');
$('#slider0').css('height', '200px');
$('#slider0').css('width', '200px');
$('#slider0').css('top', '20px');
$('#slider0').css('opacity', '1');
slideWidth = $('#slider0').width();
});
interval = window.setInterval(nextSlider, 5000);
function nextSlider() {
specificSlider((currentSlider + 1)%numsliders);
}
function specificSlider(sliderNumber){
//alert('oldslide: ' + currentSlider + " new sloide: " + sliderNumber);
window.clearInterval(interval);
// move the next slider on deck
$('#slider' + sliderNumber).css('left', $('#sliderPane').css('width'));
$('#slider' + sliderNumber).css('top', '70px');
$('#slider' + sliderNumber).css('hieght', '100px');
$('#slider' + sliderNumber).css('width', '100px');
//alert('lol');
// move old slide off,
$('#slider' + currentSlider).animate({
left: '-80px',
top: '50px',
hieght: '100px',
width: '100px',
opacity: 0
},900,null);
// new slide on
$('#slider' + sliderNumber).animate({
left: ($('#sliderPane').width() / 2 - slideWidth / 2) + 'px',
height: '200px',
width: '200px',
top: '20px',
opacity: 1
},900,null);
currentSlider = sliderNumber;
interval = window.setInterval(nextSlider, 5000);
}
</script>
css:
#sliderPane{
height: 200px;
position: relative;
overflow: hidden;
background-image: url('sliderBG.png');
background-size: 100% 100%;
padding: 20px 0;
}
.slider{
position: absolute;
opacity: 0;
top: -300px;
box-shadow: 2px 2px 10px 5px rgba(0,0,0,.4);
}
#numSliders{
visibility: hidden;
}
In order for you to accept an answer:
<div id="sliderPane">
<div id="slider0" class="slider"><img src="1.jpg"/></div>
<div id="slider1" class="slider"><img src="2.jpg"/></div>
<div id="slider2" class="slider"><img src="3.jpg"/></div>
<div id="numSliders">3</div>
</div>
<script type="text/javascript">
var numsliders;
var currentSlider = 0;
var interval;
var slideWidth;
$('#slider0').css('opacity',1);
$(document).ready(function(){
numsliders = parseInt( $('#numSliders').html() );
$('#slider0').css('left', '62px');
$('#slider0').css('height', '200px');
$('#slider0').css('width', '200px');
$('#slider0').css('top', '20px');
$('#slider0').css('opacity', '1');
slideWidth = $('#slider0').width();
});
interval = window.setInterval(nextSlider, 5000);
function nextSlider() {
specificSlider((currentSlider + 1)%numsliders);
}
function specificSlider(sliderNumber){
//alert('oldslide: ' + currentSlider + " new sloide: " + sliderNumber);
window.clearInterval(interval);
// move the next slider on deck
$('#slider' + sliderNumber).css('left', $('#sliderPane').css('width'));
$('#slider' + sliderNumber).css('top', '70px');
$('#slider' + sliderNumber).css('height', '100px');
$('#slider' + sliderNumber).css('width', '100px');
//alert('lol');
// move old slide off,
$('#slider' + currentSlider).animate({
left: '-80px',
top: '50px',
height: '100px',
width: '100px',
opacity: 0
},900,null);
// new slide on
$('#slider' + sliderNumber).animate({
left: ($('#sliderPane').width() / 2 - slideWidth / 2) + 'px',
height: '200px',
width: '200px',
top: '20px',
opacity: 1
},900,null);
currentSlider = sliderNumber;
interval = window.setInterval(nextSlider, 5000);
}
</script>
I'm working on a site based on this: http://inner.geek.nz/javascript/parallax/
All's well except I'm getting a jump down (by whatever px is set in calcParallax(xx, x, posY))
on scroll. This number should be where the image ends not where it begins — it should begin scrollTop or 0. Not sure what I'm doing wrong, I've pretty much taken the structure verbatim from the above link without the #cloud object or relevant script.
Here's what I have:
<script type="text/javascript">
function calcParallax(tileheight, speedratio, scrollposition) {
return ((tileheight) - (Math.floor(scrollposition / speedratio) % (tileheight+1)));
}
window.onload = function() {
window.onscroll = function() {
var posX = (document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : window.pageXOffset;
var posY = (document.documentElement.scrollTop) ? document.documentElement.scrollTop : window.pageYOffset;
var ground = document.getElementById('ground');
var groundparallax = calcParallax(53, 8, posY);
ground.style.backgroundPosition = "0 " + groundparallax + "px ";
document.getElementById('javascriptcode').onscroll = function() {
var posX = (this.scrollLeft) ? this.scrollLeft : this.pageXOffset;
var j = calcParallax(53, 16, posX);
console.log('scroll js: '+ j);
document.getElementById('javascriptcode').style.backgroundPosition = j + "px 0";
}
}
</script>
Any help would be much appreciated
Use this example instead. It uses a different jQuery that seems more stable and does not jump around like the script from inner geek.
http://www.stevefenton.co.uk/cmsfiles/assets/File/backgroundparallax.html
I put together a demo on something similar while trying to minimize scripting in the scroll event... I've found that it's jumpy in Firefox and Chrome, and oddly smooth as silk in IE.
Even this game website that uses a combination of Mootools and CSS transitions is a bit jumpy.
CSS
/* Tiled background image */
body {
margin: 0;
padding: 0;
/* Use height of header image for top position */
background: #000 url(http://i201.photobucket.com/albums/aa236/Mottie1/testsite/forums/bgtile.jpg) left 1080px repeat-y;
}
/* Top background image (1920x1080) */
#wrapper {
position: relative;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: url(http://i201.photobucket.com/albums/aa236/Mottie1/testsite/forums/bg1.jpg) center top repeat-x;
z-index: 100;
}
/* Page Title image */
#header {
height: 350px;
background: url(http://i201.photobucket.com/albums/aa236/Mottie1/testsite/forums/title.png) center 40px no-repeat;
}
/* Content Block with 55% opacity background image */
.block {
width: 600px;
height: 500px;
margin: 20px auto;
border: #333 1px solid;
padding: 20px;
background: url(http://i201.photobucket.com/albums/aa236/Mottie1/testsite/forums/bg-black-55.png);
}
.block h3 {
font-family: 'Arial Black', Gadget, sans-serif;
font-size: 130%;
}
HTML
<body> <!-- contains repeated background image -->
<div id="wrapper"> <!-- contains top image -->
<div id="header"></div> <!-- contains the page title image -->
<div class="block"> <!-- contains 55% opacity background image -->
<h3>Block 1</h3>
<div class="content">Content 1.</div>
</div>
<div class="block">
<h3>Block 2</h3>
<div class="content">Content 2.</div>
</div>
<div class="block">
<h3>Block 3</h3>
<div class="content">Content 3.</div>
</div>
<div class="block">
<h3>Block 4</h3>
<div class="content">Content 4.</div>
</div>
<div class="block">
<h3>Block 5</h3>
<div class="content">Content 5.</div>
</div>
</div>
</body>
Script
$(document).ready(function(){
// defaults
var st, win = $(window)[0],
body = $('body')[0],
doc = (jQuery.support.boxModel) ? document.documentElement : document.body,
wrap = $('#wrapper')[0],
// Set top background image height here
imgH = 1080; // top image height
// vertical parallax scroll
$(win).scroll(function(){
st = (win.pageYOffset || doc.scrollTop );
if (st < imgH) { wrap.style.backgroundPosition = 'center ' + (st/4) + 'px'; } // limit moving top image only when in view
body.style.backgroundPosition = 'left ' + ( imgH + st/4) + 'px';
});
});
Change your 53 to the exact height of each element.
The only thing I can't figure out about this script is it jumps slightly vertically when I change it to a scroll left function.
var element = document.getElementById('element');
var elementparallax = calcParallax(7000, .5, posX);
element.style.backgroundPosition = " 0" + elementparallax + "px";
};
P.S. You can change the vertical scroll to horizontal by changing posY to posX and in = "0_" + elementparalax to = "_0"