need an event triggered if the page has scrolled 200px down (jQuery) - javascript

I want to show and hide a piece of code if i scroll and the page is for example half way, i have tried to use window scroll but this doesnt works(no errors, clean code, different browsers, different jQuery versions), but this doesn't trigger anything, so i am looking for a better way to show and hide a div if i scrolldown.
used this to trigger an event(not working)
$(window).scroll(function(){
alert('works')
});

Try using the window.onload function (that's how they use it in jQuery examples):
window.onload = (function(){
$(window).scroll(function () {
if( $(window).scrollTop() > 200 ) {
// Display something
}
})
})

Related

JQuery if statement not working as expecting

I'm using Bootstrap 3 and creating an if statement with JQuery to make my navbar collapse when anything on the body is clicked, but only when the browser width is less than 992px. When the browser is 992px or wider, I want this function to be ignored. My function below is working as expected, except for the fact that "test" gets logged to the console when the body is clicked on all browser widths when it should only do so when it is less than 992px. Is something wrong with my if statement below?
if ($(window).width() < 992) {
$('body').click(function() {
console.log("test");
$('.navbar-collapse').collapse('hide');
});
};
I updated my code to have the if statement inside of the function, as seen below. It still functions properly and only logs "test" to the console on the correct browser width, but I'm wondering if this is a bad way to do it as the browser will be checking its width on every click even when I don't want it to. Is that a bad way of doing things? Is it better practice to try to get the first code I posted to work?
$('body').click(function() {
if ($(window).width() < 992) {
console.log("test");
$('.navbar-collapse').collapse('hide');
};
});
The second method is the way to go. The first one will only bind the click event if the width is less than 992 when that block of code initially executes.
What if the user resizes the browser after the initial decision to bind/not bind has been made? That's why you need to check the width on every click.
If you bind your click event handler using .bind(), you can use the .resize() event to only have the handler bound when the screen is under your desired width. The .unbind() function does the job. For example:
var collapseNavbar = function() {
console.log("test");//remove when done with testing
$('.navbar-collapse').collapse('hide');
}
$(window).resize(function() {
if($(window).width() < 992) {
$('body').bind('click',collapseNavbar);
} else {
$('body').unbind('click',collapseNavbar);
}
});
This way the check for window width is only done while/after resizing, and not on every click.
The bound function can be named as you wish, just make sure it is indeed named so unbinding can work properly. As the documentation says:
By naming the handler, we can be assured that no other functions are accidentally removed.
I'm not sure if the resize event is raised when the page is loaded, though. You might need to add a little snippet to ensure the behavior is present for a browser window which starts at a width lower than 992px (i.e. if you refreshed the page after resizing, or if you're viewing it on a smartphone). Something like this should do it:
$(document).ready(function() {
if($(window).width() < 992) {
$('body').bind('click',collapseNavbar);
}
});

Remove and Add scroll event handler using jQuery .off or .unbind

I am writing my own image Lazy Loading function that when a div is scrolled to its bottom we load some new images, the height of the container div (#ScrollDiv in this case) is increased and when we scroll to the bottom again we make the same call. This is fine although I pass a 'pagination ID' with each request for more images (this is called appName.featureName.PaginationConstant and in a parent scope) and I want to remove or freeze the scroll event so we don't make other requests or increment the pagination ID. For example:
appName.featureName.lazyLoader = function() {
var currentScroll = $(this).scrollTop(),
divHeight = $(this)[0].scrollHeight,
actualHeight = $(this).height() + parseInt($(this).css('padding-bottom'))
// have we hit the bottom of the Scroll Div?
if((divHeight - actualHeight) <= currentScroll ) {
// yes we have, remove the scroll, see I name this function below
$('#ScrollDiv').off('scroll', appName.featureName.lazyLoader);
// Now get more photos, in the function below I shall re-bind the scroll functionality
appName.featureName.getMorePhotos(++appName.featureName.PaginationConstant);
}
};
// this is the lazyload funtion
appName.featureName.lazyLoad = function () {
$('#ScrollDiv').on('scroll', appName.featureName.lazyLoader);
};
Everything works great apart from the unbinding! I am still able to fire the scroll event handler despite the fact I have tried to remove it once my condition is met with $('#ScrollDiv').off('scroll', appName.featureName.lazyLoader);
What am I doing wrong?
Have you ever tried like this?
$('#ScrollDiv').on('scroll','#ScrollDiv', appName.featureName.lazyLoader);
and
$('#ScrollDiv').off('scroll','#ScrollDiv', appName.featureName.lazyLoader);
or you can use the method bind too
$('#ScrollDiv').bind('scroll', appName.featureName.lazyLoader);
and
$('#ScrollDiv').unbind('scroll', appName.featureName.lazyLoader);
jQuery's .off() function doesn't work that way. If you wanna add and remove only your own scroll handler and leave other 3rd party scroll handlers alone, you want to use
$("#scrollDiv").on("scroll.appName", appName.featureName.lazyLoader);
and to remove all of your own handlers:
$("#scrollDiv").off(".appName");
or, to only remove your own scroll handler, but leave a click handler alone:
$("#scrollDiv").off("scroll.appName");
See the documentation at http://api.jquery.com/off/ for more information.

window.scroll events triggering twice

No matter what method I use to detect scrolling on the page the event is triggered twice. Please see the code for the different methods I have tried.
<body onmousewheel="alert('Why are you alerting twice?')">
or
<script src="js/jquery-1.8.3.min.js"></script>
<script>
$(window).scroll(function(){
alert("Why are you alerting twice?");
});
</script>
or
window.onscroll = please_scroll;
function please_scroll() {
alert("Why are you alerting twice?");
}
I have even tried using $.debounce.
In case it is of any use I will explain what I am trying to do:
When the user scrolls the wheel either up or down, the page will animate the scroll to the next full width content div. I have code that is successfully doing this onclick of my menu, but I would also like it to happen as the user scrolls, essentially auto assisting them with scrolling to each part of my page. This is the function I currently have for scrolling:
function scrollTo(id){
// Scroll
$('html,body').animate({scrollTop: $("#"+id).offset().top - 110},'slow',function(){
animation_active = "false";
});
}
many devices can trigger scroll events which appear to happen once more often. simply use a timeout for that:
var timeout;
$(window).scroll(function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
// do your stuff
}, 50);
});
you can play with the value 50, i recommend something between 50 and 150.

