javascript code to close slide div without hiding the setting icon upon clicking outside the div

Can you help me with an issue I am facing while implementing a slide div for creating theme color? The div works fine, but when I click outside of it, the div does not close. I have tried multiple solutions, but none seem to work. I have researched various internet resources, but I am still unsure of how to implement the fix. Here is the relevant code snippet:

function clickedThemebtn() {
  var ele = document.getElementsByClassName("theme-colors")[0];

  if (ele.classList.contains("shown")) {
    ele.classList.remove("shown");
  } else {
    ele.classList.add("shown");
  }
}

You can find my code on JSFiddle

Answer №1

Take a look at this JSFiddle link.
I've implemented a fixed positioned div to cover the entire screen and handle clicks outside of it.

Here's the HTML structure:

<div class='toggleclickoutside' onClick="handleOutsideClick()"></div>
<div id="toggleshown" class="theme-colors">...</div>

JavaScript function for handling outside clicks:

function handleOutsideClick() {
  var element = document.getElementsByClassName("theme-colors")[0];

  if (element.classList.contains("shown")) {
     element.classList.remove("shown");
  }
}

CSS for the new div:

.toggleclickoutside{
  position: fixed;
  width: 100vw;
  height: 100vh;
  top: 0px;
  left: 0px;
}

Answer №2

To ensure that the menu closes when clicking anywhere inside the menu, you can add an event listener to the document that triggers the close event. It's important to note that additional checks may be needed to prevent unintended behavior.

function handleMenuClick(e) {

    var menu = document.getElementsByClassName("menu")[0];
    
    if (e.target.id === "menuButton") {
        if (menu.classList.contains("visible")) {
            menu.classList.remove("visible");
        } else {
            menu.classList.add("visible");
        }
        return;
    }
    
    menu.classList.remove("visible");    
}

document.addEventListener('click', handleMenuClick);

Check out the updated fiddle

If you prefer a jQuery solution, here's a link to a relevant fiddle: jQuery fiddle

Answer №3

To ensure the theme selector closes when it is clicked outside of, you need to listen for the click event on the document object and verify if the click occurred within the theme selector before hiding it.

document.addEventListener('click', handleDocumentClick);

function handleDocumentClick(event) {
  const themeSelector = getThemeSelector();
  if (!themeSelector.contains(event.target)) {
    hideThemeSelector();
  }
}

function getThemeSelector() {
  return document.getElementsByClassName("theme-colors")[0];
}

function hideThemeSelector() {
  const themeSelector = getThemeSelector();
  themeSelector.classList.remove("shown");
}

function showThemeSelector() {
  const themeSelector = getThemeSelector();
  themeSelector.classList.add("shown");
}

Additional functions have been included for ease of use.

The updated fiddle can be viewed here: https://jsfiddle.net/0nqzpyko/

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

Matching names with corresponding IDs from multiple arrays in React

In my React app, I am dealing with an array structure. There is one array that contains the ids of two other arrays, along with their respective names. The goal is to create a new array that combines all the necessary information. Here is a simplified vers ...

Object is not compliant with HTMLInputElement interface and cannot execute 'stepUp'

Currently, I am facing an issue with passing the selected value from a dropdown list of countries to a PHP file using AJAX. The goal is to take this value and then transfer it to another input field identified by the ID #tele. Here is the gist of my code: ...

Disruption of HTML file content

When I open my HTML file directly, the entire content appears messed up. However, when I view it through live preview in Brackets, everything looks fine. What could be causing this issue? Keep in mind that I am using CSS and JavaScript files from Bootstr ...

jQuery Mobile offers a feature that allows users to create collapsible elements

I recently ran a coding validation check at and encountered the following errors: <div data-role="collapsible-set" id="col"> <div data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" class="ui-nodisc-icon"> ...

Implementing Multiple Identification using JavaScript and PHP

I need to complete a simple task. Here is the code snippet: echo' <div class="col-sm-12" id="recensioni_titolo"> <form role="form" id="review-form" method="post" action="php\insert_comment.php"> ...

