I am trying to slide image from left to right and after a set point it should again slide in reverse direction. This is my code somehow its not working as i am going wrong somewhere in the if statement.
(function($) {
var x = 0;
var y = 0;
//cache a reference to the banner
var banner = $("#banner");
// set initial banner background position
banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');
// scroll up background position every 90 milliseconds
window.setInterval(function() {
banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
x++;
//x--;
//if you need to scroll image horizontally -
// uncomment x and comment y
}, 90);
if ($(banner.offset().left > 40) {
banner.css("backgroundPosition", "0px 0px ");
}
})(jQuery);
div#banner {
width: 960px;
height: 200px;
margin: auto;
background: url(http://cdn-careers.sstatic.net/careers/gethired/img/companypageadfallback-leaderboard-2.png?v=59b591051ad7) no-repeat 0 0;
}
div#banner p {
font: 15px Arial, Helvetica, sans-serif;
color: white;
position: relative;
left: 20px;
top: 120px;
width: 305px;
padding: 20px;
background: black;
text-align: center;
text-transform: uppercase;
letter-spacing: 20px;
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner"></div>
Firstly, you are using a IIFE (Immediately Invoked Function Expression) instead of a DOM ready handler. This code will only work if placed after the elements it references.
Use this shortcut for DOM ready that also provides a locally scoped $
jQuery(function ($) {...});
You also have a missing closing paren (or really a redundant $( as it is already a jQuery object):
JSFiddle: http://jsfiddle.net/g0gn4osy/7/
You also need to have a delta value that changes the direction when you hit a bound value. I sped up your timing to show this:
jQuery(function ($) {
var delta = 1;
var y = 0;
//cache a reference to the banner
var $banner = $("#banner");
// set initial banner background position
$banner.css('background-position', '0px' + ' ' + y + 'px');
// scroll up background position every 90 milliseconds
window.setInterval(function () {
var position = parseInt($banner.css('background-position'));
if (position >= 40 || position < 0) {
delta = -delta;
}
position += delta;
$banner.css("background-position", position + 'px' + ' ' + y + 'px');
}, 10);
});
Notes:
You also had backgroundPosition instead of background-position for the CSS property. I prefer to use the values that match the css properties (personal choice only for maintenance).
To avoid the redundant $() issue, I recommend you prefix jQuery variables with $. e.g. $banner in this case. Then it becomes obvious you are dealing with a jQuery object.
I tend to use the current position of an element, rather than keep a global var running. This allows for external influences to change the position and still work. Have removed x and just use position.
Inspired and modelled on Gone Coding's answer.
I have expanded his example to take into account the image width and the view pane DIV width.
It now scrolls to image end and then back. You never scroll off the canvas or past a visible part of the image. It doesn't jerk or rock, just switches direction.
With awareness of the viewing box width you can easily adjust the width of div#banner to fit the display space and the code adjusts. Just remember to set the background image width imgW var.
I have also added:
Visual indicator for testing with a current position and scroll direction. (With -1 is scrolling left, +1 is scrolling right),
Image start position in px. (A minus number or Zero. With 0 is start image at left, Minus number is start image part way through i.e image pre-scrolled left)
Image start vertical position in px (to vertically pull image up/down. Useful if view pane height shorter than image height and you want to tweak what is seen)
Things to do:
Change image URL (background: url(IMAGENAMEHERE) no-repeat 0 0;)
Insert image width (var imgW = #PIXELWIDTH#;)
Play with WIDTH: and HEIGHT: of view pane (div#banner)
Enjoy.
Fiddle
Have a play http://jsfiddle.net/Lm5yk46h/
Image credit Mark Higgins | Dreamstime.com Image source for purchase
Javascript
jQuery(function ($) {
var delta = 1;
var imgW = 3000;//width of image px
var imgY = 0;//to shift image view vertically px (Minus or zero)
//cache ref to #banner
var $banner = $("#banner");
var viewpaneW = $banner.width();
var endpos = (imgW - viewpaneW);
var startpos = 0;//0 or negative number
// set initial banner background position
$banner.css('background-position', startpos + 'px' + ' ' + imgY + 'px');
// scroll background position every 20ms
window.setInterval(function () {
var position = parseInt($banner.css('background-position'));
// minus is left, plus is right
if (position >= 0 ) delta = -delta;//go left
if (position < (-1*endpos)) delta = (-1*delta);//go right
position += delta;//increment posn
$banner.css("background-position", position + 'px' + ' ' + imgY + 'px');
$("#indicator").text('Posn:' + position + ' | direction: ' + delta);
}, 20);
});
CSS
div#canvas {
background-color: #999;
width: 100%;
height: 400px;
margin:0;padding:10px;
}
div#banner {
width: 460px;
height: 300px;
margin: 10px;
background: url(https://digido.net/eg/newcastle-beach-3000x300.jpg) no-repeat 0 0;
}
div#banner p {
font: 13px Arial, Helvetica, sans-serif;
color: white;
position: relative;
left: 0;
top: 310px;
width: 99%;
padding: 10px;
background: black;
text-align: center;
text-transform: uppercase;
letter-spacing: 8px;
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
HTML
<div id="canvas">
<div id="banner">
<p id="indicator">Hit run</p>
</div>
</div>
Just put the if condition inside the setInterval. And check the syntax error. The if doesn't have a closing }:
// scroll up background position every 90 milliseconds
window.setInterval(function() {
banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
x++;
//x--;
if (banner.offset().left > 40) {
banner.css("backgroundPosition", "0px 0px ");
}
}, 90);
Your "if" should be like this:
if ($(banner).offset().left > 40) {
banner.css("backgroundPosition", "0px 0px ");
}
https://jsfiddle.net/wc4b2g97/
your if should be inserted inside your setInterval handler, so it would get evaluated every 90 milliseconds (thank you for correcting me).
Actually, your if is evaluted only the first time, when your javascript file is parse.
Add it into your setInterval and it should work as expected
Related
I'm coding a very tiny small feature, but I'm having problems with the scroll. I need to do a zoom of a div scaling with css:
transform: scale(X,Y)
But my problem is that I don't have a correct left and top scroll in the parent div. I need to know how to calculate the new left and top each time the user press the button "More zoom", I could use translate css property if it is mandatory.
I can use jQuery, but I think this is just a math problem :)
One detail: I need that the image grow from the center.
Picture:
Here is the fiddle:
Fiddle example
i believe you need to mind transform-origin too:
// get element references
var foo = document.querySelector('#foo');
var bar = document.querySelector('#bar');
// fit bar into foo
// the third options argument is optional, see the README for defaults
// https://github.com/soulwire/fit.js
var zoom = 1;
var trans = 50;
var moreZoom = document.querySelector('#moreZoom');
moreZoom.onclick = function(e){
console.log(foo);
bar.style.transform = 'scale(' + (zoom + 0.1) + ',' + (zoom + 0.1) + ')';
zoom = (zoom + 0.1);
bar.style.transformOrigin = (50 / zoom) +'px ' +(50 / zoom )+'px';
}
#foo {
background: #36D7B7;
height: 200px;
width: 400px;
padding: 50px;
overflow: auto;
}
#bar {
background-image: url('http://www.space.com/images/i/000/028/001/original/wing-small-magellanic-cloud-galaxy-1920.jpg?interpolation=lanczos-none&fit=around%7C1440:900&crop=1440:900;*,*');
background-size:cover;
height: 100%;
transform:scale(1);
width: 100%;
}
<script src="https://rawgithub.com/soulwire/fit.js/master/fit.js"></script>
<button id="moreZoom">
More Zoom
</button>
<div id="foo">
<div
http://jsfiddle.net/as20h6t4/5/
I want to position my markers when zoom 18 += 10px up, so what I dit is this:
his._mapsWrapper.subscribeToMapEvent<void>('zoom_changed').subscribe(() => {
this._mapsWrapper.getZoom().then((z: number) => {
this._zoom = z;
if(z === 18) {
$('.marker').css({ 'width' : '25px', 'height' : '25px', 'line-height': '25px', 'top' : '+= 10!important' });
$('.number-id').css({'font-size': '11px'})
}
But it seems not to work can somebody help me out here? Here is a PLUNKER, where you can see this code in src/google-maps/directive/google-map.ts in the method _handleMapZoomChange()
What it does it is setting all the elements to 10px, but what I basically wants is to set the current top position + 10px.
$('.marker').each( function (index) {
console.log(index + ":" + $(this).css('top'));
var currentTop = $(this).css('top');
$(this).css('top', currentTop + '10px');
})
If you are using custom overlay, it can cause unexpected behaviour if you adjust left or top position of the marker, because that is tied to latLng position of the marker.
Instead, just use margin-top css attribute (margin-top: 10px or margin-top: -10px depending on your needs)
The same thing when drawing the marker, don't adjust position like this:
if (point) {
div.style.left = (point.x - 10) + 'px';
div.style.top = (point.y - 10) + 'px';
}
Instead add the offset as margin-top and margin-left to your marker's css:
div.style.cssText = `width: 25px;
height: 25px;
...
margin-top: -10px;
margin-left: -10px;`
I have this following animation:
<!DOCTYPE HTML>
<html>
<head>
<style>
.example_path {
position: relative;
overflow: hidden;
width: 530px;
height: 30px;
border: 3px solid #000;
}
.example_path .example_block {
position: absolute;
background-color: blue;
width: 30px;
height: 20px;
padding-top: 10px;
text-align: center;
color: #fff;
font-size: 10px;
white-space: nowrap;
}
</style>
<script>
function move(elem) {
var left = 0
function frame() {
left+=10 // update parameters
elem.style.left = left + 'mm' // show frame
if (left == 10000) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 1) // draw every 1ms
}
</script>
</head>
<body>
<div onclick="move(this.children[0])" class="example_path">
<div class="example_block"></div>
</div>
</body>
</html>
as you see, the blue block moves out of the rectangle if it crosses it. how do i have the blue block oscillate about the rectangular border to and fro keeping the speed constant throughout ...
(in my case the speed is 10 m/s aka 10 mm/ms)
You need to update code as: Here is working JSfiddle
function move(elem) {
var left = 0
var fwdMove = true;
function frame() {
if (left < 0) {
fwdMove = true;
} else if (left > 520) {
fwdMove = false;
}
fwdMove?left += 10:left -= 10
elem.style.left = left + 'px' // show frame
}
var id = setInterval(frame, 1) // draw every 1ms
}
We begin by adding a variable to track the direction that we're heading in. We don't want to modify how fast you're moving, so we use a positive or negative 1 to affect the position.
var direction = 1; // 1=Right, -1=Left
var left = 0
function frame() {
left+=(10 * direction); // update parameters
Because mm are a print-unit, and we're working in the browser, we'll change it to use px. If you really need to use mm, you'll have to find a way of converting between them for the box to stop at the appropriate spot.
elem.style.left = left + 'px' // show frame
Finally, we check whether we've gone past the bounds of the box, and if so, we put it back in the box and reverse the direction;
if (left <= 0) {
direction = 1; // Begin moving to the left
left = 0; // Put the box back in the path
} else if (left >= (530 - 20)) {
direction = -1; // Begin moving to the right
left = (530 - 20); // Put the box back in the path
}
JSFiddle.
I have implemented a parallax scrolling effect based on a tutorial I found. The effect works great. However, when I specify the background images, I am unable to control the y (vertical) axis. This is causing problems because I'm trying to set locations on multiple layered images.
Any thoughts on what's causing the problem?
Here is one external script:
$(document).ready(function(){
$('#nav').localScroll(800);
//.parallax(xPosition, speedFactor, outerHeight) options:
//xPosition - Horizontal position of the element
//inertia - speed to move relative to vertical scroll. Example: 0.1 is one tenth the speed of scrolling, 2 is twice the speed of scrolling
//outerHeight (true/false) - Whether or not jQuery should use it's outerHeight option to determine when a section is in the viewport
$('#mainimagewrapper').parallax("50%", 1.3);
$('#secondaryimagewrapper').parallax("50%", 0.5);
$('.image2').parallax("50%", -0.1);
$('#aboutwrapper').parallax("50%", 1.7);
$('.image4').parallax("50%", 1.5);
})
This is another external script:
(function( $ ){
var $window = $(window);
var windowHeight = $window.height();
$window.resize(function () {
windowHeight = $window.height();
});
$.fn.parallax = function(xpos, speedFactor, outerHeight) {
var $this = $(this);
var getHeight;
var firstTop;
var paddingTop = 0;
//get the starting position of each element to have parallax applied to it
$this.each(function(){
firstTop = $this.offset().top;
});
if (outerHeight) {
getHeight = function(jqo) {
return jqo.outerHeight(true);
};
} else {
getHeight = function(jqo) {
return jqo.height();
};
}
// setup defaults if arguments aren't specified
if (arguments.length < 1 || xpos === null) xpos = "50%";
if (arguments.length < 2 || speedFactor === null) speedFactor = 0.1;
if (arguments.length < 3 || outerHeight === null) outerHeight = true;
// function to be called whenever the window is scrolled or resized
function update(){
var pos = $window.scrollTop();
$this.each(function(){
var $element = $(this);
var top = $element.offset().top;
var height = getHeight($element);
// Check if totally above or totally below viewport
if (top + height < pos || top > pos + windowHeight) {
return;
}
$this.css('backgroundPosition', xpos + " " + Math.round((firstTop - pos) * speedFactor) + "px");
});
}
$window.bind('scroll', update).resize(update);
update();
};
})(jQuery);
Here is the CSS for one section:
#aboutwrapper {
background-image: url(../images/polaroid.png);
background-position: 50% 0;
background-repeat: no-repeat;
background-attachment: fixed;
color: white;
height: 500px;
width: 100%;
margin: 0 auto;
padding: 0;
}
#aboutwrapper .image4 {
background: url(../images/polaroid2.png) 50% 0 no-repeat fixed;
height: 500px;
width: 100%;
margin: 0 auto;
padding: 0;
}
.image3{
margin: 0 auto;
min-width: 970px;
overflow: auto;
width: 970px;
}
Both of these are being called to achieve the parallax scrolling. I really just want to more specifically control the background image locations. I've tried messing with the CSS background position and I've messed with the first javascript snippet as well. No luck.
just a quick shot, have you tried actually placing the images, either in a div or just using the img src tag to actually move the element rather than manipulating the y axis of a background image?
I have elements which are overlapping and I would like to prevent this. Here is a picture: http://grab.by/cB7t
Also, here is the CSS for those elements:
.navigationItem {
background: #808080;
-webkit-border-radius: 360px;
padding: 1.0em;
text-decoration: none;
color: #fff;
position: absolute;
-webkit-box-shadow: 0px 2px 5px #909090;
font-weight: bold;
text-shadow: 1px 1px 2px #707070;
font-size: 1.0em;
}
And here they are in the HTML:
play
register
our blog
contact us
about us
our rules`
As you can see, I am using them as simple styled links using the HTML a tag. The reason that their positions are absolute is because I am moving them using jQuery:
function moveAll() {
for(var i = 0; i < AMOUNT; i++) {
var random = Math.random() * 500;
$("#nav" + i).animate({"left": random + i + "px"}, "slow");
$("#nav" + i).animate({"top": random + i + "px"}, "slow");
}
}
When they move, though, they sometimes overlap which is annoying. How can I prevent them from overlapping? Thank you for your efforts.
Removing position:absolute would render them side by side.
JSFiddle
But if the whole point is to scatter them around randomly, then you will have to keep track of positioned elements and take that into account when calculating their position. You should save each link's position and calculate every next link's position according to previous already positioned links. There's simply no other way when you want random positions and non overlapping.
Final non-overlapping solution
This is a working example of non-overlapping functionality. If you'd want your links to not even touch, you should change < to <= and > to >= in the if statement condition.
Relevant code
var positions = [];
$(".navigationItem").each(function(){
var ctx = $(this);
var dim = {
width: ctx.outerWidth(),
height: ctx.outerHeight()
};
var success = false;
// repeat positioning until free space is found
while (!success)
{
dim.left = parseInt(Math.random() * 300);
dim.top = parseInt(Math.random() * 300);
var success = true;
// check overlapping with all previously positioned links
$.each(positions, function(){
if (dim.left < this.left + this.width &&
dim.left + dim.width > this.left &&
dim.top < this.top + this.height &&
dim.top + dim.height > this.top)
{
success = false;
}
});
}
positions.push(dim);
ctx.animate({
left: dim.left,
top: dim.top
}, "slow");
});
You can change the position value to relative.
See my example : http://jsfiddle.net/NmmX6/2/
I changed your loop so that it isn't id dependent :
function moveAll() {
$('.navigationItem').each(function(i,e){
var rdm = Math.random() * 500;
$(e).animate({"left":rdm + "px"}, "slow");
$(e).animate({"top": rdm + "px"}, "slow");
});
}
I tested it and did not find one case where it actually overlaps, but check it out.