jQuery .one(), how to use it in my case - javascript

Im working on a function who's triggering events when we scroll down the page but I need it to trigger the events only once and I can't figure out how to use .one() in my case. Could you give me a hand please ?
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('.sized').offset().top + $('.sized').outerHeight() - window.innerHeight)
{
$(".rotate").toggleClass("down"),
jQuery('.skill-bar').each(function()
{
jQuery(this).find('.skill-fill').animate(
{
width:jQuery(this).attr('data-percent')
}, 4000);
});
}
});
The main problem is that $(".rotate").toggleClass("down") triggers each time I reach the anchor and I want it to trigger only once.
The other function just set some divs to a certain width so it dont really matter since they dont go back to their original width:
Thanks for your help.

Related

jQuery scroll function fire once when element becomes visible

Hi guys I am using the scroll function on this script but it fires each time a user scrolls. I want it to only fire once when the user scrolls down to #ror. I tried using the fired variable to check if it has already been fired but that didn't seem to work. I know some people have answered this before but this is where i got the fired solution from and cant get it to work only once. Anyone think they can help please?
$( window ).scroll(function() {
var fired = 0;
console.log(fired);
if(fired == 0){
$('#ror').html('');
$('#ror').goalProgress({
goalAmount: 100,
currentAmount: 75,
textBefore: 'progress bar',
textAfter: '',
offset: 10,
});
fired=1;
}
});
You need to move the fired variable outside the scroll function.
As you are doing it now you are reinitializing the fired variable and setting it to 0 each time the scroll event gets fired.
var fired = 0;
$(window).scroll(function() {
console.log(fired);
if(fired == 0){
$('#ror').html('');
$('#ror').goalProgress({
goalAmount: 100,
currentAmount: 75,
textBefore: 'progress bar',
textAfter: '',
offset: 10,
});
fired=1;
}
});
To detect when a given #target scrolls into view, you can look at it's top position, and check if that position is already inside the viewport.
$('#target').offset().top - $(window).outerHeight() > $(window).scrollTop();
That left part of the equation is constant (as long as you don't move anything around, or change the size of the viewport). Therefore it may be wise to move that outside your event handler function. You need to keep in mind that the scroll event is rather expensive, since it fires constantly when you are scrolling, and the browser is already quite busy with the rendering of the viewport.
When the work is done, you can remove the event handler.
$(window).off(event);
So your final code would look something like this:
var triggerAtY = $('#target').offset().top - $(window).outerHeight();
$(window).scroll(function(event) {
// #target not yet in view
if (triggerAtY > $(window).scrollTop()) {
return;
}
// run your task
// remove this event handler
$(this).off(event);
});
Have a look at the demo: https://jsfiddle.net/6whnfa02/1/
Docs:
http://api.jquery.com/offset/
http://api.jquery.com/outerHeight/
http://api.jquery.com/scrollTop/
http://api.jquery.com/off/
$(window).scroll(function(event) {
var eT = $('#ror').offset().top,
wH = $(this).height(),
wSt = $(this).scrollTop();
if(wSt > (eT-wH)) {
alert('you have scrolled to the ror!');
//detach scroll event handler, as we dont want it to fire again
$(this).off(event);
}
}
The above code checks if user has scrolled down to an element. If yes, alert something and detach the scroll event handler for window. You can refer jquery documentation to see the meaning of offset, height and scrollTop.
Now, as #Pevera pointer out, it is costly to attach event handler to window scroll, you should be aware of that. If you have some heavy code execution inside scroll callback, it will hamper in scrolling the page. So, if you have to attach handler to window scroll, run the scroll callback code within a timeout callback. It ensures to run the scroll callback code after certain delay which helps to scroll the page better. Rewriting the above code with timeout will look like this:
var timeout = null;
$(window).scroll(function (event) {
if (!timeout) {
// set a timeout to run after 250ms
timeout = setTimeout(function () {
clearTimeout(timeout);
timeout = null;
var eT = $('#ror').offset().top,
wH = $(this).height(),
wSt = $(this).scrollTop();
if (wSt > (eT-wH)){
alert('you have scrolled to the ror!');
//detach scroll event handler, as we dont want it to fire again
$(this).off(event);
}
}, 250);
}
});
Everytime user scrolls the page, a timeout is set to run after(atleast) 250ms. In the timeout callback, we remove this timeout handler and check if user has scrolled to the element. If yes, we alert something and detach the scroll handler for window so that it doesn't run again.
Please refer to this FIDDLE for better understanding.
More info on this stackoverflow post and John Resig's blog post.

Script running only once

I'm trying to make a side menu that opens and closes from the left when you press the menu button.
Got the css, html code running properly but I can't figure out what I'm doing wrong with the script. It works perfectly but only once: When I press the menu button it comes out, press it again and it goes back just as intended. The problem is if I press it again it shows and it goes back by itself. Can anyone help me?
Here is my script:
$(document).ready(function(){
$('.menu-icon').click(function(){
$('#navigator').animate({left:'0px'},200);
$(this).animate({left:'250px'},200);
$('.menu-icon').click(function(){
>$('#navigator').animate({left:'-250px'},200);
>$(this).animate({left:'0px'},200);
});
});
>});
You have placed a click handler inside a click handler so it will run multiple times. Twice first time, then three times, then four times etc.
You need to have a single handler and decide how to animate based on the current state of the element. e.g. something like the following (not tested):
$(document).ready(function () {
$('.menu-icon').click(function () {
if ($('#navigator').css("left") != "0px") {
$('#navigator').animate({
left: '0px'
}, 200);
$(this).animate({
left: '250px'
}, 200);
} else {
$('#navigator').animate({
left: '-250px'
}, 200); > $(this).animate({
left: '0px'
}, 200);
}
});
});
I would suggest testing the "current state" using a class you toggle on the element as testing css values is notoriously unreliable during animation.
e.g. something like:
if ($('#navigator').toggleClass("open").hasClass("open")) {
Here you are attaching the click event listener two times. One normal and one after clicking, thats why its happening use jquery toggle
or use in this way
$(document).ready(function(){
$('.menu-icon').click(function(){
var navigator = $('#navigator');
if(navigator.offset().left == 0)
{
navigator.animate({left:'-250px'},200);
$(this).animate({left:'0px'},200);
}
else
{
navigator.animate({left:'0px'},200);
$(this).animate({left:'250px'},200);
}
});
});

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.

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

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
}
})
})

Categories

Resources