I'm creating a parallax website but I'm using the code of some nice tutorial that I found.
This tutorial came with some JS to change the scroll speed of some sprites using the tag "data-" but even though I already have the sprites with a different scrolling speed compared to the background, I can't modify this speed to my own preference.
This is the JavaScript code:
$(document).ready(function(){
// Cache the Window object
$window = $(window);
// Cache the Y offset and the speed of each sprite
$('[data-type]').each(function() {
$(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
$(this).data('Xposition', $(this).attr('data-Xposition'));
$(this).data('speed', $(this).attr('data-speed'));
});
// For each element that has a data-type attribute
$('section[data-type="background"]').each(function(){
// Store some variables based on where we are
var $self = $(this),
offsetCoords = $self.offset(),
topOffset = offsetCoords.top;
// When the window is scrolled...
$(window).scroll(function() {
// If this section is in view
if ( ($window.scrollTop() + $window.height()) > (topOffset) &&
( (topOffset + $self.height()) > $window.scrollTop() ) ) {
// Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($window.scrollTop() / $self.data('speed'));
// If this element has a Y offset then add it on
if ($self.data('offsetY')) {
yPos += $self.data('offsetY');
}
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$self.css({ backgroundPosition: coords });
// Check for other sprites in this section
$('[data-type="sprite"]', $self).each(function() {
// Cache the sprite
var $sprite = $(this);
// Use the same calculation to work out how far to scroll the sprite
var yPos = -($window.scrollTop() / $sprite.data('speed'));
var coords = $sprite.data('Xposition') + ' ' + (yPos + $sprite.data('offsetY')) + 'px';
$sprite.css({ backgroundPosition: coords });
}); // sprites
// Check for any Videos that need scrolling
$('[data-type="video"]', $self).each(function() {
// Cache the video
var $video = $(this);
// There's some repetition going on here, so
// feel free to tidy this section up.
var yPos = -($window.scrollTop() / $video.data('speed'));
var coords = (yPos + $video.data('offsetY')) + 'px';
$video.css({ top: coords });
}); // video
}; // in view
}); // window scroll
}); // each data-type
}); // document ready
and this is the HTML markup of a single sprite:
<div class="stars" data-type="sprite" data-speed="10">
<img class="star1" src="img/cenas/1.PNG">
</div>
I tried changing the data-speed value but there aren't any changes. What can I do to have different sprites with different scroll speed?
Related
I'm trying to scroll an image by dragging my cursor. I'm using the Draggable jQuery library but I'm having a problem.
I need to determine the limit of the image so that I can block the drag to avoid showing white space.
Anyone can help me with that?
jsfiddle
<div style="width:100%;height:100%;" id="parent">
<img src="http://cdn.wallpapersafari.com/10/37/Aim58J.jpg" id="draggable"/>
$( "#draggable" ).draggable({
axis: 'x,y',
cursor: "crosshair",
});
If you need scrolling by dragging, do not use dragging. Use simple mouse move instead. Look at the example below. In this case you can scroll any content inside your container.
Hope it would help.
UPDATED:
If you need dragging of some background element, you should to drag it by mousemove and calculate visible area according to container size.
So, in few words - Drag image left till its width minus left offset is bigger than container(window) width, and so on for right, top and down offsets.
// Main script
function run() {
var $image = $('#draggable');
var $window = $(window);
var isStarted = false;
var cursorInitialPosition = {left: 0, top: 0};
var imageInitialPosition = {left: 0, top: 0};
var imageSize = {width: $image.width(), height: $image.height()};
// stop dragging
var stop = function() {
isStarted = false;
$window.unbind('mousemove', update);
};
// update image position
var update = function(event) {
// size of container (window in our case)
var containerSize = {width: $window.width(), height: $window.height()};
var left = imageInitialPosition.left + (event.pageX - cursorInitialPosition.left);
var top = imageInitialPosition.top + (event.pageY - cursorInitialPosition.top);
// don't allow dragging too left or right
if (left <= 0 && imageSize.width + left >= containerSize.width) {
$image.css('left', left);
}
// don't allow dragging too top or down
if (top <= 0 && imageSize.height + top >= containerSize.height) {
$image.css('top', top);
}
};
$window.mousedown(function(event){
var position = $image.position();
cursorInitialPosition.left = event.pageX;
cursorInitialPosition.top = event.pageY;
imageInitialPosition.left = position.left;
imageInitialPosition.top = position.top;
$(window).mousemove(update);
});
$window.mouseout(stop);
$window.mouseup(stop);
}
$(function(){
// wait for image loading because we need it size
var image = new Image;
image.onload = run;
image.src = "http://cdn.wallpapersafari.com/10/37/Aim58J.jpg";
});
https://jsfiddle.net/2hxz49bj/5/
I'm currently working on this script for "tooltips" on a website. I'm finding that the code I currently have will get the image height for my first tooltip image on the page ('pop1') but it ignores the rest (they come out as null).
What's the most effective way to get all the tooltip image heights, and use them every time the user scrolls over the tooltip image?
Another issue, if anyone is able to figure this one out - is that on my FULL webpage (many more divs, rows, columns, etc.) the script begins to break because clientX and clientY are being affected by the various divs and page elements.
I'd like to be able to set clientX and clientY to the exact (x, y) coordinates that the user's mouse is at, relative to the entire webpage, not relative to the page's child elements.
Thanks
Here's my JSFiddle: http://jsfiddle.net/tgs7px4f/18/
JS Code:
$('a.popper').hover(function (e) {
var target = '#' + ($(this).attr('data-popbox'));
$(target).show();
}, function () {
var target = '#' + ($(this).attr('data-popbox'));
if (!($("a.popper").hasClass("show"))) {
$(target).hide();
}
});
$('a.popper').mousemove(function (e) {
var target = '#' + ($(this).attr('data-popbox'));
// images vary in height!
// images are all 366px wide.
var imageWidth = 366;
var imageHeight = $(".popimg").height();
//alert('Image Height: ' + imageHeight);
//Offset tooltip:
//10px to the right of cursor
var imageX = e.clientX + 20;
//imageHeight up from cursor
var imageY = e.clientY - imageHeight - 20;
// Find bounds of current window, and if...
// Tooltip goes off right side:
if ((imageX + imageWidth) > $(window).width()) {
//Move tooltip left so it meets edge:
imageX = $(window).width() - imageWidth;
}
// Tooltip goes off top
if (imageY < 0) {
//Move tooltip down so it meets top:
imageY = 0;
}
$(target).css('top', imageY).css('left', imageX);
});
What's the most effective way to get all the tooltip image heights, and use them every time the user scrolls over the tooltip image?
First of all, I suppose you mean whenever a user does a mouseover on one of the elements? However, this seems to work and it cashes the height of the image directly on the element and uses it the next time a mouseover occurs:
$('a.popper').mousemove(function (e) {
var target = '#' + ($(this).attr('data-popbox'));
// images vary in height!
// images are all 366px wide.
var imageWidth = 366;
$target = $(target);
if (!$target.attr("height")) {
var img = $target.closest(".popbox").children("img");
var imageHeight = img.height();
$target.attr("height", imageHeight);
console.log("height attribute set");
} else {
var imageHeight = +($target.attr("height")) + 0;
console.log("cached height used");
}
console.log('Image Height: ', imageHeight);
//Offset tooltip:
//10px to the right of cursor
var imageX = e.clientX + 20;
//imageHeight up from cursor
var imageY = e.clientY - imageHeight - 20;
// Find bounds of current window, and if...
// Tooltip goes off right side:
if ((imageX + imageWidth) > $(window).width()) {
//Move tooltip left so it meets edge:
imageX = $(window).width() - imageWidth;
}
// Tooltip goes off top
if (imageY < 0) {
//Move tooltip down so it meets top:
imageY = 0;
}
$(target).css('top', imageY).css('left', imageX);
});
Obviously, you should remove all the console.log statements which are for testing purposes only.
jsFiddle
Regarding your second question, it's hard to say anything concrete without another jsFiddle or additional code.
I have a simple code for moving the background images, but the image is jerking up once the section is in view. the idea is for the background-pos to move only when the section is in view.
Any ideas?
$window = $(window);
$('.portfolioSection').each(function(){
var $bgobj = $(this); // assigning the object
var speed = 8;
$(window).scroll(function() {
if($(window).scrollTop() + 150 >= $bgobj.offset().top){
// Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($window.scrollTop() / speed);
// Put together our final background position
var coords = '0 '+ yPos + 'px'
// Move the background
$bgobj.css({ backgroundPosition: coords });
}
}); // window scroll Ends
});
Solved it- I didn't account for the section position - Line 9
var yPos = -(($window.scrollTop()-$bgobj.offset().top) / speed);
I have a parallax script that I am using to slow the background position of an element relative to the window scroll. It performs GREAT on my macbook pro but on slower computers it shudders more than I feel it needs to.
Here is the code below:
var bgobj = $('.paral');
$(window).scroll(function () {
onScroll(bgobj);
});
function onScroll(bgobj) {
var $window = $(window);
var yPos = ($window.scrollTop() / bgobj.data('speed'));
// Put together our final background position
var coords = yPos + 'px';
// Move the background
bgobj.css({ backgroundPositionY: coords });
}
So my question is, what optimisations can be made to the code to improve speed on lower machines?
Thank you
Have you considered throttling?
http://underscorejs.org/#throttle
http://underscorejs.org/#debounce
var bgobj = $('.paral');
var onScrollThrottled = _.throttle(onScroll, 100);
$(window).scroll(function () {
onScrollThrottled(bgobj);
});
function onScroll(bgobj) {
var $window = $(window);
var yPos = ($window.scrollTop() / bgobj.data('speed'));
// Put together our final background position
var coords = yPos + 'px';
// Move the background
bgobj.css({ backgroundPositionY: coords });
if (isScrolledIntoView($('#more-info'))) {
animateCircle();
}
}
Of course, instead of throttling/debouncing the entire onScroll function you can apply the optimisation to animateCirle or updating the background css
I see some minor improvements to be done. Nothing big:
//cache $window and speed
var $window = $(window);
var bgobj = $('.paral');
var speed = bgobj.data('speed')
$window.scroll(function () {
onScroll(bgobj);
});
function onScroll(bgobj) {
var yPos = ($window.scrollTop() / speed);
// Put together our final background position
//var coords = yPos + 'px'; // this is not needad as jQuery defaults to pixels if nothing is specified
// Move the background
bgobj.css({ backgroundPositionY: coords });
if (isScrolledIntoView($('#more-info'))) { // depending on what is inside this function, this might slow everything doen
animateCircle();
}
I have a div with a width of 308px. In this div I have a buffer bar (which can be any length from 0 to 308).
The div is used to show the progress of a playing audio track. The audio track has a duration in milliseconds.
I am trying to enable the user to change the position in the track based on a click in the div. However my math is all wrong.
What I currently have is:
var pos = e.pageX - $(this).offset().left; // returns the position of the click in the div (0 to 380)
var relpos = parseInt(308, 10)/parseInt(pos, 10);
var newpos = parseInt(duration, 10)/parseInt(relpos, 10);
How to calculate the new position based on the position of the click on the div?
I've setup a fiddle if you want to test it.
First the 308 is actualy the buffer width you should replace that if you need to resize.
The code is:
(function($) {
var duration = 138736;
$(document).on('click', '.buffer', function(e) {
var pos = e.pageX - $(this).offset().left;
var relpos = duration*pos;
var newpos = relpos/308;
$('.test').html(pos + '/' + newpos + '/' + duration);
});
})(jQuery);
if 308 is duration
than pos is x, x = (pos * duration) / 308