execute jquery function for each element containing class - javascript

The below function mostly works - it moves the backgrounds as I need, however I would like the function to run on any element with a class of "animate", rather than having to call each element down the bottom. I tried $('.animate').load(function(){}; but it just wont work... Thanks
JAVASCRIPT
$(window).load(function(){
(function(){
$.fn.move = function(){
var $this = $(this);
var offset = $this.offset().top;
var start = 0;
var end = offset + $this.height();
var speed = $this.attr("speed");
return this.each(function(){
$(window).bind('scroll', function() {
var windowPos = $(window).scrollTop();
if((windowPos >= start) && (windowPos <= end)) {
var newCoord = windowPos * speed;
$this.css({'background-position': '0 '+ newCoord + 'px'});
};
});
});
};
})(jQuery);
$('.animate').move();
});
HTML
<div class="welcome_6"></div>
<div class="welcome_5"></div>
<div class="welcome_4"></div>
<div class="welcome_3"></div>
<div class="welcome_2 animate" speed="-1"></div>
<div class="welcome_1 animate" speed="0"></div>
EDIT:
When I scroll the page the elements move according to the scroll location. Each element moves at a different speed (set as html attribute). This code moves them all at the same speed.. I'm assuming the $('.animate') should be somewhere up the top replacing the $.fn.move but i cant figure it out..

Should be $('.animate') instead of $('animate') note the dot at the start of the query which says to the jQuery that you are looking for a class.

I think the issue is with the way you are using the immediately invoked function inside the load function and you are passing in jQuery at the bottom and not into the immediately invoke function. This will update the background position as long as you script tag is placed after the jquery script tag
Here is a link to js fiddle:
UPDATE: https://jsfiddle.net/kriscoulson/pnrx34wp/1/
I do not have your exact code for styling so I improvised but if you inspect the elements the background position is being updated;
AND UPDATE :
$.fn.move = function() {
var $this = $(this);
var offset = $this.offset().top;
var start = 0;
var end = offset + $this.height();
return this.each(function(index, element) {
var $element = $(element);
var speed = $element.attr("speed");
$(window).bind('scroll', function() {
var windowPos = $(window).scrollTop();
if ((windowPos >= start) && (windowPos <= end)) {
var newCoord = windowPos * speed;
$element.css({
'background-position': '0 ' + newCoord + 'px'
});
};
});
});
};
$(document).ready(function() {
$('.animate').move();
});
EDIT: Your 'this' binding was off and your speed was declared outside of the this.each

Related

How can I animate/slide a div into view while moving the contents as opposed to just revealing the contents?

I would like to use the jquery slideUp and slideDown methods, but instead of the effect being one of the contents merely being revealed, as though a screen is being pulled back and forth, I would like the contents themselves to slide into view, as though a hidden panel is being pulled back and forth.
If you want to use jQuery animate check this fiddle: http://jsfiddle.net/cgLy77us/1/
Script:
$(document).ready(function(){
var SlideUpAnimate = function(duration, callback){
var $element = $("#slideUp");
var startPosition = $(window).scrollTop() + $(window).height() + $element.height();
var finishPosition = $element.position().top;
$element.css("top", startPosition + "px").show().animate({
top: finishPosition + "px"
},duration, callback);
};
var SlideDownAnimate = function(duration, callback){
var $element = $("#slideUp");
var finishPosition = $(window).scrollTop() + $(window).height() + $element.height();
var startPosition = $element.position().top;
$element.css("top", startPosition + "px").animate({
top: finishPosition + "px"
},duration, function(){
$element.hide();
callback();
});
};
SlideUpAnimate(1000,function(){
//Some callback code here like:
SlideDownAnimate(1000);
});
});
I think you can adapt to every situation.

jquery tooltip should change position when offscreen

on window scrolling the Tooltip should appear correctly above/below/left/right of its parent.
Once I scrolled down on my Demo the position of the Tooltip brakes.
How can I calculate the y-offset of the parent and display the tooltip in the right position?
I'm nearly there, not sure what is missing.
http://fiddle.jshell.net/j7MWE/
$.fn.tooltip = function () {
var $el = $(this);
var $w = $(window);
var timer;
var delay = 500;
$el.mouseenter(function (e) {
timer = setTimeout(function () {
var $c = $(e.currentTarget);
var $tt = $('<div class="tooltip fade right"><div class="arrow"></div><h3 class="popover-title" style="display: none;"></h3><div class="popover-content"><article class="default"><h1>Anchorman 2: The Legend Continues</h1><ul><button>£10.99 Buy</button><button>£3.49 Rent</button><p>Hilarious comedy sequel starring Will Ferrell and Steve Carell.</p></article></div></div>').appendTo($(e.currentTarget).closest('.item')).fadeIn(300);
$tt.toggleClass('horiz-offscreen', $w.width() < $tt.outerWidth() + $tt.offset().left);
if ($w.height() < $tt.outerHeight() + $tt.offset().top) {
$tt.css('top', $w.scrollTop() + $w.height() - $c.position().top - $tt.outerHeight());
}
}, delay);
});
$el.mouseleave(function (e) {
$('.tooltip', e.currentTarget).fadeOut(500, function () {
$(this).remove();
});
clearTimeout(timer);
});
};
$('.item').tooltip();
its old but it can helps,
to calculate that you can use this:
$tt.css('top', abs($c.position().top - $w.scrollTop() - $tt.outerHeight()) );
$c.position().top the element distance from top
$w.scrollTop() scrolled value
$tt.outerHeight() your tooltipheight
and than we do some Maths and get the absolute value

making a function works on specific widths

I am trying to make this function works only when the screen size is above 1024px.
//Parallax background image
var velocity = 0.5;
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};$(window).bind('scroll', update); update();
Here is what I have tried to do:
//Parallax background image
var velocity = 0.5;
$(window).on("ready resize", function() {
if ($(window).width() < 770) {
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};});$(window).bind('scroll', update); update();
I really don't know what I am doing wrong...
You haven't stated what the problem you're coming across is. If it's "my code doesn't work", then perhaps you should check your syntax first. Your braces are messed up.
//Initialize velocity and empty update function
var velocity = 0.5;
var update = function () {};
//When window is ready (content loaded) OR resized, execute the following function
$(window).on("ready resize", function () {
if ($(window).width() >= 1024) { //Check if window width is 1024px wide or larger
update = function () { //Set update to run this function when executed.
var pos = $(window).scrollTop(); //Get scrollbar position https://api.jquery.com/scrollTop/
//For each element with 'parallax' class, execute the following function
$('.parallax').each(function () {
var $element = $(this); //Get the current parallax-classed element
var height = $element.height(); //Save the current height of this element
//Set the CSS of this parallax-classed element set the background position
$(this).css('background-position', '40% + ' + Math.round((height - pos) * velocity) + 'px');
});
};
} else { //Execute if screen width is < 1024px
update = function () {}; //Set update to do nothing
}
});
//When window is scrolled through, run the update function
$(window).bind('scroll', update);
//update();
Last line is unnecessary, as resize will handle function value, and scroll will handle the execution.
You were missing a + or - within the background-position setting.
So for example, if the result of your Math.round() was "30", then Javascript would interpret that line as $(this).css('background-position', '40%30px'); which obviously would cause issues. I'm sure you wanted it to say something like $(this).css('background-position', '40% + 30px');.

