prevent javascript from loading more than once [duplicate] - javascript

This question already has an answer here:
Running function on window scroll once in jQuery
(1 answer)
Closed 6 years ago.
I was trying to run on scroll load more but I want it to only run once. The code below keeps on running each time the scroll reaches bottom of page.
I need to add something to the code
if ($(window).scrollTop() == $(document).height() - $(window).height() && x==24 ){
but i don't know what to add to make it so that it only runs once or so that the code is prevented from running more than once.
<script>
if ($(window).scrollTop() == $(document).height() - $(window).height() && x==24 ){
});
});
</script>
so basically my question is how to prevent javascript from running more than once.

If the scroll event is only needed to call the function once, you can then remove the scroll event from $(window) using .off() within if statement.
body {
height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="div1">div </div>
<script>
x = 24;
$(document).ready(function() {
$(window).on("scroll.once", function() {
if ($(window).scrollTop() == $(document).height() - $(window).height() && x == 24) {
$(window).off("scroll.once");
$("#div1").append(123);
}
});
});
</script>

I have a simple but not too elegant solution where you can add a boolean flag before the function and check the boolean state before executing the codes in your function. Change to the desire boolean state after the first call of your function so that you can prevent it from being called again. For example:
<script>
var called = false;
function myFunc(){
if (!called){
//your code here
called = !called;
}
}
</script>
It will not be the best answer out there but still, hope it helps =)

Related

jQuery Scroll function for a web page is not working out?

