I have a background image (width = 2000px, height = 400px) sitting behind a div with width and height equal to 400px. My image is split into 5 blocks, all with width and height equal to 400px. I want my image to shift by 400px each time the function is called to emulate a GIF image.
var imageWidth = $("#imageScroll").width();
console.log(imageWidth);
var timer = setInterval(function(){ shiftImage() }, 250);
function shiftImage(){
$("#imageScroll").mouseover (function(){
$("#imageScroll").css({"background-position-x": (imageWidth)});
});
};
});
This is my jQuery code, and I have tried and failed on a lot of different code. imageScroll is the ID of the div that I want the image to be pushed through.
you have to define css of the image so that it repeats itself on the x-axis.
<style>
#imageScroll{
height: 400px;
width: 500px;
background-image: url('./background.jpg');
background-repeat: repeat-x;
}
</style>
then, at the bottom of the page, or in body onload, you should execute the following instructions.
intervalFunc = setInterval(shiftImage, 250);
function shiftImage(){
var currentBackgroundX = $('#imageScroll').css('background-position-x');
split = currentBackgroundX.split("%");
currentBackgroundX = split[0];
currentBackgroundX = parseInt(currentBackgroundX);
$('#imageScroll').css({"background-position-x": (currentBackgroundX + 25) + '%'});
}
I didn't give too much though about the positioning part actually, since that is a completely different subject. But what i'm trying to do here is, change the background-position-x by 25% every 250 miliseconds. You can change the inner workings of the shiftImage function.
If you want to stop the animation at any point, just run
clearInterval(intervalFunc);
Hope this helps
Edit: jsFiddle
Edit 2: edited fiddle link
Edit 3: edited fiddle link
Related
I'm using bxslider to have a carousel of images. The thing is though, the images it receives to display are of somewhat unpredictable sizes. The container size is 243x243. And we know that no image will have a side smaller than 243. So...I'd like to center the image in the container. And either zoom in until the shorter of the two dimensions (L vs W) fills the container at 243, and the longer dimension overflow is hidden.
For the images I'm working with, doing this will be perfect for getting the important details of the picture in the frame.
But I'm having trouble...
I've tried the following to center the picture in the frame:
jQuery(".bx-container").each(function() {
var img_w = jQuery(this).children("img").width();
var img_h = jQuery(this).children("img").height();
var pos_top = (img_h - containerHeight) / 2;
var pos_left = (img_w - containerWidth) / 2;
var pos_top = (243 - img_h) / 2;
var pos_left = (243 - img_w) / 2;
jQuery(this).children("img").css({
'top' : pos_top + 'px',
'left' : pos_left + 'px'
});
});
And I've tried this to position not square images into the frame:
jQuery(".bx-container").each(function(){
var refRatio = 1;
var imgH = jQuery(this).children("img").height();
var imgW = jQuery(this).children("img").width();
if ( (imgW/imgH) < refRatio ) {
jQuery(this).addClass("bx-portrait");
} else {
jQuery(this).addClass("bx-landscape");
}
});
});
I've messed with both scripts and the css but I just can't seem to get it work. It either centers but doesn't resize right. Or resizes but centers wrong. Or does both wrong.
Here's the jsfiddle: http://jsfiddle.net/vgJ9X/298/
Could someone help me out?
Thanks!
EDIT:
New jsfiddle...the portrait ones work right. The landscape images still squish. :(
http://jsfiddle.net/vgJ9X/307/
EDIT:
I THINK it has something to do with relatively positioned elements not being allowed to overlap. Trying to find a fix. If anyone knows, edit the last fiddle I posted.
jQuery(".bx-container img").each(function () {
var w = jQuery(this).width();
var h = jQuery(this).height();
if (w > h) $(this).addClass('bx-landscape');
else $(this).addClass('bx-portrait');
});
Check this Updated JSFiddle
Update
jQuery(".bx-container img").each(function () {
var w = jQuery(this).width();
var h = jQuery(this).height();
if (w > h){
$(this).addClass('bx-landscape');
var trans= -243/2;
$(this).css('-webkit-transform','translateZ('+trans+'px)');
}
else if(h > w){
$(this).addClass('bx-portrait');
var trans= -243/2;
$(this).css('-webkit-transform','translateY('+trans+'px)');
}
});
check this JSFiddle
Update of Update
Found the issue with landscape, the plugin is setting max-width:100%; overriding it with max-width:none; fixes the issue...
Update Of Updated Fiddle
Try this:
img{
position:relative;
height:100%;
width:300px;
}
Simple an clean.
Demo: http://jsfiddle.net/vgJ9X/302/
I did a couple things to your jsfiddle.
First I changed the order of your resize and center functions, so the resize comes first. This way, the smaller images get resized, then centered. I also uncommented the first portion of your code.
You also had a couple of errors in your css. There was an extra closing bracket after img style declaration. Your .bx-portrait img and .bx-landscape img declarations were set to 100%px;.
Update:
Change the css in your two .bx classes to:
.bx-portrait img {
height: 100%;
width: auto;
}
.bx-landscape img {
height: auto;
width: 100%;
}
And add a clearfix to your ul:
.bxslider:after {
content: '';
clear: both;
display: table;
padding: 0;
margin: 0;
}
The height is clipping because .bx-viewport has a set height of 243px but also has a 5px border, which makes the actual internal height 233px. You'll need to make the height 253px to account for the 10px of border. This is why they don't look centered vertically.
DEMO
Why don't you just use background images instead and center them. Here is a demo from your original code
http://jsfiddle.net/8y8df/
If you want to show the full size image, just remove the background-size:contain; from the css.
Let's say I have an image, cat.jpg, and when clicked I want to clone it.
$('img.cat').on("click", function() {
$(this).clone().appendTo('#container');
});
Upon duplication, however, I want the new cat.jpg to appear as half the size of the original. And I want this to continue happening each time a new cat.jpg is clicked.
Any ideas on how to go about accomplishing this? Is it even possible to inject new styling/classes/parameters via .clone()?
It sounds like the following is what you're after:
// If all images are within #container, use $("#container") instead:
$(document).on("click", "img.cat", function () {
var original = $(this);
original.clone().css({
width: original.width() / 2,
height: original.height() / 2
}).appendTo("#container");
});
Fiddle: http://jsfiddle.net/G6XTz/
Of course, you may have wanted the newly added image to be half the size of the last cat image, rather than the cat image clicked:
Fiddle2: http://jsfiddle.net/G6XTz/1/
Caveat:
The width and height can only divide so far; eventually you'll run into some problems. Better check the result of division first, and make a decision to do something else when it makes sense.
Just setting the width to half seems to be enough with an img element, the height gets set automatically in proportion to the width:
$('#container').on('click','img.cat', function() {
$(this).clone()
.appendTo('#container')
.width(function(i,v) { return v/2;});
});
Demo: http://jsfiddle.net/Mr2x8/
But if you find you need to set the width and the height here's one way to do it:
$('#container').on('click','img.cat', function() {
var $this = $(this);
$this.clone()
.appendTo('#container')
.width($this.width()/2)
.height($this.height()/2);
});
Demo: http://jsfiddle.net/Mr2x8/1/
id do this:
$(this).clone().addClass('small').appendTo('#container');
this adds the css class small to the clone of this.
Create a new class with the specific new styling you want to get changed dynamicaly in your CSS file.
.newClass {
//example green outline
outline: solid thin green;
}
And then modify your script:
$('img.cat').on("click", function() {
$(this).clone().addClass('newClass').appendTo('#container');
});
EDIT :
If the only thing you want to change is the size of the img for lets say 10% each click then:
$('img.cat').on("click", function() {
var width = $(this).width() * 0.9;
var height = $(this).height() * 0.9;
$(this).clone().css({"width":width+"px", "height":height+"px"}).appendTo('#container');
});
The above code will produce the same image but 10% smaller than the image clicked .
If you want to click only the initial image then simply put the width and height variable outside the click function and update them inside for each click.
NOTE :
In the css() you add +"px" if initial width is in px else you add +"%" if it is in percentage.
I'm trying to make some DOM element rotate smoothly around a fixed point. I'm writing this from scratch using jQuery and no matter what update speed I choose for the setInterval or how small I go with the amount of degrees the orbit advances on each loop, I get this janky staircase animation effect. I've tried using jquery's .animate instead of the .css hoping it would smooth things out but I cant seem to get it to work. Any help is appreciated.
In other words, it's not as smooth as rotating an image in HTML5 canvas. I want to make it smoother.
Here is a jsFiddle demonstrating the issue.
Notice how the animation is not quite smooth?
For reference, here is the code:
HTML
<div id="div"></div>
<div class="dot"></div>
<button class="stop">STOP</button>
<button class="start">START</button>
CSS
#div{
position:absolute;
height: 20px;
width: 20px;
background-color: #000;
}
.dot{
position:absolute;
width: 5px;
height: 5px;
background-color: #000;
}
button{
position:absolute;
}
.stop{
top:200px;
}
.start{
top:225px;
}
THE ALL IMPORTANT JAVASCRIPT
$(document).ready(function(){
$('#div').data('angle', 90);
var interval;
$('.stop').on('click', function(){
if(interval){
clearInterval(interval);
interval = undefined;
}
});
$('.start').on('click', function(){
if(!interval){
interval = setBoxInterval();
}
});
interval = setBoxInterval();
});
function drawOrbitingBox(degrees){
var centerX = 100,
centerY = 100,
div = $('#div'),
orbitRadius = 50;
//dot might not be perfectly centered
$('.dot').css({left:centerX, top:centerY});
//given degrees (in degrees, not radians), return the next x and y coords
function coords(degrees){
return {left:centerX + (orbitRadius * Math.cos((degrees*Math.PI)/180)),
top :centerY - (orbitRadius * Math.sin((degrees*Math.PI)/180))};
}
//increment the angle of the object and return new coords through coords()
function addDegrees(jqObj, degreeIncrement){
var newAngle = jqObj.data('angle') + degreeIncrement;
jqObj.data('angle', newAngle);
return coords(newAngle);
}
//change the left and top css property to simulate movement
// I've tried changing this to .animate() and using the difference
// between current and last position to no avail
div.css(addDegrees(div, degrees), 1);
}
function setBoxInterval(){
var interval = window.setInterval(function(){
drawOrbitingBox(-0.2); //This is the degree increment
}, 10); //This is the amount of time it takes to increment position by the degree increment
return interval;
}
I'd rather not resort to external libraries/plugins but I will if that's the accepted way of doing this kind of stuff. Thank you for your time.
That's because the value you set for top and left properties is rounded up. You should try using CSS Transforms.
Combining CSS Animations/Transitions and CSS Transforms you should also be able to get the animation without JavaScript.
Oh, I run into that myself!
There is actually nothing you can do, the stuttering you see is the pixel size. The pixel is the minimal step for css based animations, you can't do "half pixels" or "0.2 pixels". You will see that the same keeps happening with css3 animations.
The only solution is to speed up your animation, i'm afraid.
Also, cosndsider using rquestAnimationFrame instead of interval: https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame
Recently I tried to make the images in lightbox. If you click the image it show off in lightbox effect. But Some of the Reason, Lightbox is not centering properly in a window size. For Example if you click the image it loaded in lightbox but for the first time it lightbox load in bottom of the site and again you click the image it align properly.
here is the screenshot what i exactly saying.
First Screenshot looks when you click the image when page load.
First Time Click the Image:
Second Time Click the Image:
For the First Time it getting alignment problem.
For the Second Time it not getting alignment problem(Without Page Load)
Javascript:
<script>
jQuery(document).ready(function() {
jQuery("img").click(function() {
var img_path;
if ($(this).parent('a').length) {
img_path = $(this).parent('a').prop('href');
}
else
{
img_path = $(this).attr('src');
}
jQuery(".cplightbox1").html(jQuery("<img>").attr("src", img_path));
jQuery(".cpoutter").css('display', 'block');
jQuery('.cpoutter').animate({'opacity': '1'});
//jQuery('.lightbox').animate({'opacity':'1.00'});
var cplightbox = document.getElementsByClassName('cplightbox')[0];
var cpoutter = document.getElementsByClassName('cpoutter')[0];
cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";
return false;
});
});
</script>
HTML CODE:
Here is the Fiddle
http://jsfiddle.net/rCUGD/7/
But Some How this Script is working properly in jsfiddle.net. May Be I messup with script or css
I am Not where i made a mistake
EDITED:
Now After #JustAnil Here is the Screenshot:
After the second click it should show like this normal
Checkout this working JSFiddle.
You need to change the following lines (where you calculate the offset).
Change the following lines:
var cplightbox = document.getElementsByClassName('cplightbox')[0];
var cpoutter = document.getElementsByClassName('cpoutter')[0];
cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";
To:
var cplightbox = document.getElementsByClassName('cplightbox')[0];
// We need the actual height of the image so grab it from the "inner" container
var cplightbox1 = document.getElementsByClassName('cplightbox1')[0]; // New Line
var cpoutter = document.getElementsByClassName('cpoutter')[0];
// Calculate the (negative) offset from the width & height
cplightbox.style.marginLeft = "-"+$(cplightbox1).width() / 2 + "px";
cplightbox.style.marginTop = "-"+$(cplightbox1).height() / 2 + "px";
// ^ Negative offset so we can vertically and horizontally center it.
Finally
Change your CSS from:
.cplightbox {
margin-left: auto;
margin-right:auto;
width:auto;
height:auto;
display:inline-block;
}
To:
.cplightbox {
position:fixed;
top:50%;
left:50%;
display:inline-block;
}
Checkout this question CSS Vertically & Horizontally Center Div (Thats how to center a div to the middle of the screen).
Then alter your javascript to calculate the negative offset (dependant on how big the picture is [ie 50% of the width & height])
View this working JSFiddle.
I am using this great jQuery plugin to have the fullscreen backgound for my website.
This plugin currently fills the entire background on the screen, I was wondering if it is possible to give it a margin.
For instance I want to have a gap in the right side of the screen for 150px (so I can see the body background) and the rest of the page will be filled with backstretch.
I have played with _adjustBG function but I can't get this working.
Any helps will be appreciated.
Since the author of this plugin didn't make an option for margin, I'll tweak it for you.
Below is the modified _adjustBG() function that you may need.
Just open the file "jquery.backstretch.js" (the normal version, not the minimized) then replace the original _adjustBG() function (at the end of file) with this function.
function _adjustBG(fn) {
var rightMargin = 150; //--- edit the margin value here
try {
bgCSS = {left: 0, top: 0}
bgWidth = rootElement.width()-rightMargin;
bgHeight = bgWidth / imgRatio;
// Make adjustments based on image ratio
// Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
if(bgHeight >= rootElement.height()) {
bgOffset = (bgHeight - rootElement.height()) /2;
if(settings.centeredY) $.extend(bgCSS, {top: "-" + bgOffset + "px"});
} else {
bgHeight = rootElement.height();
bgWidth = bgHeight * imgRatio-rightMargin;
bgOffset = (bgWidth - rootElement.width()) / 2;
if(settings.centeredX) $.extend(bgCSS, {left: "-" + bgOffset + "px"});
}
$("#backstretch, #backstretch img:last").width( bgWidth ).height( bgHeight )
.filter("img").css(bgCSS);
} catch(err) {
// IE7 seems to trigger _adjustBG before the image is loaded.
// This try/catch block is a hack to let it fail gracefully.
}
// Executed the passed in function, if necessary
if (typeof fn == "function") fn();
}
Update:
By poking around w/ console, I found that if you subtract 150 from the width of the background-image, it will, by default, give you a margin on the right. You may want to adjust the height so your image scales, but, maybe something like this to run in $(document).ready():
var $bg = $('#backstretch');
var newImgWidth = $bg.width() - 150;
$bg.css('width', newImgWidth);
If IE6 is no issue, you can try to put the following in your stylesheet:
#backstretch{
width: auto !important;
right: 150px;
}
I tried this on the backstretch homepage and it worked as I would expect. As I am not totally familiar with this plugin please feel free to correct me.