Merge two JavaScript functions

I've been attempting to merge two if functions together but I keep encountering errors. Despite trying different methods, I have not been successful in combining them.

My goal is to check if the body has a specific class and if it does, I want to uncheck a checkbox.

The two functions I tried to combine are:

if (document.body.classList.contains('thatClass')) {
    // do some stuff
}

$(function() {
  $(document).on("click", function(e) {
    if ($(e.target).is(".main-nav-slideout") === false) {
      $("#main-nav-toggle").prop("checked", false);
    }
  });
});

This is my attempt at combining the snippets:

$(function() {
  $(document).on("click", function(e) {
      if (document.body.classList.contains('thatClass') && $(e.target).is('.main-nav-slideout') === false) {
      $('#main-nav-toggle').prop('checked', false);
    }
  });
});

Answer №1

You have the option to condense it by simply invoking the function as needed.

$(function() {
  toggleCheckbox()
  $(document).on("click", '.nav-trigger', toggleCheckbox)
});

function toggleCheckbox() {
  $("#nav-toggle").prop("checked", $('body').hasClass('active'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class='active'>
<input type='checkbox' id='nav-toggle' />
<div class='nav-trigger'>Toggle me</div>
</body>

Answer №2

Give this a shot:

$(function() {
  $(document).on("click", function(e) {
      if (document.body.getAttribute('class').split(' ').indexOf('thatClass')>-1 && ($(e.target).is(".main-nav-slideout") === false) {
      $("#main-nav-toggle").prop("checked", false);
    }
  });
});

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

Issues with npm installation not capturing all required dependencies

After running npm install to install all dependencies, I encountered an issue where the dependencies were not being installed in my current project. The following message was displayed: https://i.sstatic.net/RafcR.png I then attempted to audit the projec ...

Fulfill the promise to retrieve the value contained within

Is there a way to use TypeScript to call the Wikipedia API for retrieving a random page title and save it in a variable for later use? I am struggling with resolving promises as I keep getting ZoneAwarePromise returned. I'm new to both promises and Ty ...

A comprehensive guide on how to find keywords within an array and then proceed to make all text within the parent div tag stand

I am currently looking for a webpage that displays a list of products based on keywords from an array. Once it detects any word in the array, it highlights it with a red background - everything is working smoothly so far. However, I now wish for the script ...

Identify the changed field using Javascript

In my MVC application, I have a form with multiple fields that I am monitoring for changes using JavaScript. The code snippet below keeps track of any changes made in the form: var _changesMade = false; // Flag the model as changed when any other fie ...

Remove the 'name' attribute from the input tag within the URL

Is there a way to make the server update the URL format to localhost:3000/userinput instead of localhost:3000/?name=userinput when submitting a name? Any suggestions would be greatly appreciated. Thank you in advance. ExpressJs FILE <!DOCTYPE html> ...

Undefined boolean when passing to AngularJS directive

I developed a custom directive that allows for the addition of a gradient background color in AngularJS: .directive('colouredTile', function () { return { restrict: 'A', controller: 'ColouredTileController&apos ...

Exploring Array Iteration: Navigating through Arrays with the .map Method in React and Vue

I am currently using Vue after coming from a React background. In React, there is a method called .map that allows you to render a component multiple times based on the number of items in an array and extract data from each index. Here's an example: f ...

Unable to modify page property status through the Notion API

I've been attempting to use the Notion JS-sdk to update a page's status using their API. However, I've run into some issues that I can't seem to resolve. Updating the status requires modifying the properties object, but no matter what ...

The function being called within useEffect is rendering too quickly, causing it to break. However, it functions correctly after

When using React-id-swiper to load images for products, I encountered an issue with setting the useState 'loading' state to false after all images have been successfully loaded. In this case, there are 5 products. To achieve this, I implemented ...

What are some effective replacements for SoundManager2 worth considering?

While Soundmanager2 is a useful app, many find the code to be overly complex and difficult to navigate. It almost seems as if it was purposely written in a way to confuse rather than clarify. Are there any recommended alternatives to Soundmanager2 that are ...

Although responseText functions properly, responseXML remains constantly null

I've searched through all available answers here and still can't find a solution. I'm confident that I haven't overlooked anything obvious. My issue involves loading map markers based on latitude and longitude coordinates. The problem ...

I am looking to create a PHP script that restricts access to individuals under the age of 18 based on the current

I'm looking for a way to use Php, javascript, or ajax to restrict access for individuals under 18 years old based on the current date. Any suggestions on how I can achieve this? Could someone please review my code for calculating age onblur or onSubm ...

When a radio button is chosen, multiple text fields must be completed in order to validate the form

I am working with a set of 3 radio buttons. If the last option, labeled "In Home," is chosen, then all 4 of the text fields must be filled in for the form to validate. While I have found information on how to achieve this with checkboxes or a single text f ...

What could be the reason for req.route displaying the previous route instead of

Question: const router = express.Router(); router .route('/:id') .delete( validate(messageValidator.deleteById), MessageController.deleteById, ) .get( validate(messageValidator.getById), MessageController.getById, ); ...

Aggregating MongoDB: Calculating unique values within an array

Looking to find the distinct tags count on all records within a mongodb query, utilizing JS. Data structure of the record: { "_id": { "$oid": "62e593aed8fd9808777225e8" }, "title": "“The world as ...

Display the number of items that have been filtered as soon as the Mixitup page loads

Currently, I am utilizing MixItUp 3 for sorting and filtering items, with the goal of displaying the count of items within each filter category upon the initial page load. Despite attempting a solution found on SO (mixitup counting visible items on initial ...

How can you reach a constant from a different component in React?

I am new to developing a react application and struggling with accessing const data from another component. The specific constant I need access to is located in the TableComponent.js file. TableComponent.js export default function({ infinite }) { const [ ...

Error: The "checkAvailability" method is not available in the model object

When attempting to implement some functionality methods for my model, I encountered an issue where sending a request resulted in the following traceback: /home/nano/Dev/JS/OMI/node_modules/mongoose/lib/utils.js:413 throw err; ^ TypeE ...

What is the purpose of the Express 4 namespace parameter?

Having worked extensively with Express 4, I recently attempted to implement a namespaced route with a parameter. This would involve routes like: /:username/shows /:username/shows/:showname/episodes I figured this scenario was ideal for express namespacin ...

Styling Challenges with CSS/AngularJS Accordion in Footer

I want to create a page layout as shown below: +---------------------------+ | Auto-fill / v scrollable ^| | || | || | v| +---------------------------+ | Fixed [][][] ...