Refreshing javascript page without refreshing HTML, but as windows' width changes - javascript

The opacity of my nav bar changes as I scroll, and the rate at which it changes is based on the width of the window. Once the page is loaded, I tried changing the width but the opacity change rate is still the same. Is there a way for the opacity change rate parameters to change automatically without refreshing the page?
if ($(window).width() > 1060) {
fadenumber = 500;
}
else if ($(window).width() > 800){
fadenumber = 600;
}
else if ($(window).width() > 600){
fadenumber = 400;
}
else {
fadenumber = 200;
}
$(document).on('scroll', function () {
$('.navbar').css('opacity', ($(document).scrollTop() / fadenumber));
var fadeStart=0 ,fadeUntil=fadenumber;
var offset = $(document).scrollTop(),opacity=0
;
if( offset<=fadeStart ){
opacity=1;
}else if( offset<=fadeUntil ){
opacity=1-offset/fadeUntil;
}
$('.icon').css('opacity',opacity).html(opacity);
});
Thank you

There's an event for when the window or a DOM object gets resized.
So you can create an event listener that does this.
Here's how to get the size and add a listener. (Also here's a more in depth jsfiddle I wrote for this: http://jsfiddle.net/snlacks/65mL7btd/)
var outputDiv = $('#outputjq');
function callback(){
outputDiv.html(window.innerWidth);
}
$(window).on('resize', callback);
callback();
if you want to change the rate, you can augment the rate inside of the callback.
function callback2(){
if ($(window).width() > 1060) {
fadenumber = 500;
}
else if ($(window).width() > 800){
fadenumber = 600;
}
else if ($(window).width() > 600){
fadenumber = 400;
}
else {
fadenumber = 200;
}
}
var fadenumber;
$(window).on('resize', callback2);
callback2();

var onScroll;
$(document).on('scroll', onScroll = function () {
$('.navbar').css('opacity', ($(document).scrollTop() / fadenumber));
var fadeStart=0 ,fadeUntil=fadenumber;
var offset = $(document).scrollTop(),opacity=0
;
if( offset<=fadeStart ){
opacity=1;
}else if( offset<=fadeUntil ){
opacity=1-offset/fadeUntil;
}
$('.icon').css('opacity',opacity).html(opacity);
});
$(document).on('resize', function () {
if ($(window).width() > 1060) {
fadenumber = 500;
}
else if ($(window).width() > 800){
fadenumber = 600;
}
else if ($(window).width() > 600){
fadenumber = 400;
}
else {
fadenumber = 200;
}
onScroll();
});
[You should make variables global first]
Interpreter will check the width after resize.
You can copypaste your resize function code (without onScroll();) into scroll function, so it will check the width also when the document is being scrolled.
EDIT
You can put () after onResize function to make sure, variables will be set when document is ready (and you can put all in $(document).ready()), like this:
$(document).ready(function(){
var onResize;
$(document).on('resize', onResize = function () {
if ($(window).width() > 1060) {
fadenumber = 500;
}
else if ($(window).width() > 800){
fadenumber = 600;
}
else if ($(window).width() > 600){
fadenumber = 400;
}
else {
fadenumber = 200;
}
}()); // () to launch function right after it's declared
});

if ($(window).width() > 1060) {
fadenumber = 500;
}
else if ($(window).width() > 800){
fadenumber = 600;
}
else if ($(window).width() > 600){
fadenumber = 400;
}
else {
fadenumber = 200;
}
changeOpacityRate();
$(document).on('scroll', function ()
{
changeOpacityRate();
});
function changeOpacityRate()
{
$('.navbar').css('opacity', ($(document).scrollTop() / fadenumber));
var fadeStart=0 ,fadeUntil=fadenumber;
var offset = $(document).scrollTop(),opacity=0 ;
if( offset<=fadeStart )
{
opacity=1;
}
else if( offset<=fadeUntil )
{
opacity=1-offset/fadeUntil;
}
$('.icon').css('opacity',opacity).html(opacity);
}

Related

How to make two different functions work on window resize

