Turn off sticky sidebar feature for mobile-friendly layout

I have encountered an issue with my script that I need assistance with. I am trying to disable this script for responsive or mobile view, but despite trying various methods, it is not functioning as expected.

<script type="text/javascript">
$(function(){ // document ready
    if ($('#sidebar').length) { // ensure existence of "#sticky" element
        var el = $('#sidebar');
        var stickyTop = $('#sidebar').offset().top; // returns a number
        var stickyHeight = $('#sidebar').height();

        $(window).scroll(function(){ // scroll event
            var limit = $('#img1').offset().top - stickyHeight - 15;

            var windowTop = $(window).scrollTop(); // returns a number

            if (stickyTop < windowTop){
                el.css({ position: 'fixed', top: 0 });
            }
            else {
                el.css('position','static');
            }

            if (limit < windowTop) {
                var diff = limit - windowTop;
                el.css({top: diff});
            }
        });
    }
});
</script>

Answer №1

To obtain the dimensions of the viewport using jQuery:

var viewWidth = $(window).width();
var viewHeight = $(window).height();

In this scenario:

 if($(window).width()>=768){
//Insert your script code here, which will only be executed if the viewport width is 768 or greater (adjust value as needed)
}

Answer №2

Consider utilizing modernizr for this purpose as it offers a wide array of feature detection techniques, particularly for touch devices such as mobiles.

To start, include modernizr like so:

https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js

Then, integrate your function/javascript code within modernizr, such as:

if(!Modernizr.touch){ 

    $(function(){ // document ready
        if ($('#sidebar').length) { // ensure "#sticky" element exists
        var el = $('#sidebar');
        var stickyTop = $('#sidebar').offset().top; // returns number
        var stickyHeight = $('#sidebar').height();

        $(window).scroll(function(){ // scroll event
        var limit = $('#img1').offset().top - stickyHeight - 15;

        var windowTop = $(window).scrollTop(); // returns number

        if (stickyTop < windowTop){
            el.css({ position: 'fixed', top: 0 });
        }
        else {
            el.css('position','static');
        }

        if (limit < windowTop) {
            var diff = limit - windowTop;
            el.css({top: diff});
        }
    });
   }
});        

}

This setup will be activated in the absence of a touch device.

Answer №3

<script type="text/javascript">
$(function(){ // Ensuring the document is ready

 // Detecting device width using screen.width and executing code for devices greater than 767 pixels (such as iPad) or based on specific requirements

if ($('#sidebar').length && screen.width > 767 ) { // Checking if "#sticky" element exists
    var el = $('#sidebar');
    var stickyTop = $('#sidebar').offset().top; // Getting the top offset value
    var stickyHeight = $('#sidebar').height();

    $(window).scroll(function(){ // Handling scroll event
        var limit = $('#img1').offset().top - stickyHeight - 15;

        var windowTop = $(window).scrollTop(); // Storing the current scroll position

        if (stickyTop < windowTop){
            el.css({ position: 'fixed', top: 0 });
        }
        else {
            el.css('position','static');
        }

        if (limit < windowTop) {
            var diff = limit - windowTop;
            el.css({top: diff});
        }
    });
}
});
</script>

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

Is it possible to store an HTML element tag in a variable?

I've been learning JavaScript on w3schools and freecodecamp, but I stumbled upon something in w3schools that has me puzzled. Can someone please explain why this particular code snippet works? The variable "text" is declared as containing the string " ...

Angular directive does not focus on the text box

I've been working on creating text boxes using a directive and I want only the first text box to be in focus. To achieve this, I am utilizing another directive for focus control. Below is my script: <script> angular.module('MyApp',[]) ...

What is the best method for globally configuring the Angular moment timezone?

I integrated angular moment js into my angular application. I am looking to display the date and time based on the time zone of the user accessing the app. However, I am facing difficulty in applying the time zone globally throughout my application. https ...

I am having trouble getting my dropdown to line up with the drop button labeled "MORE"