jQuery - auto input focus when scroll hit certain element

I am using jQuery plugin called Waypoints
to work with scroll action.
What I want to achieve is setting focus on the first input element of a section that is in the viewport and move the focus to the input of next respective sections when scrolled down. And, when scroll back to the first section up above, it should set the focus back to the input of the first section.
The following is what I have on my actual working setup that is using the aforementioned plugin.
Unfortunately, I can't really get the plugin up and running in my JS Fiddle.
This code block works in terms of setting focus on page load and changing focus to the targeted input when scrolled down
but scrolling back to the top section does not set the focus back.
(function($) {
var firstInput = $('section').find('input[type=text]').filter(':visible:first');
if (firstInput != null) {
firstInput.focus();
}
$('section').waypoint(function () {
var getFocus = $(this).find('input[type=text]').filter(':visible:first');
getFocus.focus();
});
$('section').waypoint(function () {
var getFocus = $(this).find('input[type=text]').filter(':visible:first');
getFocus.focus();
}, {
offset: function () {
return -$(this).height();
}
});
});
Here is my JS Fiddle
that doesn't have the plugin part.
As long as somebody can explain how they should be done in normal jQuery
if not familiar with this plugin.
jQuery Waypoints is very straightforward to use. I haven't tried with your code but I got it done with this:
$('input:first').focus();
$('section').waypoint(function() {
$(this).find('input:first').focus();
});
Please see this fiddle.
However, using mousewheel on scrolling down, the scroll sometimes jumps back at the mid part. It might be how the browser reacts on input focus. I haven't gone through the whole documentation but there is no example for input focus.
If you're only looking to do just this simple task I suggest you drop the plugin. I can show you how to get this done with jQuery.
You can handle the scrolling with jQuery's scroll() function. You need to get the scrollTop() on scrolling event then compare it with the <input>'s top offset().
$(window).scroll(function(){
var st = $(this).scrollTop();
$('input[type=text]').each(function(){
var offset = $(this).offset();
if(st >= offset.top -20 && st < offset.top + $(this).height()){
$(this).focus();
}
});
});
Here is the fiddle.

preventDefault() on touchstart without disabling scrolling

I use the following script to prevent the first tap on a link:
$(document).ready(function () {
$('#container a').bind("touchstart",function(e){
var $link_id = $(this).attr('id');
if ($(this).parent().parent().data('clicked') == $link_id) {
return true;
} else {
e.preventDefault();
}
});
});
Because these links [#container a] are covering the whole screen I am not able to scroll on touch devices.
Is there a way to keep the scrolling behavior working if the user scrolls (touchmove / swipe / drag / …)?
Maybe there is another way / script to get the effect I want without disabling scrolling…?
I found another solution to this problem by using quo.js this library will handle tap event without effecting on scrolling functionality
the code will be like this
$(document).ready(function () {
$$('#container a').tap(function(){
//your function here
});
});

Categories

Resources