I am trying to set scroll for a web page but it's not working out properly.
What I want is that when someone scroll to the middle of the or at least a little up before the footer element so I want to trigger scroll event and then wait for like 10 to 15 seconds as on triggering the scroll event the data is loaded through ajax which takes time and then each time to do so when someone goes down again to the footer so again the scroll function should get triggered.
What I am working now with is as follows but I want to enhance it to the above requirements :
$(document).on('scroll', function() {
if($(this).scrollTop()>=$('footer').position().top){
$('div#load_more').click();
}
});
Use $(window) instead of $(document)
// helper function does exactly what it says
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
var $canfetch = true;
$(window).on('scroll', function(e) {
var scrollHeight = $(window).scrollTop();
var scrollPosition = $(".highlight")[0].offsetTop;
// if user has reached bottom of page the sleep function for next scroll event will be fired.
if (scrollPosition-scrollHeight <= 0) {
if($canfetch) {
console.log("ajax call here");
}
$canfetch = false;
// sleep function usage
sleep(15000).then(() => {
alert("15 seconds have passed");
// return to top of page
$(window).scrollTop(0);
$canfetch = true;
});
}
});
.ok {
height:500px;
}
.highlight{
height:20px;
text-align:center;
background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ok"></div>
<div class="highlight">Reference Point</div>
<div class="ok"></div>
I just did a jsfiddle test of your code and had following observations:
a. Assuming the footer is in a div
if you are using class='footer' then you have to use
$('.footer').position().top
If you are using id='footer' then you have to use $('#footer').position().top
b. I added console.log($(this).scrollTop() + '~~footer positon top is '+ $('.footer').position().top); and found that the condition is never met.
1671~~footer positon top is 1868 when I scrolled all the way down.
Hope this helps a bit.
Side Note: You might want to consider a cool plugin called ajax load more to achieve similar feature.
Use the below function use $(window) instead of $(document):
$(window).on('scroll', function(e) {
alert("Scrolled");
});

Make script run once per pageload

How do I make the following, run only once per pageload...
$(window).scroll(function(){
if($(document).scrollTop()>=$(document).height()/5)
$("#spopup").show("slow");else $("#spopup").hide("slow");
});
Here is what I use to close the pop up in case that makes a difference...
function closeSPopup(){
$('#spopup').hide('slow');
}
http://codepen.io/john84/pen/vgWVRp
I was reading up on the .one() function but am unsure as where to put it
http://api.jquery.com/one/
At the end of the function call, redefine the function.
$(window).scroll(function(){
if($(document).scrollTop()>=$(document).height()/5)
$("#spopup").show("slow");else $("#spopup").hide("slow");
$(window).scroll(function(){});
});
The first time they scroll, it will execute the function (based on your if/else) and after completing that action, it clears the javascript linked to on scroll
there is many ways to do this. i think setting a flag is going to work :
var isopen = false;
$(window).on('scroll', function(){
if($(document).scrollTop() >= $(document).height()/5 && isopen == false) {
$("#spopup").show("slow");
isopen = true;
$(window).off('scroll');
}
});

.delay() not working on my .show() JQuery

I'm trying to make my footer disappear when on a mobile device and only when the keyboard is open. Which I have working perfectly, however the issue is that the footer reappears before the keyboard has time to close. Which is because I'm using the event from the textbox having focus not the keyboard being open. So I thought the best way to resolve this is with a .delay() however, this isn't working at all. Anyone have any ideas here?
<script>
var isMobileView = false; //global variable
$(document).ready(function () {
function setScreenWidthFlag() {
var newWindowWidth = $(window).width();
if ( $(window).width() > 600) {
isMobileView = false;
}
else {
isMobileView = true;
}
}
$(".tbinputArea").focus(function() {
if(isMobileView)
$("#footer").hide();
});
$(".tbinputArea").focusout(function() {
if(isMobileView)
$("#footer").delay(500).show();
});
setScreenWidthFlag();
$(window).on("resize", function (e) {
setScreenWidthFlag();
});
});
</script>
$("#footer").delay(500).show(0);
Try this.
refer this explanation precisely explained the reasons for it http://www.mattlunn.me.uk/blog/2012/06/jquery-delay-not-working-for-you/
Delay is just for queue delay not any event delay so try to add some events within like fadeIn or similar.

.scroll() is only running once

I'm trying to create a small snippet for a sticky sidebar with jQuery. For some reason, the function inside of .scroll() is only running once instead of running at every scroll event. What could I be doing wrong?
var sticky = $('#sticky');
var staticSticky = $(sticky).offset().top;
$(window).scroll(moveEl(sticky, staticSticky));
function moveEl(element, staticElToTop){
if( $(window).scrollTop() >= staticElToTop ){
$(element).css('top', $(window).scrollTop() + 'px');
}
}
See here for the entire attempt: http://codepen.io/ExcellentSP/pen/GqZwVG
The code above is not fully functional. I'm just trying to get the scroll event to work properly before I continue.
You need to wrap content of your your moveEl method into the function (to be returned for $(window).scroll()) like this:
var sticky = $('#sticky');
var staticSticky = $(sticky).offset().top;
$(window).scroll(moveEl(sticky, staticSticky));
function moveEl(element, staticElToTop) {
return function() {
if( $(window).scrollTop() >= staticElToTop ){
$(element).css('top', $(window).scrollTop() + 'px');
}
}
}
Explanation:
The key difference is that you call a function and it returns undefined by default, so it equals to $(window).scroll(undefined). Since you actually called it, you see it's fired only once which is obvious.
As soon as you return a function within moveEl method, .scroll() gets a handler, so it becomes $(window).scroll(handler). So it will work now as expected.
In doing that $(window).scroll(moveEl(sticky, staticSticky));, you ask to javascript to execute the function. You don't pass its reference.
$(window).scroll(function(){
moveEl(sticky, staticSticky);
});

Use javascript of file.js, but isn't a typical function

I have in a javascript file code, but it isn't encapsulate in a function, specifically is an event, so I need to know how can I call this event in my html file.
$(window).scroll(function() {
if ($(window).scrollTop() > 164) {
$("ticky-nav").show();
}
else {
$("ticky-nav").hide();
}
});
and I include that like this
<script type="text/javascript" src="static/js/GD.js"></script>
Thanks for your answers
You need to make sure it is either encapsulated in a $(document).ready() handler or after the DOM has loaded
$(document).ready(function () {
$(window).scroll(function () {
if ($(window).scrollTop() > 164) {
$("ticky-nav").show();
} else {
$("ticky-nav").hide();
}
});
});
$("ticky-nav") is an invalid selector also since there is no element type of ticky-nav you are most likely looking for $("#ticky-nav") which is an element with id ticky-nav
Also make sure to include
<script type="text/javascript" src="static/js/GD.js"></script>
underneath your jQuery script tag
If you want to execute the function without the scroll event, you can create it like this:
var doScroll = function() {
if ($(window).scrollTop() > 164) {
$("ticky-nav").show();
}
else {
$("ticky-nav").hide();
}
};
And then call doScroll(); from somewhere :)

Categories

Resources