So basically I am just trying to change the CSS class of a specific element upon scrolling. This worked great when using this code:
$(window).bind('scroll', function() {
if ($(window).scrollTop() >= 270) {
$('.homeLink').addClass('selected');
}
else {
$('.homeLink').removeClass('selected');
}
});
However, I want to remove the class upon scrolling further. So I tried using this code:
$(window).bind('scroll', function() {
if ($(window).scrollTop() >= 270 && < 300) {
$('.homeLink').addClass('selected');
}
else {
$('.homeLink').removeClass('selected');
}
});
When using the 2nd code, it just doesn't work at all. Meaning, nothing changes.
I know I am just being stupid and doing this wrong, but I am not sure how to fix it. I am pretty big noob when it comes to js. Any help would be very appreciated.
EDIT:
I have also tried this with no luck:
$(window).bind('scroll', function() {
if ($(window).scrollTop() >= 270 && $(window).scrollTop() < 300) {
$('.homeLink').addClass('selected');
}
else {
$('.homeLink').removeClass('selected');
}
});
This is the correct sintax:
if ($(window).scrollTop() >= 270 && $(window).scrollTop() < 300) {
Try this:
if($(this).scrollTop()>= 270 && $(this).scrollTop() < 300){
Related
I'm having an issue on how I can set multiple conditions. Basically I have three conditions that would read or listen to browser viewport. The first and second conditions are working but the third condition doesn't seem to trigger. Is it because of the conflict with the second condition?
if($(window).width() > 1280) {
console.log('desktop');
}
else if ($(window).width() < 1280) {
console.log('tablet');
}
else if ($(window).width() < 780) {
console.log('mobile');
}
It is because of your second else/if. If $(window).width() is less than 780, it is also less than 1280
Change it to
else if ( $(window).width() >= 780 && $(window).width() < 1280) {
console.log('tablet');
}
Your second condition also includes the third one. Because every value which is below 780 is also below 1280. You need something like windowWidth < 1280 && windowWidth >= 780 to give the range.
const windowWidth = $(window).width();
if(windowWidth > 1280) {
console.log('desktop');
} else if (windowWidth < 1280 && windowWidth >= 780 ) {
console.log('tablet');
} else if (windowWidth < 780) {
console.log('mobile');
}
Also it will be good to keep the window into a variable, not every time use with jQuery.
Here is a more concise example, but the condition rely on the order, some people do not like this style, but I think it is OK, and we can add a comment.
//Do not change the condition order
if($(window).width() <= 780) {
console.log('mobile');
}
else if ($(window).width() <= 1280) {
console.log('tablet');
}
else {
console.log('desktop');
}
Edited: The condition should be * than and equal to ....
There is flaw in your second condition...below is the fix..hope it helps!!
if($(window).width() > 1280) {
console.log('desktop');
}
else if ($(window).width() < 1280 && $(window).width() >= 780) {
console.log('tablet');
}
else if ($(window).width() < 780) {
console.log('mobile');
}
It's because the condition before < 780 is also met (ie. If the width is equal to 600 its inferior to 1280). Change the condition order or, better, improve the second condition :
if($(window).width() >= 1280) {
console.log('desktop');
}
else if ($(window).width() < 1280 && $(window).width() >= 780) {
console.log('tablet');
}
else if ($(window).width() < 780) {
console.log('mobile');
}
You also forgot a case, if the user's screen resolution is equal to 1280, you'll never enter any of your conditions. I change > to >= to include that case.
you can try this also, it will satisfy your second condition
if ($(window).width() > 1280) {
console.log('desktop');
}
else if ($(window).width() < 1280) {
if ($(window).width() < 780) {
console.log('mobile');
} else {
console.log('tablet');
}
}
or
if ($(window).width() > 1280) {
console.log('desktop');
}
else {
if ($(window).width() < 780) {
console.log('mobile');
} else {
console.log('tablet');
}
}
The correct way to do this would be to move your third condition up to the second spot.
When doing this kind of checks always place the most restricting condition first.
In your case, the tidiest way is:
var w = $(window).width();
if (w < 780) { // most restrictive condition. Excludes all the others...
console.log('mobile');
} else if (w < 1280) { // this one includes the one above but it will never be triggered if w < 780
console.log('tablet');
} else { // all the other cases
console.log('desktop');
}
Contrary to what many said, there is no need for this else if statement:
else if (windowWidth < 1280 && windowWidth >= 780) { ... }
This adds an unnecessary, redundant check.
It sure is a light operation, but imagine that, instead of windowWidth < 1280 you were checking
functionForCalculatingWidth() : int {
// huge amount of lines with expensive computation
return result;
}
you would be calling the same function twice. See why it is bad design?
In the same way, if you were to check conditions based on the largest element (plus let's add another fictional condition), you would do:
var w = $(window).width();
if (w > 1280) {
console.log('desktop');
} else if (w > 990) {
console.log('weird device');
} else if (w > 780) {
console.log('tablet');
} else {
console.log('mobile');
}
Hope this will satisfy you you can check this.
Different is this shows width in console easy to understand this logic if you cant understand let me know
Here is fiddle
$(window).bind("resize", function() {
sizewindow = $(this).width();
console.log(sizewindow)
if (sizewindow < 780) {
console.log('mobile');
} else if (780 < sizewindow < 1280) {
console.log('szechuan sauce');
if (sizewindow > 1280) {
console.log('rick and morty gone for 2 years sad af')
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have some function, which checks if user scrolls to the bottom of the page, if yes, ajax runs and portion of result is added into current page.
This works well, but if i will add negative number to start this function faster, getData() function runs many times, and also all code starts to act strange - you can scroll up by one pixel and this runs again. Below working version without offset, and next with offset which is better for me as function starts earlier, but with loading getData() many times, which is wrong.
I think about some solution with flag - true / false, but i can't figure how do this properly.
$(window).scroll(function() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
console.log(counter)
if (counter > sum) {
return false;
} else {
getData(counter);
counter++;
}
}
});
$(window).scroll(function() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 300) {
console.log(counter)
if (counter > sum) {
return false;
} else {
getData(counter);
counter++;
//$(window).unbind('scroll');
}
}
});
Thank you for debouncing tip.
Thanks to this, i was able to fix my code and all works well now.
Below example:
$(window).scroll(function() {
var timer;
if (timer) {
window.clearTimeout(timer);
}
timer = window.setTimeout(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 500) {
console.log(counter)
if (counter > sum) {
return false;
} else {
getData(counter);
counter++;
}
}
}, 200);
});
I am trying to make an animation happen once the webpage is at a certain part of the page. I have looked at other people queries and my problem is similar but it does not work.
here is the code:
if($('html,body').scrollTop() > 400) {
$('.fish_one').animate({"margin-left":"+=65%"},1000);
$('.fish_two').animate({"margin-left":"-=10%"},1000);
$('.left').animate({"opacity":"+=1"},1000);
$('header').css({"background-color":"#fff"});
$('header a').css({"color":"#94d9f8"});
}
You need to check the if statement every time the page scrolls, not just on load. Use $(window).scroll(function(){
$(window).scroll(function(){
if($(window).scrollTop() > 400) {
alert("lower");
}
});
Fiddle
EDIT: to prevent the function from repeating itself:
var pos = false;
$(window).scroll(function(){
if(($(window).scrollTop() > 400) !== pos ){
alert("changed");
}
pos = $(window).scrollTop() > 400;
});
OR
var pos = false;
$(window).scroll(function(){
if(($(window).scrollTop() > 400) && !pos ){
alert("just passed breakpoint");
}
pos = $(window).scrollTop() > 400;
});
New Fiddle
Try adding it to an event listener like this:
var eventTriggered=false;
$(document).on( 'scroll', function(){
if($(document).scrollTop() > 400 && !eventTriggered) {
alert("success");
eventTriggered=true;
}else if($(document).scrollTop() < 400){
eventTriggered=false;
}
});
This one works
i have this little script where i try to detect the window size to apply the limit of caracters of an element.
the problem the detection is not working. Always apply the limit of 150.
i have set an alert to look if detect or not, and now i´m sure that he is always apply the same.
can someone help me to find out what is wrong with this script?
here is my code:
$(function () {
$(".block6 p").each(function (i) {
len = $(this).text().length;
if (len > 10) {
if ($(window).width() <= 1280) {
$(this).text($(this).text().substr(0, 150) + '...');
}
else if ($(window).width() > 1280) {
$(this).text($(this).text().substr(0, 10) + '...');
}
}
});
});
Your code only runs once, on document.ready. You need to run the test every time the window is resized:
$(window).on('resize',function() {
if ($(window).width() <= 1280) {
$(".block6 p").each(function (i) {
var len = $(this).text().length;
if (len > 10) {
$(this).text($(this).text().substr(0, 150) + '...');
}
});
} else { //if ($(window).width() > 1280) {
$(".block6 p").each(function (i) {
var len = $(this).text().length;
if (len > 10) {
$(this).text($(this).text().substr(0, 10) + '...');
}
});
}
});
$(document).ready(function() {
$(window).trigger('resize');
}
http://jsfiddle.net/mblase75/6PQ4Q/
That said, you have a problem in that you're altering the text of each element directly, so switching back and forth by resizing the browser will be destructive. I suggest using text-overflow: ellipsis instead if possible.
I want to scroll to a div each time user presses j key. Here is the code for it.
$(function() {
function scroll(direction) {
var scroll, i,
positions = [],
here = $(window).scrollTop(),
collection = $('.message_box');
collection.each(function() {
positions.push(parseInt($(this).offset()['top'],0));
});
for(i = 0; i < positions.length; i++) {
if (direction == 'next' && positions[i] > here) { scroll = collection.get(i); break; }
if (direction == 'prev' && i > 0 && positions[i] >= here) { scroll = collection.get(i); break; }
}
if (scroll) {
$('html, body').animate({"scrollTop": $(scroll).offset().top-50});
$(scroll).css('color', 'blue');
$(scroll).mouseleave(function() {
$(this).css('color', 'black');
});
}
return false;
}
$("#next,#prev").click(function() {
return scroll($(this).attr('id'));
});
$('body').keyup(function(event) {
if (event.which == 74) {
return scroll('next');
}
});
$('body').keyup(function(event) {
if (event.which == 75) {
return scroll('prev');
}
});
});
I need to subtract 50 from the offest of the div to scroll to which is this.
$('html, body').animate({"scrollTop": $(scroll).offset().top-50});
It will scroll the first time but not the rest of the times. I always get the integer 218 which is the offset of the first div to scroll to.
DEMO - http://jsfiddle.net/XP5sP/6/
Can someone help me ?
The problem is that you're always moving the scrollTop value to 50 pixels before the first matched element, so it's always identifying that element as the one you need to scroll to in your if statement because its position is greater than the current scrollTop value.
Modify the relevant section of your code to this:
if (direction == 'next' && positions[i] > here + 50) {
scroll = collection.get(i);
break;
}
That way it accounts for the window being scrolled to 50 pixels above the current element.
$(scroll).offset().top-50 is prefectly valid, as .top will return an integer value. Therefore the issue is not with this portion of your code.
I suspect the issue is to do with the scroll variable you have within the scroll function. I always keep away from naming my variables the same as my function names when within the same scope.
Try putting some space between your minus symbol so it does not get mistaken for a dash.
$('html, body').animate({"scrollTop": $(scroll).offset().top - 50});
or save your mathematics in a variable first
var scrollMinusFifty = $(scroll).offset().top - 50;
$('html, body').animate({"scrollTop":scrollMinusFifty});