removeEventListener won't remove - javascript

I know this question is asked a lot, but I must be overlooking something, as I can't find a figure out why I can't remove the event listner in the code below.
Can someone help me out? What am I missing?
function winResize() {
viewportWidth = window.innerWidth;
viewportHeight = window.innerHeight;
const $sidebar = document.querySelector('.sidebar');
const $purchaseFormFixed = document.querySelector('form.purchase-form');
function checkFromTop() {
...
}
if ( viewportWidth >= '1000' ) {
let sidebarHeight = $sidebar.offsetHeight;
let space = viewportHeight - (sidebarHeight + 50);
if ( space > '0' ) {
window.removeEventListener('scroll', checkFromTop, false);
$sidebar.classList.add('sticky');
$purchaseFormFixed.classList.remove('show');
} else {
window.addEventListener('scroll', checkFromTop, false);
$sidebar.classList.remove('sticky');
}
}
}
window.addEventListener('resize', winResize);
winResize();

Move the checkFromTop function definition outside of winResize so that the same function reference is passed to removeEventListener.

Related

How to use value in 1 function in second function

Im still pure beginner with programing. I have this function
window.onload = function () {
currentWidth = window.innerWidth
console.log(currentWidth)
}
This function shows me in console.log what is my window width when i reload the page.
Then i have little bit complicated function which return also function.
const resizeHandler = (function () {
const isBig = () => window.innerWidth > 850
let wasBig = isBig()
return function handler(event) {
//if (isBig() == wasBig) return; // no change
if (window.innerWidth > 850) {
$('.side-bar').removeClass('non-active')
wasBig = true // future use
} else {
$('.side-bar').addClass('non-active')
wasBig = false
}
}
})()
window.addEventListener('resize', resizeHandler)
I have width value in variable called currentWidth I thought when i replace window.innerWidth by variable name currentWidth it's fine but it is not.
Is my logic correct or in javascript is "smater" way to do that please?
Directly call the resize handler on page load as well.
resizeHandler();
window.addEventListener('resize', resizeHandler);
Variables declared inside a function are function-scoped, that means they exist only inside that specific function.
Try:
var currentWidth;
window.onload = function () {
currentWidth = window.innerWidth
}
So now you can replace window.innerWidth with currentWidth, as you asked.
by LL

How to stop click event on resize & load if screen width is greater than?

I am facing this problem over and over again and just don't know how to solve this. I have a click event that I would like to fire only if the screen width is less than **576px* and if a page is loaded to make this event fire.
But when I resize the browser larger than 576px the click event still works.
Can someone please help me out how can I solve this common issue that I am facing?
Thanks in advance.
My code:
const onSearchMobile = () => {
let screenWidth = window.innerWidth;
let searchIcon = document.querySelector('.main-header__search--icon');
if (screenWidth <= 576) {
console.log('Yes lower then 576');
searchIcon.addEventListener('click', () => {
console.log('clicked!');
});
}
};
window.addEventListener('resize', onSearchMobile, false);
window.addEventListener('load', onSearchMobile);
Just check the width inside event
const onSearchMobile = () => {
let screenWidth = window.innerWidth;
let searchIcon = document.querySelector('.main-header__search--icon');
searchIcon.addEventListener('click', () => {
if (screenWidth <= 576) {
console.log('clicked!');
}
});
};
window.addEventListener('resize', onSearchMobile, false);
window.addEventListener('load', onSearchMobile);
Using MediaQueryList.onchange
let searchIcon = document.querySelector('.main-header__search--icon')
let clickListener = () => console.log('clicked!')
let mql = window.matchMedia('(max-width: 576px)')
mql.addEventListener("change", (e) => {
if (e.matches) {
searchIcon.addEventListener('click', clickListener)
} else {
searchIcon.removeEventListener('click', clickListener)
}
})
You can remove eventListener:
const onSearchMobile = () => {
let screenWidth = window.innerWidth;
let searchIcon = document.querySelector('.main-header__search--icon');
if (screenWidth <= 576) {
console.log('Yes lower then 576');
searchIcon.addEventListener('click', () => {
console.log('clicked!');
});
}
else {
searchIcon.removeEventListener('click');
}
};
window.addEventListener('resize', onSearchMobile, false);
window.addEventListener('load', onSearchMobile);

Recalculating element size on window resize