Creating onClick jquery tooltip on the basis of offset(). Everything works well apart when the user comes at the bottom, tool tip actually goes hide

I am creating onClick jquery tooltip on the basis of 'offset()'. Everything works well apart when the user comes at the bottom. Tool tip actually goes hide.
Its a obvious thing I have given the main container 'overflow:hidden'. But I would like to re-position the tool tip or may be this time not according to offset position.
Ultimately I don't want to hide it.
Any suggestion or help much appreciated. Apologies if I couldn't explain it in right manner.
Here is the code and fiddle URL:
$('#data-list > li').on('click', function(){
var $this = $(this), thisoffset = $this.offset().top;
$('.active').removeClass('active');
$this.addClass('active');
$('.container-slide').animate({top:thisoffset-15}, 300).fadeIn();
});
http://jsfiddle.net/mufeedahmad/ndk44/12/
Thanks in advance.
Basically you have to check if the container-slide goes out of the wrapper box. You can add this line
if(thisoffset + $('.container-slide').height() > $(".wrapper").height())thisoffset = $(".wrapper").height() - $('.container-slide').height() + 15;
So the final code becomes
$('#data-list > li').on('click', function(){
var $this = $(this), thisoffset = $this.offset().top;
if(thisoffset + $('.container-slide').height() > $(".wrapper").height())thisoffset = $(".wrapper").height() - $('.container-slide').height() + 15;
$('.active').removeClass('active');
$this.addClass('active');
$('.container-slide').animate({top:thisoffset-15}, 300).fadeIn();
});
Check this fiddle http://jsfiddle.net/aZJuN/
var divleftoffset = $(".wrapper").offset().left - $(document).scrollLeft();
var left = event.pageX; -$(document).scrollLeft();
menuWidth = $(".container-slide").width();
divWidth = $(".wrapper").width();
menuleft = menuWidth + left;
divleft = divleftoffset + divWidth;
var right;
if (menuleft > divleft) {
left = left - menuWidth;
}
var divrightoffset = $(".wrapper").offset().top - $(document).scrollTop();
var Top = event.pageY; -$(document).scrollTop();
menuHeight = $(".container-slide").height();
divHeight = $(".wrapper").height();
menuTop = menuHeight + Top;
divTop = divrightoffset + divHeight;
var right;
if (menuTop > divTop) {
Top = Top - menuHeight;
}
$('.active').removeClass('active');
$this.addClass('active');
$('.container-slide').animate({ top: Top - 15 }, 300).fadeIn();

