if statement doesn't work for counter variable - javascript

I want my script to execute a method, when the scrollCount variable reaches a value > 2.
Code:
$( document ).ready(function() {
var scrolly = 0;
var scrollCount = 0;
console.log(scrollCount);
$('#wizard-next').click(function(e) {
e.preventDefault();
scrolly -= 300;
$( "#wizard-step-1" ).animate({ marginTop: (scrolly+'px') }, 1200);
scrollCount++;
console.log(scrollCount);
});
$('#wizard-prev').click(function(e) {
e.preventDefault();
scrolly += 300;
$( "#wizard-step-1" ).animate({ marginTop: (scrolly+'px') }, 1200);
scrollCount--;
console.log(scrollCount);
});
if(scrollCount > 2) {
console.log('Add method here!');
}
});
The if statement doesn't work. How can I fix that?

if(scrollCount > 2) {
console.log('Add method here!');
}
As I'm sure you've noticed from the comments (#Jaromanda), the if statement is only done once. Which of course at that moment is false, since scollCount will be 0.
If you want it to be called everytime a click occurs then suround it by a function.
var scrollCountCheck = function(){
if(scrollCount > 2) {
console.log('Add method here!');
}
}
And call this method in each of your click functions. right after or before scrollCount++ or scrollCount-- (depending on when you actually intended on calling it)

Related

Function is not only calling once

I am trying to execute only once, but it is executing multiple times.
I am showing alert when user reaches the 90% of the page while scrolling. But it is showing the alert multiple times.
I have also tried:
By turning statement to true after executed.
But it didn't work
File page.html
var percent = 90;
var window_scrolled;
$(window).scroll(function() {
window_scrolled = ($(document).height()/100)*90;
if($(window).scrollTop() + $(window).height() >= window_scrolled) {
var excuted = false
if (!excuted) {
alert("scrolled to bottom");
excuted = true
}
}
});
You are always setting the excuted to false each time, so it always runs.
Try this:
var excuted = false
$(window).scroll(function() {
window_scrolled = ($(document).height()/100)*90;
if($(window).scrollTop() + $(window).height() >= window_scrolled) {
if (!excuted) {
alert("scrolled to bottom");
excuted = true
}
}
});

Is it possible to split JavaScript across multiple files and access functions from each other

What I would like to do is have a JavaScript file which would contain jQuery functions that are used across multiple sites (all hosted on the same CMS - eTouches, so there is no cross domain scripting issue) and then have a site specific JavaScript file for each site which utilised the functions, making it easy to change the central function file as needed.
I am getting errors when trying to do this though, with functions not being defined when the second script it trying to execute things. Is this a possible and have I missed something basic or is it something that is not possible.
I don't think it is possible to include files as you do in PHP etc, but if I call the functions file before the site specific one I thought this should work?
Thanks in advance for any help.
Code from function document
$.noConflict();
jQuery(document).ready(function ($) {
$('☰ Menu').insertBefore($('.ehtm'));
if ($('#right_sidebar_section').length) {
} else {
$('#main_section').css('width','100%')
$('#main_section').css('marginLeft','0')
}
var mobileMenu = function (menuParent, prevSibling, menuIdentifier) {
if ($('#mobileMenu').length == 0) {
var $select = $('<div>', {
'class': 'mobile-menu',
'id': menuIdentifier
}).insertBefore(prevSibling);
$('.ehtm > ul').prependTo($('#mobileMenu'));
}
if ($('.expandContract').length==0) {
$('.mobile-menu > ul > li > a').each(function(){
$(this).css("width", "120px");
$('+<span></span>').insertBefore($(this));
})
}
$('.expandContract').click(function (evt) {
evt.preventDefault();
$(this).text($(this).text() == '+' ? '-' : '+');
$(this).parent().find("ul").slideToggle();
evt.stopImmediatePropagation();
})
};
var menuReset = function () {
$('.mobile-menu > ul').prependTo($('.ehtm'));
$('#mobileMenu').remove();
if (parseInt($('#outer_table').css('margin-left')) > 0) {
$('#outer_table').animate({
marginLeft: parseInt($('#outer_table').css('marginLeft'), 10) == 0 ? 200 : 0
});
}
$('a.expandContract').each(function(){
$(this).remove();
})
$('.ehtm > ul > li > a').each(function(){
$(this).css('width','auto');
})
}
$('.mobile-menu-toggle-link').click(function (evt) {
evt.preventDefault();
$('#outer_table').animate({
marginLeft: parseInt($('#outer_table').css('marginLeft'), 10) == 0 ? 200 : 0
});
$('.header').animate({
marginLeft: parseInt($('#outer_table').css('marginLeft'), 10) == 0 ? 200 : 0
});
$('.mobile-menu').animate({
marginLeft: parseInt($('#outer_table').css('marginLeft'), 10) == 0 ? 0 : -200
});
var wHeight = $(window).innerHeight();
var divHeight = $('#mobileMenu').height();
if (wHeight > divHeight) {
$('.mobile-menu').css("height", wHeight);
} else {
$('.mobile-menu').css("height", divHeight);
}
})
var compareWidth = $('.header').width();
/* Add class to the first table row, to allow header styling */
var headRow = $("table#outer_table").find("tr:first");
$(headRow).addClass("headerBGColor");
});
Code from site specific document
$.noConflict();
jQuery(document).ready(function ($) {
var compareWidth = $('.header').width();
var setUpPage = function () {
if (compareWidth < 768) {
mobileMenu('.ehtm li', '.header', 'mobileMenu');
}
if (compareWidth >= 768) {
menuReset();
}
/* Header image swap */
if (compareWidth>=1024) {
$("#headerImage").attr("src","https://www.eiseverywhere.com/image.php?acc=xxx&id=xxxxxx");
} else if ((compareWidth>=768) && (compareWidth<1024)) {
$("#headerImage").attr("src","https://www.eiseverywhere.com/image.php?acc=xxx&id=xxxxxx");
} else {
$("#headerImage").attr("src","https://www.eiseverywhere.com/image.php?acc=xxx&id=xxxxxx");
}
/* Carousel */
if ($('.owl-carousel').length > 0) {
$('.owl-carousel').owlCarousel({
items:1,
loop:true,
margin:10,
autoplay:true,
autoplayTimeout:3000,
dots:true
});
}
}
var breakPointCheck = function () {
var currentWidth = $('.header').width();
if (currentWidth != compareWidth) {
compareWidth = currentWidth;
setUpPage();
}
}
setUpPage();
// fixElement('.tabmenu')
$(window).resize(function () {
breakPointCheck();
});
});
They are all declared in DOM ready functions which give them a local scope. The functions cannot then be seen outside of that function and each DOM ready function is separate to the others.
You need to declare them as global functions instead (using global vars):
e.g.
// Global scope
var mobileMenu;
$.noConflict();
jQuery(document).ready(function ($) {
// Aside local function to global var
mobileMenu = function(...
The alternative is to declare the functions outside of the DOM ready handlers and make sure they are only called from code inside of DOM ready handlers. Most of the functions shown do not need to be inside DOM ready handlers as they are just declarations and are not run at that point:
e.g.
$.noConflict();
//Declare global functions
var mobileMenu = function (menuParent, prevSibling, menuIdentifier) {
if ($('#mobileMenu').length == 0) {
var $select = $('<div>', {
'class': 'mobile-menu',
...snip...
});
jQuery(document).ready(function ($) {
// Use global functions
mobileMenu(...);
});
Use jQuery.getScript()
In your shared function script, remove the jQuery(document).ready(function () {...}) wrapper.
In your site-specific document, use $.getScript() to load the shared file and place your site-specific functions in a callback that runs after the shared script loads successfully:
jQuery(document).ready(function() {
$.getScript('/url/to/functionScript.js', function () {
// Site specific functions
});
});

Load on bottom of div is not working properly

So this question is not necessarily how to get it to work, because it does. But it is very very buggy. The problem I'm having is that when you scroll down, it sometimes takes a while to load so that the function reactivates or something. Either way the variable is reset and it loads like 5 pages in a row. So it's buggy. I have the code here:
var ldid = 10;
jQuery(
function ($) {
$('#allpostcontainer').bind('scroll', function () {
if ($(this).scrollTop() +
$(this).innerHeight() >= $(this)[0].scrollHeight) {
$("#allpostcontainer").append($("<div>").load("/streampage.php?id=" + ldid, function () {
ldid = ldid + 10;
}));
}
})
}
);
You can use a flag.
If it is loading you can set it to true.
If loading finished you set it back to false
and you make ajax request only if it is false.
var ldid = 10,
isPageLoading = false;
jQuery(
function ($) {
$('#allpostcontainer').bind('scroll', function () {
if ($(this).scrollTop() +
$(this).innerHeight() >= $(this)[0].scrollHeight && !isPageLoading) {
isPageLoading = true;
$("#allpostcontainer").append($("<div>").load("/streampage.php?id=" + ldid, function () {
ldid = ldid + 10;
isPageLoading = false;
}));
}
})
}
);
If you want to set your Div tag at the end of the "allpostcontainer" div then put below script in your page.
(#bottom is Div tag id which you need to display at the bottom. #allpostcontainer is div tag id which is main Div with scroll)
<script>
$(document).ready(function () {
$('#bottom').css('position', 'absolute');
$('#bottom').css('top', $('#allpostcontainer').height() - $('#bottom').height());
});
</script>
Please let me know if you have any query.
Thank you...

Only fire a function once on scroll (scrollstop)

So, I'd like to fire a function only once on scroll (using Scrollstop, given by a stackoverflow answer)
The problem is that I don't get to fire the function only once. I've tried different solutions ( .on(), setting a counter, setting it outside/inside the window.scrollstop function) but nothing worked.
I don't think it's difficult, but.. I didn't get to make it work so far.
Here's the plugin I'm using
$.fn.scrollStopped = function(callback) {
$(this).scroll(function(){
var self = this, $this = $(self);
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
$this.data('scrollTimeout', setTimeout(callback,300,self));
});
};
and here's my code:
$(window).scrollStopped(function(){
if ($(".drawing1").withinViewport()) {
doNothing()
}
})
var doNothing = function() {
$('#drawing1').lazylinepainter('paint');
}
(removed the counter since it didn't work)
Live demo here
PS: the function I'd like to make happen only once is the lazyPaint. It begins when we scroll to the element but it fires once again when it ends.
Here's my version of having a function fire once while listening to the scroll event:
var fired = false;
window.addEventListener("scroll", function(){
if (document.body.scrollTop >= 1000 && fired === false) {
alert('This will happen only once');
fired = true;
}
}, true)
how about using a variable to see whether it was previously fired:
var fired = 0;
$.fn.scrollStopped = function(callback) {
$(this).scroll(function(){
if(fired == 0){
var self = this, $this = $(self);
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
$this.data('scrollTimeout', setTimeout(callback,300,self));
fired = 1;
}
});
};
These anwsers didn't work for me so here's my code:
var fired = 0;
jQuery(this).scroll(function(){
if(fired == 0){
alert("fired");
fired = 1;
}
});
How about this solution?
function scrollEvent() {
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
console.log('H1 on the view!');
window.removeEventListener("scroll", scrollEvent);
}
}
window.addEventListener("scroll", scrollEvent);
The question is a bit old, but as it popped up first when I search for "addeventlistener scroll once", I will add this reply. There is now a { once: true } parameter to only trigger an event once.
window.addEventListener("scroll", () => {
/* your code here */
}, { once: true });

jQuery if statement breaks my code

This is my code:
$("#header").touchwipe({
// if($('#cont-wide').css('left') == '-100%' ){
wipeLeft: function() {
$('#cont-wide').animate({
left: '-201%'
}, 500 );
$('#nav-filters').fadeOut(200);
$('#nav-map-l').delay(300).fadeIn(200);
$('#one .col-inner').delay(500).hide(0);
$('#three .col-inner').css('display','block');
setTimeout(function() {
window.scrollTo(0, 1) },
100);
},
wipeRight: function() {
$('#cont-wide').animate({
left: '1%'
}, 500 );
$('#nav-filters').fadeOut(200);
$('#nav-map-r').delay(300).fadeIn(200);
$('#one .col-inner').css('display','block');
setTimeout(function() {
window.scrollTo(0, 1) },
100);
},
min_move_x: 50,
min_move_y: 50,
preventDefaultEvents: false
// }
});
As it currently is it works fine. However when I remove the comments to add the conditional statement, the code and all my other JavaScript stops working. Thanks
You cannot put the if statement there ...
you could do this :
wipeLeft: function() {
if($('#cont-wide').css('left') == '-100%' ){
// the rest
}
},
wipeRight: function() {
if($('#cont-wide').css('left') == '-100%' ){
// the rest
}
}
Note - the css function my not produce the result you are expecting : http://jsfiddle.net/VccAn/ using a value of 10% for left in my example returns auto on Chrome ! See this question / answer for discussions related to this problem : jQuery .css("left") returns "auto" instead of actual value in Chrome
You can't just shove in an if statement in the middle of a statement.
The best solution would be creating your options object before calling touchwipe():
var options = {};
if($('#cont-wide').css('left') == '-100%') {
options.wipeLeft = function() {
};
options.wipeRight = function() {
};
}
$("#header").touchwipe(options);
Note that the if condition is only evaluated once. If you want it to be evaluated on every event, #ManseUK's answer is the way to go.

Categories