Learn the steps to Toggle Javascript on window resize

Is there a way to toggle Javascript on and off when the window is resized? Currently, resizing the window causes the navigation bar to stick and remain visible above 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>

Answer №1

To respond to changes in the size of the browser window, you can attach an event handler to the "resize" JavaScript event:

$(window).resize(function() {

    if($(window).width() <= 1200) {
        //Add your code here
    } else {
        //Add your code here
    }

});

This code will run every time the browser window is resized.

Answer №2

    $(window).resize(function() {        
        if($(window).width() <= 1200) {
            //code for smaller screens
        }else {
            //code for larger screens
        }
    });

   //trigger window resize event upon loading
   $(window).trigger('resize');

Answer №3

To determine the window width, you can use the following code snippet:

var winWidth = $(window).width(); // this will fetch the window width

// Next, you can set up a conditional statement to compare with your desired value



  if(winWidth <= 600)
   {
     // Add your code here
     alert("Window resized to 600 or less");
   }
   else
   {
     // Add your code here
     alert("Window resized to greater than 600");
   }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to achieve this smooth scrolling animation on the page?

While browsing the website , I noticed a unique page scrolling effect that caught my eye. Unsure if they were using default bootstrap code or their own custom code, I was intrigued by how it worked. I attempted to find similar effects online but struggled ...

What is the process for configuring socket.io to solely listen on a single designated route?

Is there a way to make socket.io listen only on my /home route, instead of every route? I tried changing the configuration but it only displayed a JSON file on the home path. const server = require('http').Server(app); const io = require('s ...

Display loading animation until Google Maps is fully loaded - Utilizing AngularJs

Is there a way to check the readiness of Google Maps before displaying it? I'd like to show a preloader block while the Google Maps is loading. Here is the factory code I am using: var map = false; var myLatlng = new google.maps.LatLng(48.6908333333 ...

Creating a function while utilizing this conditional statement

Seeking guidance as I work on defining an 'explode' function. This function is intended to take a string input and insert spaces around all letters except the first and last ones. For example, if we call the function with the string Kristopher, i ...

Is there a way to modify the window's location without having to reload it and without resorting to any sne

Initially, I believed that the hash hack was a necessity, but after observing the recent updates from Facebook, my perspective has shifted. The original hash hack (not certain if this is the correct term) involved changing location.hash to save a state in ...

Ways to display JSON in a structured format on an HTML page

Is there a way to display JSON in a formatted view on my html page? The JSON data is coming from a database and I want it to be displayed neatly like the following example: { "crews": [{ "items": [ { "year" : "2013", "boat" ...

Refresh a javascript file using the power of jquery

I have created a PHP file that displays a session meter in Joomla's frontend using JavaScript. Additionally, I have another PHP file that shows user details and reloads using jQuery. My goal is to make the JavaScript session meter also reload when the ...

Unable to delete touchmove event - Vue watching system

Preventing scrolling on mobile devices: const stopScroll = function(e) { e.preventDefault() } Adding the listener: document.body.addEventListener('touchmove', stopScroll, { passive: false }) Removing the listener: document.body.removeEvent ...

Can you explain the difference between serif and sans-serif fonts?

Can you explain the distinction between serif and sans-serif when it comes to the CSS font-family attribute? ...

Do we need to employ strict mode when utilizing specific ES6 functions in Node.js?

There has been a debate circulating at my workplace regarding whether or not it is necessary to include 'use strict' when using ES6 in Node.js without Babel. Some argue that certain ES6 methods may not function correctly without it, but I haven&a ...

JavaScript parsing error occurred

Encountering a parsing error in my JavaScript code when deploying Firebase functions. The error mentions an unexpected token, indicating there might be a character out of place. I've been stuck on this issue for weeks now. Any assistance would be grea ...

Python regular expression problem with matching regex

Hey there, I'm diving into my first question on stackoverflow and I've been struggling with it for hours. I'm sure the solution is right in front of me, but I just can't seem to find it. My goal is to extract information from a webpage ...

The component next/image is experiencing issues when used in conjunction with CSS

I struggled to create a border around an image because the custom CSS I wrote was being overridden by the Image component's CSS. Despite trying to leverage Tailwind and Bootstrap to solve the problem, my efforts were unsuccessful. Now, I am at a loss ...

How to update icon for fa-play using Javascript in HTML5

I recently added an autoplay audio feature to my website. I would like to implement the functionality to pause and play the music, while also toggling the icon to fa-play at the same time. This is the HTML code I am using: <script type="text/javascri ...

Themeing for dark mode using styled components in Next JS

I have been searching for an answer to this question, but haven't found one yet Currently, I am using styled components with next js along with the use-dark-mode hook to manage theme changes and detection The global styles switch seems to work fine ...

handle an exception within the initializer of its object

I'm currently working with an Ajax object that is utilized in various other objects to load 'Json' files. One issue I'm facing is trying to catch the 404 'Not found' exception thrown in the initializer object. However, every ...

Employing CSS selectors to target the subsequent element that is accessible

Here is the structure of my HTML: <input type = "checkbox" style = "display:none" id = "select"> <label for = "select" id = 'click'> click </label> <div class = 'next'> </div> I am trying to style t ...

RegEx not triggering Mongoose hooks

When performing queries on my mongo collections, I am attempting to call specific hooks for them. DispatchRequest.findOneAndUpdate({user_name:"umesh"},{email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdac8 ...

Transform ISO-8859-1 encoding into UTF-8

Recently, I encountered an issue while sending a HTTP request using jQuery's ajax. The server, unfortunately, returns the response in ISO-8859-1 format while my page is set to UTF-8. This discrepancy causes some characters to become unreadable. How ...

Symfony Form Validation through Ajax Request

Seeking a way to store form data with Symfony using an Ajax call to prevent browser refreshing. Additionally, I require the ability to retrieve and display field errors in response to the Ajax call without refreshing the page. I have a Symfony form setup ...