I want to make a sticky banner, which becomes fixed at top when it is scrolled and unsticks at the end of the page. The document height is dependent upon images, that's why I use window load event. I have the following code:
function saleBanner() {
$(window).bind("load", function() {
// Make sale banner fixed-at-top
var s = $('.sale-container');
var pos = s.offset();
var maxTop = $(document).outerHeight() - 828 - s.outerHeight(); // 828 is the total height of site footer and sign up form
function fixedBanner() {
var currentTop = $(window).scrollTop();
if (currentTop >= pos.top && currentTop < maxTop) {
s.attr("style", ""); //kill absolute positioning
s.addClass('fixed-at-top'); //stick it
} else if (currentTop >= maxTop) {
s.removeClass('fixed-at-top'); //un-stick
s.css({bottom: 0}); //set sticker right above the footer
} else {
s.removeClass('fixed-at-top'); //top of page
}
}
$(window).scroll(fixedBanner);
});
}
saleBanner();
I want to make this function work on window resize as well. So I added the following code:
function resizeBanner() {
var viewportWidth = $(window).width();
if (viewportWidth > 767) {
saleBanner();
}
}
I have one more function resizeWindow for mobile menu, which I also need to work on window resize. So when I put this two functions together, they don't work (although they work on window resize separately):
$(window).resize(function(e) {
resizeWindow(e);
resizeBanner(e);
});
Where is my mistake? How can I make both functions work on window resize?
Update: Here is the whole code for resizeWindow function. It's rather long, but may be it would be helpful for the answer.
// Mobile menu
var MQM = 768;
var viewportWidth = $(window).width();
function navSlide() {
var headerHeight = $('.cd-header').height();
$(window).on('scroll', {previousTop: 0}, function () {
var currentTop = $(window).scrollTop();
//check if user is scrolling up
if (currentTop < this.previousTop ) {
//if scrolling up...
if (currentTop > 0 && $('.cd-header').hasClass('is-fixed')) {
$('.cd-header').addClass('is-visible');
} else {
$('.cd-header').removeClass('is-visible is-fixed');
}
} else {
//if scrolling down...
if(!$('.cd-header').hasClass('menu-is-open')) {
$('.cd-header').removeClass('is-visible');
}
if( currentTop > headerHeight && !$('.cd-header').hasClass('is-fixed')) $('.cd-header').addClass('is-fixed');
}
this.previousTop = currentTop;
});
}
// Primary navigation slide-in effect on load
if(viewportWidth < MQM) {
navSlide();
}
function addOverflow() {
$('html').addClass('overflow-hidden');
$('body').addClass('overflow-hidden');
}
function removeOverflow() {
$('html').removeClass('overflow-hidden');
$('body').removeClass('overflow-hidden');
}
function hideHeader() {
$('.cd-header').removeClass('is-fixed is-visible');
}
function hideMenu() {
$('.cd-header').removeClass('menu-is-open is-fixed is-visible');
$('.cd-menu-icon').removeClass('is-clicked');
}
function resizeWindow() {
var viewportWidth = $(window).width();
$(window).off('scroll'); // unbind scroll event
if (viewportWidth > 767) {
if ($('.cd-primary-nav').hasClass('is-visible')) {
if ($('.algolia__search-content').hasClass('algolia__search-content--active')) {
hideMenu();
$('.search-trigger').addClass('is-clicked');
$('.search-header').addClass('is-fixed');
} else {
hideMenu();
if (!$('.js-algolia__input').is(':focus')) {
$('.cd-primary-nav').removeClass('is-visible').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',function(){
removeOverflow();
});
$('.search-trigger').removeClass('is-clicked');
$('.search-header').removeClass('is-fixed');
} else {
$('.search-trigger').addClass('is-clicked');
$('.search-header').addClass('is-fixed');
}
}
} else {
hideHeader();
}
} else {
navSlide();
if ($('.cd-primary-nav').hasClass('is-visible')) {
$('.cd-header').addClass('menu-is-open');
$('.cd-menu-icon').addClass('is-clicked');
$('.search-trigger').removeClass('is-clicked');
$('.search-header').removeClass('is-fixed');
}
}
}

Jquery scroll plugin scrolls down only