How do I propely use window.addEventListener("resize", () => { }) in the case below, where I need to recalculate size on every window resize:
const viewportWidth = Math.max(
document.documentElement.clientWidth,
window.innerWidth || 0
)
const viewportHeight = Math.max(
document.documentElement.clientHeight,
window.innerHeight || 0
)
const elements = list(48, () => {
const circle = document.createElement("span")
const minSize = Math.round((viewportWidth + viewportHeight) / 72)
const maxSize = Math.round((viewportWidth + viewportHeight) / 21)
const size = random(minSize, maxSize)
Object.assign(circle.style, {
width: `${size}px`,
height: `${size}px`
})
return circle
})
For whatever reason, I’m struggling with this, and I would greatly appreciate any help.
Try this :
window.addEventListener("resize", () => {
const docHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
document.getElementById('documentHeight').innerHTML = docHeight;
});
<div id="documentHeight">
Open this demo in full page view and resize the window to get the Inner height of the document.
</div>
You may simply encapsulate the above logic within the callback function within your event listener.
For instance,
class yourClass {
constructor() {
window.addEventListener("resize", () => {
// logic to carry out recalculation
elements();
});
}
// the rest of your logic
}
Doing so will ensure that the methods/functions will be called whenever the resize event is triggered on the Window.

Javascript - execute multiple different window.onscroll

I am facing a little problem here. I have basic knowledge about Javascript and i want to do the following:
Right now, when you scroll down, the menu will get smaller. when you go back up, it will return to normal. I call this event with window.onscroll:
var diff = 0;
function effects(){
var topDistance = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
var clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
if(topDistance > diff){
diff = topDistance;
if(clientWidth > 1024){
if(topDistance > 300){
document.getElementById("header").style.marginTop= "-100px";
}
}
}else if(topDistance < diff){
diff = topDistance;
if(clientWidth > 1024){
if(topDistance > 300){
document.getElementById("header").style.marginTop= "0";
}
}
}
}
window.onscroll = effects();
Now i want another function to have some effects to my call to action buttons, lets call the function "test", but if i want to do this the same way like above, the effects functions does not work anymore:
function test(){
//do something
}
window.onscroll = test();
Any help is welcome! I tihnk it won't be a big challenge to do this, but i am doing it wrong i guess. (PS: NO JQUERY PLEASE)
You override onscroll function by doing window.onscroll = blabla
You can do :
window.onscroll = function() {
effects();
test();
}
or
window.addEventListener('scroll', effects);
window.addEventListener('scroll', test);
You can use multiple listener for the scroll event.
window.addEventListener('scroll', effects);
window.addEventListener('scroll', test);
That way you don't override window.onscroll
you should use
window.addEventListener
instead of window.onscroll

manipulate when inview.js is firing

i would like to know how i can manipulate the inview.js script that the moment when its fired is not at first pixels in viewport, and the last when the element is going out but rather for example 50pixels later or earlier.
the script of inview.js is
(function ($) {
function getViewportHeight() {
var height = window.innerHeight; // Safari, Opera
var mode = document.compatMode;
if ( (mode || !$.support.boxModel) ) { // IE, Gecko
height = (mode == 'CSS1Compat') ?
document.documentElement.clientHeight : // Standards
document.body.clientHeight; // Quirks
}
return height;
}
$(window).scroll(function () {
var vpH = getViewportHeight(),
scrolltop = (document.documentElement.scrollTop ?
document.documentElement.scrollTop :
document.body.scrollTop),
elems = [];
// naughty, but this is how it knows which elements to check for
$.each($.cache, function () {
if (this.events && this.events.inview) {
elems.push(this.handle.elem);
}
});
if (elems.length) {
$(elems).each(function () {
var $el = $(this),
top = $el.offset().top,
height = $el.height(),
inview = $el.data('inview') || false;
if (scrolltop > (top + height) || scrolltop + vpH < top) {
if (inview) {
$el.data('inview', false);
$el.trigger('inview', [ false ]);
}
} else if (scrolltop < (top + height)) {
if (!inview) {
$el.data('inview', true);
$el.trigger('inview', [ true ]);
}
}
});
}
});
// kick the event to pick up any elements already in view.
// note however, this only works if the plugin is included after the elements are bound to 'inview'
$(function () {
$(window).scroll();
});
})(jQuery);
all credits go to here
my attemp was to add a value to offset top top = $el.offset().top + 50, which works! but how can i change the value for the bottom up?
thanks ted
I'd recommend using http://imakewebthings.com/jquery-waypoints/
Which you can call like so to achieve your desired effect at 10% from the bottom:
$('.flyIn').waypoint(function() {
$(this).removeClass('hidden');
$(this).addClass('animated fadeInUp');
}, { offset: '90%' });

Categories