What is the best way to eliminate a function that has been applied to a clicked element when I click outside of it?

I am working on a function that enables horizontal scrolling with the mousewheel for a selected div.

My goal is to apply this function to the element when clicked, and then remove it when clicking outside of it. I have been successful in adding the functionality, but I am struggling to figure out how to properly remove the function when clicked outside of the div (even if the mouse is still within the div).

Here is the jQuery code I have so far:

$mainDiv.on('click', function() {

    $(this).find($scrollableContainer).horizontal();

});

This is the function responsible for enabling horizontal scroll (using a mousewheel plugin):

$.fn.horizontal = function() {  

    $(this).mousewheel(function(e, delta) {
        this.scrollLeft -= (delta * 40);
        e.preventDefault();
    });

};

In essence, what I want to achieve is this: when a user clicks on $mainDiv, add the horizontal() function to $scrollableContainer. Then, if the user clicks outside of $mainDiv, remove the horizontal() function from $scrollableContainer. I attempted using a click event on the body, but it did not work as expected:

$('body').on('click', function() {
    $(this).find($scrollableContainer).off();
});

Any assistance would be greatly appreciated!

Answer №1

To begin, make adjustments to the plugin

$.fn.horizontal = function(customFunction) {  

    this[customFunction]('mousewheel', specialFunction);

    function specialFunction(event, change) {
        this.scrollLeft -= (change * 40);
        event.preventDefault();
    }

};

Next, enable the changes

$mainDiv.on('click', function() {

    $(this).find($scrollableContainer).horizontal('on');

});

And disable them when necessary

$(document).on('click', function() {
    $(this).find($scrollableContainer).horizontal('off');
});

Using a variable in find may seem odd unless that variable holds a selector as a string?

Note that there is no second argument named delta, and the mousewheel event is considered non-standard according to MDN. Are you incorporating another plugin for this non-standard functionality?

In Chrome and IE, there are properties like deltaX and deltaY on the event object that can be utilized:

function specialFunction(event) {
    event.preventDefault();

    var change = event.originalEvent.deltaX;
    this.scrollLeft -= (change * 40);
}

Additionally, MDN offers a polyfill for cross-browser compatibility.

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 unexpected token "[ ]" was encountered while assigning a numerical value to an array

Hey everyone, I have a question that's been bothering me and I can't seem to find the answer anywhere. I'm currently learning pure JavaScript and although I am familiar with several other programming languages, I keep running into an issue ...

Creating personalized buttons with Bootstrap

I'm looking to create custom buttons using Bootstrap. The "Get Quote" button should have a magnifying glass symbol on its left, and the "Clear" button should have a symbol on its left as well, like shown in the image below. Additionally, I want to cha ...

Tips on accessing values within the parentheses while calling a function in Android (View view)

String messageToSpeak=null; public void displayMessage(View view){ //String messageToSpeak = write.getText().toString(); Toast.makeText(getApplicationContext(), messageToSpeak, Toast.LENGTH_SHORT).show(); speech.speak(message ...

What is the reason for the jQuery plugin not being applied after replacing the page content with an Ajax response?

At the moment, I am utilizing jQuery ajax to dynamically add content to my website. Additionally, I have incorporated the jquery.selectbox-0.6.1.js plugin to enhance the style of select boxes on the page. The plugin successfully styles the select boxes up ...

Iterate over the div elements that have a class of X to discover any potential connections with the div elements

I've been working on a script that aims to accomplish the following: Iterate through each .display-player-box element and assign its id to a variable. Loop through the .removefromsquad elements to find one whose class attribute corresponds with the ...

Guide to placing a basic div directly over a basic html table td

I need to create a simple html table with labels in one column and content in another. What I want to achieve is placing a div over the content td while keeping the label visible. I am looking for the most efficient way to do this, possibly making the seco ...

Guide to making a sidebar navigation menu on the left using Bootstrap

How can I create a left navbar using Bootstrap? I managed to do it. <nav class="btn-group-vertical float-left navbar"> <button routerLink="product/home" routerLinkActive="is-active" class="btn btn-outline-dark">Home</button> ...

Switch between classes smoothly with animation

Is there a way to achieve this effect without using jQuery UI? I want something faster and more lightweight, as I prefer not to add another 20-90 kb to my site: $('#fo').toggleClass('tra', 'slow'); ...

IE browser issue with includes() method

The code snippet I have been using works flawlessly in browsers like Chrome, Firefox, and Edge. However, upon testing it in IE11, I noticed that it does not work as expected and breaks some functionality. var href = jQuery(this).attr('href'); if ...

Create a graph with Javascript

I successfully created a chart using JavaScript with hardcoded data in the code snippet below. However, I am facing an issue with integrating this code to work with AJAX data instead of hardcoded data. Code: window.onload = function () { var c ...

Difficulty encountered with document.querySelectorAll retrieving paginated elements

I am currently developing a project called STEEP. Our implementation involves utilizing infinite scroll to load 8 videos at a time as the user scrolls through the page. However, we are facing an issue with the script responsible for handling video playbac ...

Adjust the width of the dropdown menu for the v-combobox

I am currently working on creating a multiple search filter similar to the one found in Gitlab dashboard. https://i.sstatic.net/YHivl.png For this task, I am utilizing Vuetify's v-combobox like this : <v-combobox id="mycombo&quo ...

Troubleshooting jQuery attribute errors

Can someone help me troubleshoot this code? I'm not sure if the issue lies with the .get method not working with the .removeAttr method. Thank you! var current = 0; $("div#choice")[current].removeAttr("style"); ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

The div element is finally loading properly after multiple clicks

I need some assistance with loading dynamic divs in Angular. I have created a button that adds new divs each time it is clicked in a specific area. However, once these new divs are added, they appear incorrectly: https://i.sstatic.net/sAE6q.png After add ...

Why is DataTable only displaying data in JSON format?

I am facing an issue with displaying the data in a DataTable instead of JSON format. Could someone help me identify why it is returning that format and how to fix it? Below is a screenshot of the current result: https://i.sstatic.net/7MjN2.png //GET:Data ...

Just starting out with Jquery and encountering issues - it won't load or function on any browsers

After diving into the world of jQuery, I decided to create a basic webpage using Google's hosted jQuery. Despite following advice from various sources like Stack Overflow, my code doesn't seem to be working as expected. The change event isn' ...

JavaScript list in Google Docs

I am a beginner in the world of the Google Docs API and I am interested in retrieving a list of all documents that are not spreadsheets using the Google Docs API. I have found an API that allows me to access a specific document when I provide its documentI ...

Issues with the Bootstrap Grid System not functioning correctly when inter-component communication is needed in Angular from parent to

This is the code from app.component.html file: <div class="container"> <div class="row" id="ads"> <div class="col-xs-4"> <app-card *ngFor="let car of cars" [carNotifyBadge]="car.carNotifyBadge" [ca ...

Varied positioning for various elements within a singular table row

I would like my HTML table to have a specific layout and style. Here is a reference image of how I want it to look: Table The main requirement is for the content/phone number to be centered within each table row, with an edit icon positioned to the right ...