Im making a plugin with jquery and it makes use of a mouse scroll event.
The problem is i get it scrolls down even when im scrolling up.
Here i got my code
HTML:
<body>
<!-- <div id="element"></div> -->
<div id='wrapper'>
<img id='img1' src='./images/image1.jpg'>
</div>
<script>
$(document).ready(function()
{
$(document).scrollPage();
});
</script>
</body>
Javascript:
$.extend(Plugin.prototype, {
init: function () {
document.addEventListener('scroll', this.checkScroll);
},
checkScroll: function(event) {
//Guess the delta.
var delta = 0;
if (event.wheelDelta) {
delta = event.wheelDelta/120;
}
else if (event.detail) {
delta = -event.detail/3;
}
if(delta / 120 > 0){
console.log('up');
}
else{
console.log('down');
}
}
});
Somehow when i scroll the code always come in the else statement console.log('down');
is the formula delta / 120 > 0 wrong in this code?
Check current scrollTop vs previous scrollTop
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st;
});
My solution for:
/**
* Plugin that makes the screen scroll particular component visible on the screen
*/
$.fn.scrollTo = function() {
var isVisibleOnScreen = function(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
};
if(!isVisibleOnScreen(this)){
$('html, body').animate({
scrollTop: $(this).offset().top + 'px'
}, 'fast');
return this; // for chaining...
}
};
Usage:
$('#top').scrollTo();
i fixed it this way:
$.extend(Plugin.prototype, {
init: function () {
var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
if (document.attachEvent){
document.attachEvent('on'+mousewheelevt, function(e){scroller(e)});
}
else if (document.addEventListener){
document.addEventListener(mousewheelevt, function(e){scroller(e)},false);
}
function scroller(evt)
{
//Guess the delta.
var delta = 0;
if (!evt) evt = window.event;
if (evt.wheelDelta) {
delta = evt.wheelDelta/120;
}
else if (evt.detail) {
delta = -evt.detail/3;
}
if(delta /120 > 0){
console.log('up');
}
else{
console.log('down');
}
}
}
});

Disabling JavaScript on certain conditions like a media query

I'm trying to disable this script to run at a certain screen size.
<script>
function init() {
window.addEventListener('scroll', function(e){
var distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = 250,
header = document.querySelector("header");
if (distanceY > shrinkOn) {
classie.add(header,"smaller");
} else {
if (classie.has(header,"smaller")) {
classie.remove(header,"smaller");
}
}
});
}
window.onload = init();
</script>
I've tried wrapping the code with the following
if($(window).width() > 1200) {
// script here
}
And
window.addEventListener('resize', function(){
if(window.innerWidth > 568){
// script here
}
});
But none of them seems to work. Any recommendations?

Call function which is in window resized event from within window scroll event?

I have a variable called size and a function that depends on it. As the variable depends on the screen width and needs to change if the width varies, I need to have it within a the window resize event. However I also want to call it from with other events such as a scroll event.
$(window).resize(function (){
if ($(window).width() > 1200) {
var size = "large";
}
else {
var size = "small";
}
function showRow(param) {
if (size == "large") {
$(".result.hidden").slice(0, 3).removeClass('hidden').each(someFunction);
}
else if (size == "small") {
$(".result.hidden").slice(0, 2).removeClass('hidden').each(someFunction);
}
}
});
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 50) {
showRow();
}
});
You can do this, showRow is a global var and calculating of the window size occurs in it, so you can call it inside of resize and for scrolling. This is assuming you wanted to also use showRow inside of your resize. If you don't have any other code inside of resize, then you can just delete that altogether in the first example
var showRow = function() {
if ($(window).width() > 1200) {
var size = "large";
}
else {
var size = "small";
}
if (size == "large") {
$(".result.hidden").slice(0, 3).removeClass('hidden').each(someFunction);
}
else if (size == "small") {
$(".result.hidden").slice(0, 2).removeClass('hidden').each(someFunction);
}
}
$(window).resize(function (){
showRow();
// other code
});
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 50) {
showRow();
}
});
If you don't want to use showRow inside of resize then
// initialize windowSize
var windowSize = $(window).width() > 1200 ? "large" : "small";
var showRow = function () {
if (windowSize == "large") {
$(".result.hidden").slice(0, 3).removeClass('hidden').each(someFunction);
} else if (windowSize == "small") {
$(".result.hidden").slice(0, 2).removeClass('hidden').each(someFunction);
}
}
$(window).resize(function () {
if ($(window).width() > 1200) {
windowSize = "large";
} else {
windowSize = "small";
}
// other code
});
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 50) {
showRow();
}
});

Do something if screen width is less than 960 px