Despite trying multiple approaches, I am still struggling to align the dropdown content with the dropbtn. My goal is to have the content consistently positioned below the more menu. HTML: ` <html> <meta name="viewport" content="width=device-widt ...

Tips for creating CSS rules specifically for the default Android Browser using @media queries

Is there a CSS rule that can be applied only to the default Android Browser using @media queries? This rule should not affect Chrome, but only the default browser on Android devices. It's worth noting that there are numerous Android devices with vary ...

When fetching data from a parse object, JavaScript displayed [object, Object] as the result

When trying to access information from my parse data, I am able to display user table data on my document without any issues. However, when I attempt to query another object and insert it into an id element using jQuery with functions like text();, html(); ...

Implementing conditional statements in Puppeteer web scraping

Attempting to extract data from a table... Each country name is wrapped in an <a> tag, however some are not. Unfortunately, when the structure of the HTML changes, the program crashes Code => https://i.sstatic.net/zW3Cd.png Output => https: ...

Conditional text-boxes can be added to table columns based on certain conditions

I am working with a table that has three columns: type, 1st type, and 2nd type. The type column contains a button which toggles between two values, Db and Cr. I need to dynamically add a text box to the 1st type column when the button's value is Db, a ...

Guide on activating javascript code for form validation using php

How can I activate JavaScript code for form validation? I am currently implementing form validation on a combined login/register form where the login form is initially displayed and the register form becomes visible when a user clicks a button, triggering ...

Navigate through a nested JSON structure and update the data points

In my possession is a JSON tree structured as follows: { "projects": { "Proj1": { "milestones": { "default": "20150101", "default2": "20140406", "default3": "20140101", ...

Inject a value sent from response.render directly into the script tag

Below you will find a pug snippet. I am looking for a way to dynamically insert the user value into the chatConfig object. script. var chatConfig = { user : 'foo', pass : 'bar', } When rendering from my Express applicatio ...

Introduce a pause interval between successive ajax get calls

I've created a script that uses an ajax GET request when the user reaches near the end of the page. $(function(){ window.addEventListener('scroll', fetchImages); window.addEventListener('scroll', fetchNotifications); }); ...

Error message "The function is not defined" is commonly encountered in node.js programming

I'm having trouble with this section of my code. The error message I receive is: ReferenceError: callback is not defined at C:\js\kweb-hw\routes\board.js:14:13 var express = require('express'); var router = express. ...

Every time I attempt to execute mupx deploy, an error message appears

issue in console shubhabrata@shubhabrata-VirtualBox:~/Meteor/myapp$ mupx deploy Meteor Up: Advancing Meteor Deployments for Production Configuration file : mup.json Settings file : settings.json “ Discover Kadira! A powerful tool to monitor yo ...

Utilizing jQuery, setInterval, and making asynchronous Ajax requests

I am currently utilizing the craftyslide jquery plugin for creating engaging slideshows on my website. You can find more information about the plugin here. My website employs ajax to load its content, and specifically on the /#home page, there are two slid ...

Expand the display on mobile devices

What is the solution for adjusting a table on mobile view? I am aiming to achieve: https://i.sstatic.net/YkKAW.png However, it currently looks like this: https://i.sstatic.net/GW5mX.png Here are my code snippets: <script src="https://cdnjs. ...

Is there a way to incorporate a responsive side menu using JQuery or CSS3 that can shift the entire page layout?

Hey there, I'm currently trying to incorporate a responsive side menu into my website using either JQuery or CSS3. What I need is a side menu that will smoothly shift the page content when a link is clicked, and also adds a close button (X) to the men ...

Starting the download of the canvas featuring a stylish border design

I'm facing an issue where the canvas border is not showing up when I download the canvas with a border. The border appears on the screen, but it doesn't get included in the downloaded canvas. let canvas=qrRef.current.querySelector("canvas&qu ...

Accessing the data from an HTML5 slider using JQuery

Having some difficulty fetching a value from an HTML5 slider using JQuery. Here is my code snippet: JQuery Code: // Getting the value from slider one $("#submit").on("click", function(evt) { var sliderValue = $('#slider01').attr('value ...

"Exploring the Best Locations to Incorporate Plugins in VueJS Webpack

I am trying to incorporate Webpack provided Plugins in order to utilize JQuery globally. Some resources suggest You should add it in the webpack.config.js file under plugins:[] section. However, upon examining my webpack.config.js, I noticed that there ...