Beneath the footer lies a blank space in white

Visit our site for information on various towns. However, we are facing an issue with the CSS when it comes to new or less populated towns like this one, where the footer is not aligning properly and leaving a large white gap below. We attempted to implem ...

Replace the checkbox display heading with a text box in the designated area

I'm new to using kendo ui Currently, I am attempting to show a text box in the first column header. Instead of the checkboxDisplay heading, I want to replace it with a text box. Could someone please provide guidance on how to resolve this issue? Here ...

Integrate the dForm plugin with a convenient time picker widget

Currently, I am attempting to integrate a time picker widget into a jQuery plugin called dForm. The specific timepicker widget can be found at the following link: https://github.com/jonthornton/jquery-timepicker Despite reviewing the dForm documentation, ...

Two selection options controlling filters. The first choice influences the data shown in the second filter

I've been struggling for hours to figure out how to build this functionality. My code seems to be getting close, but I'm having trouble passing my selection from the HTML back to the controller. Here's my Angular code: var Categories = Pa ...

Sort through JSON information to establish a filter that relies on the job's location

I am currently working on developing a project and I need to create a filter. My goal is to analyze the JSON data received from the backend API, filter out job posts based on their "location" attribute, and then display the filtered results. useEffect( ...

The JQuery function assigning a value of 0 to the selectedIndex property is not functioning properly across all selected fields

<select name="wpcf-others" id="abc" class="myzebra-control myzebra-select"> <option value="wpcf-field123">General Work Jobs</option> <option value="wpcf-fields--1">Journalist/Editors Jobs</option> <option value="wpcf-4868b8 ...

Generating a container DIV with loops and ng-class in AngularJS

Currently, I am working on developing a dynamic timeline using AngularJS. To populate my timeline, I have successfully configured the data fetching from a JSON file. You can see what I have accomplished so far on PLNKR: http://plnkr.co/edit/avRkVJNJMs4Ig5m ...

How to position the navigation bar to the right using bootstrap

I have been experimenting with moving the navigation bar to the right side of the screen in bootstrap4 by using float: right; on the nav a element, but it doesn't seem to be having any effect. I am developing my project using a codepen app. Here is t ...

Error: Jasmine cannot access a property of undefined value

Just getting started with js and jasmine Attempting to create a jasmine test case for my method. Encountering an error: TypeError: Cannot read property '0' of undefined. Tried different ways of passing arrays into my method sports but still facin ...

What is the solution for fixing the error "Uncaught SyntaxError: Cannot use import statement outside a module" while using Chart consoletvs/charts:7.* in Laravel 8?

I have successfully completed all the steps outlined in the documentation. When using CDN links, everything functions as expected and I am able to load any chart. <script src="https://unpkg.com/chart.js/dist/Chart.min.js"></script> &l ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

Solving the Cross-Origin Resource Sharing problem in AngularJS

While using the http dependency in AngularJS and setting headers for CORS, I am encountering an error. Please check the console.log for more information on the error. The error message reads: "XMLHttpRequest cannot load . Response to preflight request doe ...

Bootstrap: the rows are breaching the boundaries of their parent containers, causing them to overlap with

I'm struggling to create a bootstrap layout similar to the one on Codepen. Everything looks good on the codepen demo: Codepen_bootstrap ...but when I try to view the page locally in my browser (Chrome and Safari), the design becomes distorted and el ...

What is the proper method for utilizing the "oneOf" keyword in this schema?

Is it possible to have either option A or B, but not both (mutually exclusive)? In Draft 3, I am required to use whatever is available, even though the version on top says 4. This is because when using an array for "required", it throws an error stating t ...

Combining multiple objects in an array to create a single object with the aggregated sum value can be achieved using JavaScript

I am working with an array that contains numbers of array objects, and I need to merge these arrays into a single array with unique values for content and the sum of values for total as shown in the desired result below. Any assistance would be greatly app ...