How can I make jQuery do something if my screen width is less than 960 pixels? The code below always fires the 2nd alert, regardless of my window size:
if (screen.width < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
Use jQuery to get the width of the window.
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
You might want to combine it with a resize event:
$(window).resize(function() {
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
});
For R.J.:
var eventFired = 0;
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
eventFired = 1;
}
$(window).on('resize', function() {
if (!eventFired) {
if ($(window).width() < 960) {
alert('Less than 960 resize');
} else {
alert('More than 960 resize');
}
}
});
I tried http://api.jquery.com/off/ with no success so I went with the eventFired flag.
I recommend not to use jQuery for such thing and proceed with window.innerWidth:
if (window.innerWidth < 960) {
doSomething();
}
You can also use a media query with javascript.
const mq = window.matchMedia( "(min-width: 960px)" );
if (mq.matches) {
alert("window width >= 960px");
} else {
alert("window width < 960px");
}
// Adds and removes body class depending on screen width.
function screenClass() {
if($(window).innerWidth() > 960) {
$('body').addClass('big-screen').removeClass('small-screen');
} else {
$('body').addClass('small-screen').removeClass('big-screen');
}
}
// Fire.
screenClass();
// And recheck when window gets resized.
$(window).bind('resize',function(){
screenClass();
});
I would suggest (jQuery needed) :
/*
* windowSize
* call this function to get windowSize any time
*/
function windowSize() {
windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
}
//Init Function of init it wherever you like...
windowSize();
// For example, get window size on window resize
$(window).resize(function() {
windowSize();
console.log('width is :', windowWidth, 'Height is :', windowHeight);
if (windowWidth < 768) {
console.log('width is under 768px !');
}
});
Added in CodePen :
http://codepen.io/moabi/pen/QNRqpY?editors=0011
Then you can get easily window's width with the var : windowWidth
and Height with : windowHeight
otherwise, get a js library :
http://wicky.nillia.ms/enquire.js/
use
$(window).width()
or
$(document).width()
or
$('body').width()
I know i'm late to answer this, but i hope it is of some help to anybody who have similar problem. It also works when page refreshes for any reason.
$(document).ready(function(){
if ($(window).width() < 960 && $(window).load()) {
$("#up").hide();
}
if($(window).load()){
if ($(window).width() < 960) {
$("#up").hide();
}
}
$(window).resize(function() {
if ($(window).width() < 960 && $(window).load()) {
$("#up").hide();
}
else{
$("#up").show();
}
if($(window).load()){
if ($(window).width() < 960) {
$("#up").hide();
}
}
else{
$("#up").show();
}
});});
Try this code
if ($(window).width() < 960) {
alert('width is less than 960px');
}
else {
alert('More than 960');
}
if ($(window).width() < 960) {
alert('width is less than 960px');
}
else {
alert('More than 960');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My solution for the question using Vanilla JS is,
window.addEventListener("load", function () {
if (window.innerWidth < 960) { doSomething(); }
}
This works, but with one problem, whenever resizing the screen in dev tools, which is a common thing for developers, the function does something will not be fired.
For example, if we display the webpage on a computer with a screen size of more than 1000px, the function will not be fired, and when we resize the windows to less than the target(here 960px) we expect the event to be fired but that is not what happens.
By the time the script file is already processed and finished and will not be re-read, so we need to fire an event whenever we resize the screen and handle that event using "addEventListener", Just like this;
window.addEventListener("resize", (e) => {
const windowWidth = window.innerWidth;
if (windowWidth > 960) { doSomething(); }
if (windowWidth < 960) { doSomething(); }
});
The best practise is to combine both the code-snippets in the project.
Simple and clean solution using Vanilla JavaScript
let app = document.getElementById('app')
const changeColorFn = ( app, color ) => {
app.setAttribute("style",`background: ${color}`)
}
const winSizeFn = ( winWidth, callback, app, color ) => {
if (window.innerWidth < winWidth ) {
callback(app, color);
}
}
winSizeFn( '1200', changeColorFn, app, 'red' )
winSizeFn( '800', changeColorFn, app, 'green' )
winSizeFn( '500', changeColorFn, app, 'blue' )
window.addEventListener("resize", (e) => {
// add winSizeFn here if you want call function on window resize
})
<div id="app">My app content</div>
nope, none of this will work. What you need is this!!!
Try this:
if (screen.width <= 960) {
alert('Less than 960');
} else if (screen.width >960) {
alert('More than 960');
}

Categories