Deactivate event handling for viewport widths below a specified threshold

Currently, I am attempting to deactivate a script when the width of the window falls below 700px. Despite reviewing suggestions from various sources, I have not been successful so far.

window.onresize = function () {
    if(window.innerWidth < 700) {
        $(window).bind('scroll', function() {
            if ($(window).scrollTop() > 100) {
                $('#projectinfo').hide();
            } else {
                $('#projectinfo').show();
            }
        });
    }
}

Answer №1

One issue arises from the fact that you forget to unbind the event handler once it's added to the window. It's important not to bind the scroll event handler every time the window.resize event occurs because this can significantly impact performance. Additionally, continuously rebinding an existing handler is not good practice, even if it seems to work.

A better approach would be to determine during document.ready whether to attach the scroll handler or not. If the resize scenario is critical (although users rarely resize their browser windows during a single page view - it's mostly a test for responsiveness), check if the scroll handler is already attached to the window, and only add it if it's not there and (&&) window.innerWidth >= 700. Conversely, if the scroll handler exists, unbind it when window.innerWidth < 700.

http://api.jquery.com/unbind/

Remember, you can assign names to events when binding using the event.name syntax. Check out jQuery documentation for more information:

Using Namespaces

Instead of tracking handlers for unbinding, we can namespace events to target specific actions. By adding a period (.) while binding a handler, we create namespaces:

$("#foo").bind("click.myEvents", handler ); 

To unbind such handlers normally:

$("#foo").unbind("click"); 

To be more precise with unbinding:

$("#foo").unbind("click.myEvent"); 

We can also remove all handlers within a namespace, regardless of event type:

$("#foo").unbind(".myEvent"); 

Attaching namespaces to event bindings is particularly beneficial when working on plugins or code that may interact with other event-handling processes in the future.

Answer №2

detach and attach maybe?

var $w = $(window);

function scrollHandler(e) {
  $('#projectinfo').toggle($w.scrollTop() > 100);
}

$(window).resize(function (e) {
  $w.width() < 700 ? $w.bind('scroll', scrollHandler) : $w.unbind('scroll', scrollHandler);
});

This code could use some fine-tuning for better performance, but it serves as a basic illustration.

Answer №3

Avoid using bind as it is deprecated. Instead, utilize on (and off). Additional recommendations can be found in the comments below.

(function ($, w, d) {
    $(function () {
        var $projectinfo = $('#projectinfo');
        var $w = $(w);
        var useScroll;

        function useScroll() {
            if ($w.scrollTop() > 100) {
                // Opt for adding or removing a class instead of using hide() and show()
                $projectinfo.addClass('hidden');
            } else {
                $projectinfo.removeClass('hidden');
            }
        });

        function checkWindowWidth() {
            var useScrollTop = $w.width() < 700;
            if (useScrollTop) { 
                $w.on('scroll', useScroll);
            } else {
                $w.off('scroll', useScroll);
            }
        };

        // Upon resize, only assess the viewport width once
        $w.on('resize', function () {
            // Consider using a 'debounce' function for this
            checkWindowWidth();
        });


    })
})(jQuery, window, document);

For further information on debounce functions, visit: debounce, bind vs on

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

The ID update functionality in Node.js is malfunctioning

Hello everyone, I am currently venturing into the world of NodeJS with a goal to create a backend API for a car rental agency. After writing some code to update, view, and delete records by id stored in MongoDB, I encountered a strange issue where it only ...

Troubleshooting Yeoman and Angular: Routing troubles persist

I recently started exploring with yeoman to develop angular applications. I am facing an issue while trying to create routes using yo:angular route. After running the command: yo:angular route foo yeoman generates the following files: app/scripts/contr ...

Issues with accessing identical SESSION variables across multiple files

I'm currently working on a website using Wordpress. My permalink structure is configured to display the post/page name. Therefore, when accessing a page named store, the URL appears as: www.mysite.com/store/?some=arguments In all my Wordpress templa ...

Looking for assistance with JQuery and JavaScript?

