Using variable to control an event - javascript

I have a footer popup that shows when the page is scrolled a certain amount. I have a little x that the user can click to make the footer go away. I am trying to use a variable to make the footer stay hidden when the x is clicked. I am not able to get it to work like I want and I want to understand why. Here is the code:
jQuery(function($) {
$(document).scroll(function(){
var position = $(this).scrollTop();
var fired = 0;
if(position < 360 && fired === 0){
$('#popup').slideUp();
} else {
$('#popup').slideDown();
}
$('.close').on('click', function(){
$('#popup').slideUp();
fired = 1; // I thought that this was suppose to override the current variable
});
});
});
So, why does this not work?

It doesn't work because you declared var fired = 0; inside the scroll function. So whenever the user scrolls, fired is set to 0. Just declare it above the scroll-function, then it should work.

Fired is a local variable to the scroll callback and as a result is always 0. Place it outside of the callback and it will remain once set.
jQuery(function($) {
var fired = 0;
$(document).scroll(function(){
var position = $(this).scrollTop();
//...

Related

How to change a div class after scrolling past, and then change it back to original when completing the same scrolling action for a second time?

In my html I've got a div that changes its class when the user scrolls past it (and the div becomes out of view), such that when the user scrolls back up the page the class is changed.
I would like to have that div class reverted to original the second time the user scrolls back up, but just can't figure out a way to do so. I'm trying to find a way for it to work in such a way that the effect repeats and the class alternates every time it comes back into view.
I'm doing this with two scripts at the moment. The first one works and changes the class of the div when the user scrolls back up:
<script>
$(function() {
var scroll1 = $(window).scrollTop(); // how many pixels have been scrolled
var os1 = $('#div1').offset().top; // pixels to top of div1
var ht1 = $('#div1').height(); // height of div1 in pixels
if (scroll > os1 + ht1) {
$('#div1').removeClass('english').addClass('japanese');
}
});
</script>
But the second one doesn't seem to do anything at all:
<script>
$(function() {
var scroll2 = $(window).scrollTop();
var os2 = $('#div1').offset().top;
var ht2 = $('#div1').height();
var class1 = document.getElementsByClassName('japanese')[0].className;
if (scroll > os1 + ht1 && class1 == 'japanese') {
$('#div1').removeClass('japanese').addClass('english');
}
});
</script>
I guess this is happening because you have the same conditions in both of the functions.
For the second condition use this instead
if(scroll < os1 + ht1)

Updating global variable on scroll event attached to a DOM element

I've got a situation where I want a variable to be updated when scrolling inside a <div>. There is a series of other things which will happen depending on this variable updating, so I don't want to wrap it inside the scroll event. Is there a way to avoid that?
Here is my JS:
var scrollEl = document.getElementById("scrollEl");
var scrollElWidth = scrollEl.offsetWidth;
var scrolled = 0;
var updater = function(updated) {
scrolled = Math.round(updated);
return scrolled;
}
scrollEl.addEventListener("scroll", function() {
var percentage = 100 * scrollEl.scrollLeft / (scrollEl.scrollWidth - scrollElWidth);
//This works
console.log(updater(percentage));
});
//This doesn't
console.log('Updated scroll variable: ', scrolled);
Here is a fiddle: https://jsfiddle.net/0u4fp0yv/

Retaining scrollbar position using jquery

I have a java function,
private GroupsSelector group(LabourInputReportCriteria.Level level) {
HtmlSelectBooleanCheckbox box = new HtmlSelectBooleanCheckbox();
boolean isSelected = selections.isGroupSelected(level);
box.setSelected(isSelected);
// box.setDisabled(isDaySelectedOnFirst(level));
String id="groupBy" + level.getClass().getSimpleName();
box.setId(id);
box.setOnclick("submit()");
box.addValueChangeListener(u.addExpressionValueChangeListener("#{reportSearchCriteriaModel.groupBy}"));
HtmlOutputText labelComponent = new HtmlOutputText();
labelComponent.setValue(getGroupSelectionValue(level));
tr().td();
html(box);
html(" ");
html(labelComponent);
//html("<span id='"+id+ "'></span>");
//html("<script> function resetGroupsSelector() { var x = document.getElementById('search_report_form:groupByWeekLevel'); alert(x); } </script>");
endTd().endTr();
return this;
}
Whenever I click on a checkbox, sumbit() is called and it has some functionality at the backend. Now, my question is whenever I click on a checkbox, the scrollbar position is moving up i.e, it is going on top of the page. I want to avoid this. I want to retain my scrollbar position as it is. How am I supposed to do it?
I tried adding the follwing code but it dint work.
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" >
var addTweet = function() {
var scrollPosition = $(document).scrollTop();
$('#results9016').prepend($newTweet);
$('html, body').scrollTop(scrollPosition);
}
</script>
Please help.
inside the function that you call when clicking you can say
function submit(event) {
event.preventDefault();
...
}

Pure js add and remove (toggle) class after scrolling x amount?

I don't want to use jQuery for this.
It's really simple, I just want to add a class after scrolling past a certain amount of pixels (lets say 10px) and remove it if we ever go back to the top 10 pixels.
My best attempt was:
var scrollpos = window.pageYOffset;
var header = document.getElementById("header");
function add_class_on_scroll() {
header.classList.add("fade-in");
}
function remove_class_on_scroll() {
header.classList.remove("fade-in");
}
window.addEventListener('scroll', function(){
if(scrollpos > 10){
add_class_on_scroll();
}
else {
remove_class_on_scroll();
}
console.log(scrollpos);
});
But console shows a number that continues to grow regardless of scrolling up or down. And the class fade-in never gets added, though console shows we past 10.
You forgot to change the offset value in the scroll handler.
//use window.scrollY
var scrollpos = window.scrollY;
var header = document.getElementById("header");
function add_class_on_scroll() {
header.classList.add("fade-in");
}
function remove_class_on_scroll() {
header.classList.remove("fade-in");
}
window.addEventListener('scroll', function(){
//Here you forgot to update the value
scrollpos = window.scrollY;
if(scrollpos > 10){
add_class_on_scroll();
}
else {
remove_class_on_scroll();
}
console.log(scrollpos);
});
Now you code works properly
Explanation
There is no documentation for that, like you asked for. This is just an issue in the logic workflow.
When you say that scrollpos = window.scrollY your page is at an top-offset of 0, so your variable stores that value.
When the page scrolls, your scroll listener will fires. When yout listener checks for the scrollpos value, the value is still 0, of course.
But if, at every scroll handler, you update the scrollpos value, now you can have a dynamic value.
Another option is you to create a getter, like
var scrollpos = function(){return window.scrollY};
This way you can dynamically check what that method will return for you at every offset.
if(scrollpos() > 10)
See? Hope that helped. (:
One simple way to achieve what you want (one line of code inside the scroll event):
window.addEventListener('scroll', function(e) {
document.getElementById('header').classList[e.pageY > 10 ? 'add' : 'remove']('fade-in');
});
#header {
height: 600px;
}
.fade-in {
background-color: orange;
}
<div id='header'></div>
just use the method toggle in classList
header.classList.toggle('fade-in')

How can I set my browser window's scrollbar or a div scrollbar to scroll in increments using animate and scrollTop?

The general idea to the site i am designing is to scroll through a set of menu items horizontally and incrementally underneath a static div that will magnify(increase dimensions and pt size) the contents of a menu items. I don't really need help with the magnify portion because i think it's as simple as adding a mag class to any of the menuItem divs that go underneath the static div. I have been messing with this for a few weeks and the code I have for incrementally scrolling, so far, is this:
$(document).ready(function () {
currentScrollPos = $('#scrollableDiv').scrollTop(120); //sets default scroll pos
/*The incrementScroll function is passed arguments currentScrollPos and UserScroll which are variables that i have initiated earlier in the program, and then initiates a for loop.
-The first statement sets up the variables: nextScrollPos as equal to the currentScrollPos(which by default is 120px) plus 240px(the distance to next menuItem), prevScrollPos as equal to the currentScrollPos(which by default is 120px) minus 240px(the distance to next menuItem).
-The second Statement checks to see if the user has scrolled using var userScroll
-The third statement sets: var CurrentScroll equal to the new scroll position and var userScroll to false*/
function incrementScroll(currentScrollPos, userScroll) {
for (var nextScrollPos = parseInt(currentScrollPos + 240, 10),
prevScrollPos = parseInt(currentScrollPos - 240, 10); //end first statement
userScroll == 'true'; console.log('dude'), //end second statement and begining of third
currentScrollPos = scrollTop(), userScroll = 'false') {
if (scrollTop() < currentScrollPos) {
$('#scrollableDiv').animate({
scrollTop: (parseInt(prevScrollPos, 10))
}, 200);
console.log('scrolln up')
} else if (scrollTop() > currentScrollPos) {
$('#scrollableDiv').animate({
scrollTop: (parseInt(nextScrollPos, 10))
}, 200);
console.log('scrolln down')//fire when
}
}
}
$('#scrollableDiv').scroll(function () {
userScroll = 'true';
_.debounce(incrementScroll, 200); //controls the amount of times the incrementScroll function is called
console.log('straight scrolln')
});
});
I have found a variety of solutions that are nigh close: such as a plugin that snaps to the next or previous div horizontally demo, another solution that also snaps and is based on setTimeout demo, but nothing that nails incrementally scrolling through divs. I also found a way to control the rate at which a user may scroll through the menuItems using debounce which is included in the above code.
The console.logs inside the loop do not fire when I demo the code in jsfiddle which leads me to believe the problem lies within the loop. I'm a noob though so it could be in syntax or anywhere else in the code for that matter. Also in the second demo, i have provided the css for the horizontal static div, but the moment I put it in my html it keeps the js from working.
I would like to write the code instead of using a plugin and any help would be appreciated! Also, thank you ahead of time!
Try this fiddle. Menu container height is 960px to show 4 menu items. "Zoom" div is positioned absolutely at top. When you scroll mouse over this div, menu items shifts to top/bottom. I had to add additional div to bottom to be able to scroll to last 3 menu items. JS code:
jQuery(document).ready(function($){
var current = 0;
var menu = $('.menu-container').scrollTop(0);
var items = menu.find('.menu-item');
var zoom = $('.zoom');
function isVerticalScroll(event){
var e = event.originalEvent;
if (e.axis && e.axis === e.HORIZONTAL_AXIS)
return false;
if (e.wheelDeltaX)
return false;
return true;
}
function handleMouseScroll(event){
if(isVerticalScroll(event)){
var delta = event.originalEvent.wheelDelta * -1 || event.originalEvent.detail;
current += (delta > 0 ? 1 : -1);
if(current < 0)
current = 0;
if(current >= items.length){
current = items.length - 1;
}
menu.stop().animate({
"scrollTop": current * 240
}, 300);
items.removeClass('current').eq(current).addClass('current');
event && event.preventDefault();
return false;
}
}
zoom.on({
"MozMousePixelScroll": handleMouseScroll,
"mousewheel": handleMouseScroll
});
});
Hope it will help.

Categories