Javascript: Scroll to nth row in a table?

Using either pure Javascript or jQuery, how do I scroll the page so that the nth row in a table is centered on the page?
Some examples I've seen that have this sort of feature usually require that the element I scroll to uses an id as the selector, but since the table has a dynamic amount of rows and may be paged, I'd rather not go this route of having to give each <td> tag an id.
Is the easiest way to just calculate the position of the td relative to the top of the document and scroll the window using setInterval until the middle of the window is >= to the position of the nth <td> tag?
I suppose some pseudo-code of the way I imagine it working would be:
function scrollToNthTD(i) {
var position = CalculatePositionOfTR(i);
var timer = setTimeout(function () {
ScrollDownALittle();
if( CenterOfVerticalWindowPosition > position)
clearInterval(timer);
}, 100);
}
Latest update (no-jquery for for modern browsers)
var rows = document.querySelectorAll('#tableid tr');
// line is zero-based
// line is the row number that you want to see into view after scroll
rows[line].scrollIntoView({
behavior: 'smooth',
block: 'center'
});
Demo at http://jsfiddle.net/r753v2ky/
Since you can use jQuery here it is..
var w = $(window);
var row = $('#tableid').find('tr').eq( line );
if (row.length){
w.scrollTop( row.offset().top - (w.height()/2) );
}
Demo at http://jsfiddle.net/SZKJh/
If you want it to animate instead of just going there use
var w = $(window);
var row = $('#tableid').find('tr').eq( line );
if (row.length){
$('html,body').animate({scrollTop: row.offset().top - (w.height()/2)}, 1000 );
}
Demo at http://jsfiddle.net/SZKJh/1/
Don't use jQuery - it slows down sites!
var elem = document.getElementById("elem_id");
elem.scrollIntoView(true);
You can do something like this
function CalculatePositionOfTR(){
return $('tr:eq(' + i + ')').offset().top;
}
function ScrollDownALittle(position){
$('html, body').animate({
scrollTop: position
}, 2000);
}
function scrollToNthTD(i) {
var position = CalculatePositionOfTD(i);
var timer = setTimeout(function () {
ScrollDownALittle(position);
if( CenterOfVerticalWindowPosition > position)
clearInterval(timer);
}, 100);
}
Give this a shot:
/*pseudo-code*/
$("td.class").bind("click", function() {
var y = $(this).position().top,
h = $(window).height();
if(y > h/2) {
$("body").animate({
scrollTop: y - h/2
}, 2000);
};
});
aka-g-petrioli
I have corrected the followings from your answer.
$('#control button').click(function(){
var w = $(window);
var row = table.find('tr')
.removeClass('active')
.eq( +$('#line').val() )
.addClass('active');
if (row.length){
w.scrollTop( row.offset().top - row.offset().top/5);
}
});
This will help you to scroll accurate position.

Categories