I oversee a team of employees, each with a 7-day work schedule. To streamline the process, I have developed a PHP form that I would like to use to collect data for verification in JavaScript before submitting it to an SQL database using AJAX. My main cha ...

Meteor chat platform now offers the option to create multiple chat rooms

I've been working on an application that features multiple chat rooms. Currently, one of the rooms is functional in terms of sending and receiving messages. However, when I navigate to a different room and try to send a message, the message doesn&apos ...

Create a one-of-a-kind SVG design with a customized blur effect in

Recently, I've been experimenting with SVG effects and animations and stumbled upon a fantastic example of how to apply a blur effect to an SVG path. However, I'm struggling to figure out how to set a different color instead of the default black ...

Using "array_agg" in a "having clause" with Sequelize

I am facing a particular scenario with my database setup. I have three tables named computers, flags, and computerFlags that establish relationships between them. The structure of the computerFlags table is as follows: computerName | flagId computer1 | ...

Issue regarding the carousel functioning on Bootstrap version 4.5.0

I am currently facing an issue with the carousel in the latest version of Bootstrap (4.5). I have set up a multiple item carousel by creating a grid inside it, where each item looks like this: <div class="carousel-item active"> < ...

What steps can be taken to enable automatic playback for this slider?

After downloading the slider from this site, I've been attempting to enable autoplay on this slider but have not had any success. Can anyone provide guidance on how I can achieve this? I've tried modifying the code below without achieving the des ...

Enigmatic blank space found lurking beneath the image tag

Recently, I made a change to the header image on my website. Previously, it was set using <div style="background-image... width=1980 height=350> and now I switched to <img src="... style="width:100%;"> This adjustment successfully scaled do ...

Browsing through items within arrays to evaluate their values

I am facing an issue with two arrays that consist of objects. The first array contains restaurant objects with attributes such as name and averagePrice, while the second array has price objects (cheap, medium, expensive) with properties like label, lowEnd, ...

Images with scratches visible in Chrome

This puzzle may seem easy to some, but it's been quite challenging for me. I've encountered a discrepancy in how Firefox and Chrome render images (specifically technical drawings). Despite my attempts to use image-rendering: -webkit-optimize-cont ...

The script fails to start using npm start, however, it runs smoothly when using node server.js

For a while now, I've been facing an issue that I just can't seem to resolve. When I navigate to my project's src folder and execute `node server.js`, everything functions as expected. I can access the application at http://localhost:3000/cl ...

Enhance Your Search Bar with Ajax and JQuery for Dynamic Content Updates

My goal is to create a search bar that dynamically loads content, but I want the actual loading of content to start only after the user has finished typing. I attempted a version of this, but it doesn't work because it doesn't take into account ...

Exploring the concept of utilizing named arguments within Express.js routing

I've searched extensively, but can't seem to find any information on this topic. My goal is to create requests like the following: url/list/message=hello?id=1234 Despite my efforts, I have not come across any resources on how to achieve this us ...

Tips for controlling a "collapsed" state for every intricately nested node within a tree

My data structure is complex and dynamic, illustrated here: const tree = [ { name: "Root Node", collapsed: true, nodes: [ { name: "Node 1", collapsed: true, nodes: [ { name: "Sub node" ...

Navigating and extracting nested JSON properties using JavaScript (React)

I am currently working with a nested JSON file that is being fetched through an API. The structure of the JSON file looks something like this: { "trees":{ "name":"a", "age":"9", "h ...

How can I customize the hover effect of the drop-down options <option> to have a "blue" background color?

I've been struggling to change the default blue background color of the drop-down options when hovering over them with the mouse. Despite trying various solutions from this forum, nothing seems to be working at the moment. (These solutions used to wor ...

Filter Observable based on object array property

I am trying to filter an Observable and only keep the stream that has a specific property value in an array of objects inside it. For example, consider this Observable: const observable = of({name: 'agency', year: '2010', job: [ ...

The entered value in the <input> field is not valid

I am encountering an issue where the input value is auto-filled, but when I click the submit button, the input field value is not recognized unless I modify something in it, such as deleting and adding the last word to the first name. Is there a way to m ...