Disable javascript function in specific size of screen - javascript

I want to disable the javascript function in specific size of screen - and enable it in specific size of screen.
Here is my code:
$(document).ready(function(){
$("#moveleft").click(function(){
if ($(window).width() < 768) {
$('.box__image').animate({'left' : "-=330px"});
}
});
});

You could listen to window's size change event
$(document).ready(function() {
$(window).on('resize', function() {
if ($(this).width() < 768) {
$("#moveleft").click(function() {
$('.box__image').animate({
'left': "-=330px"
});
});
} else {
$("#moveleft").off('click')
}
});
});

Related

How not to execute JavaScript code when the screen has a specific size?

I am using the following to add and remove CSS classes based on the current scroll position:
$(function() {
var header = $(".grid-bar");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 400) {
header.addClass("move");
} else {
header.removeClass("move");
}
});
});
But I want to disable the addition and removal of the CSS classes on a screen size smaller than 800px.
I have tried wrapping the code in a resize function but after I do so, it stops responding at all:
$(window).resize(function(){
if ($(window).width() => 800){
var header = $(".grid-bar");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 400) {
header.addClass("move");
} else {
header.removeClass("move");
}
});
}
});
As others have mentioned, you have an improper operator for "greater than or equal to". The following is incorrect:
if ($(window).width() => 800) {
// ^^ this operator is wrong
if ($(window).width() >= 800) {
// ^^ it should be like this
Also, you need to bind and unbind the scroll handler whenever the screen size changes. You will need to keep track of whether or not the scroll handler is bound or not. Here is what that looks like:
const $window = $(window);
const $header = $(".grid-bar");
let isBound = false;
const scrollHandler = function() {
const scroll = $window.scrollTop();
if (scroll >= 400) {
header.addClass("move");
} else {
header.removeClass("move");
}
}
$(window).resize(function(){
if ($window.width() >= 800) {
if (!isBound) {
$window.on('scroll', scrollHandler);
isBound = true;
}
} else if (isBound) {
$window.off('scroll', scrollHandler);
isBound = false;
}
});
$window.trigger('resize');
Here is a fiddle: https://jsfiddle.net/1mru359x/5/

How to Disable / Re-enable Javascript on window resize?

I need to be able to disable / re-enable Javascript on window resize?
Currently when the window is resized on the desktop, the nav bar sticks and is the only thing visible instead of the content.
<script>
if ( $(window).width() <= 1200 ) {
}else{
$('nav').addClass('original').clone().insertAfter('nav').addClass('cloned').css('position','fixed').css('top','0').css('margin- top','0').css('z-index','500').removeClass('original').hide();
scrollIntervalID = setInterval(stickIt, 10);
function stickIt() {
var orgElementPos = $('.original').offset();
orgElementTop = orgElementPos.top;
if ($(window).scrollTop() >= (orgElementTop)) {
as original element.
orgElement = $('.original');
coordsOrgElement = orgElement.offset();
leftOrgElement = coordsOrgElement.left;
widthOrgElement = orgElement.css('width');
th',widthOrgElement).show();
$('.original').css('visibility','hidden');
} else {
$('.cloned').hide();
$('.original').css('visibility','visible');
}
}
</script>
You can bind an event handler to the "resize" JavaScript event:
$(window).resize(function() {
if($(window).width() <= 1200) {
//You code here
}else {
//You code here
}
});
Your code will be executed whenever the browser window's size is changed.
$(window).resize(function() {
if($(window).width() <= 1200) {
//small screen code
}else {
//large screen code }
});
//trigger window resize event on load
$(window).trigger('resize');
you can do it by checking the window width
var winWidth = $(window).width(); // you can get the window width from this
//Then check with the condtion(compare with your need ex :)
if(winWidth <= 600)
{
//your work here
alert("window resize less than or equal to 600");
}
else
{
//your work here
alert("window resize greater than to 600");
}

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');
}
}
}

Slide Toggle After Page Resize Bugging - jQuery

I have created a collapsible navigation which works fine on page load, but on the resizing of the window it seems to get trippy and slides up and down a number of times (can be just twice, or can go on for up to ten times).
(function ($) {
$.fn.myfunction = function () {
$(".navi-btn").hide();
$(".navigation").show();
};
})(jQuery);
(function ($) {
$.fn.mysecondfunction = function () {
$(".navi-btn").show();
$(".navigation").hide();
$(".navi-btn").click(function () {
$(".navigation").slideToggle();
});
$("li").click(function () {
$(".navigation").slideToggle();
});
$("#width").text("too small");
};
})(jQuery);
$(document).ready(function () {
var width = $(window).width();
if (width > 400) {
$('#width').myfunction();
} else {
$('#width').mysecondfunction();
}
$(window).resize(function () {
var width = $(window).width();
if (width > 400) {
$('#width').myfunction();
} else {
$('#width').mysecondfunction();
}
});
});
Here is a "working" demo jsfiddle
I have written the script myself, so I am sure there is an easy fix, I just don't seem to know what I have done.
I was thinking perhaps after a resize, would reloading the function be a good workaround, and if so how can this effect be achieved?
You are adding the click event while resizing the window. This will bind the same function multiple times to the click event. So the best option would be to bind the event only once which could be done on ready event. In this link I limited this binding in resize event itself by adding a class to the navi-btn and checking that.
$(".navi-btn").not(".binded").addClass("binded").click(function () {
$(".navigation").slideToggle();
});
Hope this gives you an idea.
Thanks,
Jothi
I had a quick test and found that removing the resive condition and putting it into it's own function seemd to fix the issue
From
$(document).ready(function () {
var width = $(window).width();
if (width > 400) {
$('#width').myfunction();
} else {
$('#width').mysecondfunction();
}
$(window).resize(function () {
var width = $(window).width();
if (width > 400) {
$('#width').myfunction();
} else {
$('#width').mysecondfunction();
}
});
});
to
$(document).ready(function () {
var width = $(window).width();
if (width > 400) {
$('#width').myfunction();
} else {
$('#width').mysecondfunction();
}
});
$(window).resize(function () {
var width = $(window).width();
if (width > 400) {
$('#width').myfunction();
} else {
$('#width').mysecondfunction();
}
});

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