I have a question regarding using a function multiple times on the page I am trying to set a block auto height in dependence of screen resolution but I have 2 divs on different pages that need to be applied this function, it get applied only for one div for ex:
first tie I apply it to following selectors
<script>
$(function () {
resize_main_pane();
$(window).resize(resize_main_pane);
});
function resize_main_pane() {
var offset = $('.pagina-servicii').offset(),
remaining_height = parseInt($(window).height() - offset.top - 105);
$('.pagina-servicii').height(remaining_height);
}
</script>
second time to the following:
<script>
$(function () {
resize_main_pane();
$(window).resize(resize_main_pane);
});
function resize_main_pane() {
var offset = $('.another-selector').offset(),
remaining_height = parseInt($(window).height() - offset.top - 283);
$('.another-selector').height(remaining_height);
}
</script>
How can I combine them or use separately? I wonder if I need to use some no conflict setting?
Loop all selected divs and apply height to them:
function resize_main_pane() {
$.each($('#selector1, #selector2', function(){
var offsetMinus = $(this).hasClass('bigOffset') ? 283 : 105;
var offset = $(this).offset(),
remaining_height = parseInt($(window).height() - offset.top - offsetMinus);
$(this).height(remaining_height);
});
}
Put your selectors in an array and loop trough them with each.
The $(this) will be either of your class selectors and calculates the offset and height independently.
$(function () {
resize_main_pane();
$(window).resize(resize_main_pane);
// If you want to trigger this function on document load you could replace the above line with:
$(window).resize(resize_main_pane).trigger('resize');
});
function resize_main_pane() {
$('.pagina-servicii, .another-selector').each(function(index) {
var offset = $(this).offset(),
remaining_height = parseInt($(window).height() - offset.top - [105,283][index]);
$(this).height(remaining_height);
});
}
Related
I'm trying to write a function in jQuery that could create an infinite scroll with divs that are already in my page. I would like to make them appear and load randomly when you reached the end of the original content. The thing is that I'm just starting to use jQuery and I don't really know who to do it!
All my divs have a class of item and are inside a .content div. For the moment I have 11 of them.
I tried to .append(specific div) and it worked, but I don't know how to do it with a list of div.
Does anyone have an idea of what I should do?
$(document).ready(function() {
var collection = $("div.content .item").get();
collection.sort(function() {
return Math.random() * 10 > 5 ? 1 : -1;
});
$.each(collection, function(i, el) {
$(el).appendTo($(el).parent());
});
});
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
$(".content").append('Here is where I dont know what I should write')
});
});
}
});
Hi :3 The jquery clone() function may be of help, in your case:
let triggerDistance = $(document).height() - $(window).height() - 50;
let OriginalItems = $(".item").length;
$(window).scroll(function() {
let scrolledDistance = $(window).scrollTop();
if ( scrolledDistance > triggerDistance) {
var randomItem = Math.floor(Math.random() * OriginalItems);
var clonedItem = $("#item_"+randomItem).clone();
clonedItem.removeAttr('id');
clonedItem.appendTo("html");
}
});
You select a random item from the original ones, you create a new copy of said item using clone, you append the clone to the document :)
Here's a fiddle: https://jsfiddle.net/collederfomento/d98a15cu/4/
A few things could be improved:
preventing the function from firing too often
preventing the function from cloning the same item twice in a row
I've made a slider with jQuery using html tags which have classes instead of IDs so that I will be able to use the same jQuery code for other duplicated sliders.
The problem is, I want the width of my ul to be calculated based on the number of lis, instead of setting it manually in CSS. When there is only one slider I can set my vars outside of the function, but when I have to use it though event attributes on my html parts so that I will be able to use them for multiple sliders, I have to move the vars inside of my function, which sets the wrong width.
This is my code:
function OLAR(direction,span) {
var OurNexNPrv = $(span);
var Parent_OLAR = OurNexNPrv.parents('.OLAR');
var UL_OF_OLAR = Parent_OLAR.find('.OLAR_CONTENT ul');
var LI_OF_OLAR = UL_OF_OLAR.find('li');
var LI_OF_OLAR_LENGTH = LI_OF_OLAR.length;
var Quantity_OF_OLAR_PAGES = LI_OF_OLAR_LENGTH / 3;
var Max_Margin_LEFT = -(Quantity_OF_OLAR_PAGES - 1) * 576;
UL_OF_OLAR.css('width',LI_OF_OLAR_LENGTH*192);
var AffectedLeftMargin;
var CurrentLeftMargin = UL_OF_OLAR.css('margin-left');
CurrentLeftMargin = parseFloat(CurrentLeftMargin);
if (direction == 'right') {
AffectedLeftMargin = CurrentLeftMargin - 576;
}
if (direction == 'left') {
AffectedLeftMargin = CurrentLeftMargin + 576;
}
if (AffectedLeftMargin < Max_Margin_LEFT) {
AffectedLeftMargin = 0;
}
if (AffectedLeftMargin > 0) {
AffectedLeftMargin = Max_Margin_LEFT;
}
UL_OF_OLAR.animate({'marginLeft': AffectedLeftMargin}, 1000);
}
$('.CIRCLE_LOAD_RIGHT').click(function () {
OLAR('right');
});
$('.CIRCLE_LOAD_LEFT').click(function () {
OLAR('left');
});
How can I set the width for each of my uls individually, through css commands outside of that function?
Okay, my ul tag did not have the absolute position; after giving it the right position and left:0 and bottom:0 or right:0 and bottom:0 (based on your language)the given width which comes from JQuery code can rhyme perfectly with everything else. I've tried it with multiple sliders and it works perfectly :)
So, we need an anchor point in order to make this work. And there is nothing wrong with this JQuery code which has been mentioned above!
Have a great day.
I've got a situation where I want a variable to be updated when scrolling inside a <div>. There is a series of other things which will happen depending on this variable updating, so I don't want to wrap it inside the scroll event. Is there a way to avoid that?
Here is my JS:
var scrollEl = document.getElementById("scrollEl");
var scrollElWidth = scrollEl.offsetWidth;
var scrolled = 0;
var updater = function(updated) {
scrolled = Math.round(updated);
return scrolled;
}
scrollEl.addEventListener("scroll", function() {
var percentage = 100 * scrollEl.scrollLeft / (scrollEl.scrollWidth - scrollElWidth);
//This works
console.log(updater(percentage));
});
//This doesn't
console.log('Updated scroll variable: ', scrolled);
Here is a fiddle: https://jsfiddle.net/0u4fp0yv/
I need a script which toggle a class when another class or section is visible in the viewport (during scrolling).
Here I have an script which works for precised distance from top, but can somebody help me to modify it for my needs?
$(window).scroll(function(){
if ($(this).scrollTop() > 50) {
$('#viewport').addClass('turn_on');
} else {
$('#viewport').removeClass('turn_on');
}
});
A couple of things. First the scroll event (as well as the resize event) fire multiple times. Traditionally, developers have used something called debouncing to limit the number of times a function fires. I've never got it to work correctly, so instead I check if a condition is met before continuing. You are basically doing this already.
var bool = false
$(window).on('scroll', function(){
if(!bool){
bool = true;
//fire the function and then turn bool back to false.
};
});
The next thing you need is to identify the element to add the class to. Let's say it has an id of foo.
var yOffset = $('#foo').offset().top;
From here, you'll need to compare the current vertical scroll position with that of the yOffset. You may also need to add the height of the element for when it scrolls out of frame.
var elHeight = $('#foo').height();
The element should be completely in frame with the $(window).scrollTop() equals the yOffset and out of frame when the $(window).scrollTop() is greater than yOffset + elHeight.
This is all assuming the element isn't in the frame to begin with. If it is, it will be trickier but it's a start.
Working fiddle
Try to add function that detect if element passed in argument is visible :
function isVisisble(elem){
return $(elem).offset().top - $(window).scrollTop() < $(elem).height() ;
}
$(window).scroll(function(){
if (isVisisble( $('your_element') ))
$('#viewport').addClass('turn_on');
} else {
$('#viewport').removeClass('turn_on');
}
});
Hope this helps.
Thx everyone for help.
Here I found the solution: LINK
And here is the modified script:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * 0.1,
gridBottom = windowHeight * 1;
$(window).on('scroll', function () {
$('.inner').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
$(this).addClass('on');
}
});
});
});
I need to have 2 of these one page but each with different percentages. When I try re-writing the JS or even use different class/ID names it still always pulls from the first SPAN.
http://jsfiddle.net/K62Ra/
<div class="container">
<div class="bw"></div>
<div class="show"></div>
<div id="bar" data-total="100">
<div class="text">Currently at <br/><span>70</span><br><i>Click To Give</div>
</div>
JS and CSS in the Fiddle.
Much Thanks.
This one will work smoothly:
http://jsfiddle.net/K62Ra/7/
$('.bar').each(function() {
var percentStart = 0;
var total = $(this).data('total');
var percent = parseInt($(this).find('span').html());
$(this).find('> div').addClass("load");
var that = this;
var timer = setInterval(function() {
$(that).siblings('.show').css('height', percentStart/total*100+'%');
$(that).css('height', percentStart/total*100+'%');
$(that).find('span').html('%'+percentStart);
if(percentStart<percent) { percentStart=percentStart+1; return; }
clearInterval(timer);
}, 35);
});
The interval has to be terminated as well, or it will run infinitely (though not doing anything).
I've changed your id="bar" into a class. Then I'm running a each loop for the .bar classes. here is the fiddle: http://jsfiddle.net/K62Ra/3/
here is the code:
$('.bar').each(function (index, element) {
percent = $(this).find('span').html();
total = $(this).attr('data-total');
percentStart = 0;
setInterval(function () {
$('.show').css('height', percentStart / total * 100 + '%');
$(this).css('height', percentStart / total * 100 + '%');
$(this).find('span').html('%' + percentStart);
if (percentStart < percent) {
percentStart = percentStart + 1;
}
}, 35);
});
$(".bar div").addClass("load");
Like some of the comments have stated, having duplicate ids is bad design and can cause some weird errors.
You can find a solution to your problem by changing a number of things. One, instead of
referring to divs in you selectors by id'#', you can infer them by class '.' like
$('.bar')
The next step would be to ensure exclusivity for each div with class 'container' by using a closure
$('.container').each(function(){
var x
var y
.
.
});
And finally, avoid 'selecting' elements in the selector directly, but use $(this) and .find() to ensure you are within the current div with class 'container'.
http://jsfiddle.net/K62Ra/5/
$('.container').each(function(){
var percent = $(this).find('div.bar div span').html();
var total = $(this).find('div.bar').attr('data-total');
var percentStart = 0;
var that = $(this);
setInterval(function() {
that.find('.show').css('height',percentStart/total*100+'%');
that.find('div.bar').css('height',percentStart/total*100+'%');
that.find('div.bar div span').html('%'+percentStart);
if(percentStart<percent) {percentStart=percentStart+1;}
},35);
$(this).find("div.bar div").addClass("load");
});
There are already several good answers here. I would recommend validating your html. Also some of your css was causing weirdness when there was scrolling involved (fixed background images weren't scrolling.)
I took a slightly different approach than everyone else. Instead of using a setInterval I went with $.animate and a step function. Like others, I chose a class to target each of the items: 'fill-me-up'.
Fiddle: http://jsfiddle.net/LFbKs/6/
NOTE: Check the fiddle since I modified the HTML (very slightly) and the css to a larger degree.
// for each item we need to "fill up"
$('.fill-me-up').each(function(){
// cache DOM references
var this$ = $(this)
, bar$ = this$.find('.bar')
, show$ = this$.find('.show')
, span$ = bar$.find('div span')
// the target percentage height for this item
, p = span$.text()
// combine '.bar' and '.show' so we can apply the animation to both
, toAnimate = $().add(bar$).add(show$);
// add class causing fade-in
bar$.find('div').addClass('is-visible');
// animate height to target height over 2 seconds and
// at each step, update the span with a truncated value
toAnimate.animate(
{ height: p+'%' },
{
duration: 2000,
step: function( currentStep ) {
span$.html('%'+currentStep.toFixed(0));
}
}
);
});
Cheers