Hide collapsible menu in JQuery when clicking outside of it - blur effect

My JQuery function doesn't seem to be working as expected. Sometimes when I click on the elements, nothing happens and it triggers a function that hides the collapsible menu if clicking anywhere on the document instead of redirecting to the correct href's. Are there better methods to achieve this?

HTML

    <div>
      <button id="bottone" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav " aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#home">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#about_me">About Me</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#portfolio">Portfolio</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#services">Services</a>
      </li>
            <li class="nav-item">
        <a class="nav-link" href="contacts.php">Contacts</a>
      </li>
    </ul>
    </div>
  </div>

JQuery

$(document).ready(function () {

      $("#bottone").blur(function (event) {
        var screenWidth = window.innerWidth;
        if (screenWidth < 768) {
          $("#navbarNav").collapse('hide');
        }
      });
});

Answer №1

What is the purpose of using button blur? Instead, you can achieve the same effect by using

$(document).on("click",function(e){ ... })

This method will toggle the menu showing and also allow redirection when clicking on a link without an anchor.

Check out the snippet below:

$(document).ready(function() {
 
 $(document).on("click",function(e){
    var screenWidth = window.innerWidth;
    if (screenWidth < 768) {
      $("#navbarNav").collapse('hide');
    }
 });

});
.navbar-toggler-icon {
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(0,0,0, 0.7)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E") !important;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>


<div>
  <button id="bottone" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav " aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#home">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#about_me">About Me</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#portfolio">Portfolio</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#services">Services</a>
      </li>
      <li class="nav-item">
        <a class="nav-" href="/contacts.php">Contacts</a>
      </li>
    </ul>
  </div>
</div>

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

"Optimizing websites for Retina displays through pixel ratios and media queries

Is there a way to make my max-width media queries effective for retina displays? I encountered an issue when testing my website on a macbook air with a pixel ratio of 2, causing my media queries to trigger at incorrect screen widths. For reference, here i ...

Transform CSS Selector into XPATH

Recently, I came across an interesting article about mapping CSS selectors to XPATH queries. Now, I'm on the lookout for any .NET libraries that can help with this mapping or conversion process. If you have any recommendations or suggestions on how to ...

Python allows for the sending of HTML content in the body of an email

Is there a way to show the content of an HTML file in an email body using Python, without having to manually copy and paste the HTML code into the script? ...

Developing a interactive quiz platform with JavaScript

I recently attempted to develop a straightforward quiz page using Javascript. Everything seemed to be working fine, until I noticed that when I clicked the submit button in the browser, the text generated in the paragraph section (via Script) vanished almo ...

Place Wordpress plugin scripts at the end of the JS queue for optimal performance

I'm currently working on a straightforward Wordpress application, but I've run into an issue where all the plugin scripts are being rendered before the ones enqueued in my functions.php. Below is a snippet from the functions.php file: function ...

What is the correct way to apply a concatenated element id when using the .click() function in

Having an issue with assigning buttons to input boxes in a loop. When using concatenated element IDs with the .click() method, the buttons won't click for some reason. The following code works: document.getElementById("streamInput1") .addEventLi ...

I am having trouble getting JQuery tablesorter to work, what am I missing?

As a newcomer to jQuery, I am attempting to implement Tablesorter, but unfortunately, it does not seem to be functioning properly on my table (the styling remains unaffected by the tablesorter css, and the sorting functionality is non-existent). Below is ...

Using CSS to create a zoom effect with absolute positioning

I am attempting to implement an interesting effect on my website where clicking a thumbnail causes a full-size div to "zoom in" from the thumbnail. My initial strategy involved using CSS and jQuery, setting the full-size div to position:absolute with top a ...

Ensuring accurate form validation on the server side using Spring MVC 3 within a jQuery dialog

I am encountering an issue validating a form within a jQuery dialog, while also using tiles in my project. Below is the relevant code snippet: Controller: @RequestMapping(value = "/popupOpen.do") protected ModelAndView popupOpen(@RequestParam String idDi ...

Retrieving data from Mysql based on selected checkboxes in HTML

Is it possible to get multiple return values for checkboxes? Currently, the code provided only echoes a single value even when multiple checkboxes are selected. How can this be resolved? $q2 = mysqli_query($conn,"SELECT product_img_url FROM temp_img"); ...

Querying MySQL database for variable values in JavaScript

I have a JavaScript file on my website that carries out calculations. Currently, my variables are defined as global variables in another JavaScript file. What I would like to do is make these variables dynamic by pulling their values from a MySQL database ...

Will using lengthy CSS custom property names impact the performance of a website?

I've been contemplating experimenting with projects that aim to shorten CSS variables in order to decrease the size of my CSS file. How do long CSS custom property names impact page performance? Reduction in CSS file size (including compression) Imp ...

Load the Google Maps JavaScript file only when it is required

I am working on a page that contains a button to open Google Maps in a modal. Since this function is rarely used by users, I am exploring the possibility of loading the Google Maps library only when it is needed. I would rather have the user wait for the m ...

Sending array values from a dynamic input field in Angular 4 and processing them accordingly

I am currently exploring options on how to add and delete multiple input fields. When a user submits two or more fields, I want the results to be displayed in an array. This is my HTML form: <form method="post" [formGroup]="formData"> ...

Challenger arises in the realm of Chakra UI styling

Recently, I've encountered an issue with displaying a card using chakra UI and next js. The CSS of chakra UI seems to be messed up, causing all my components to display incorrectly. It was working perfectly fine until yesterday. I tried deleting the . ...

Ensuring Uniqueness of Usernames through Client-Side Validation in

Looking to implement client-side validation for a username field during user registration to check if it is available before form submission. Using jQuery validate for basic client-side validations: http://jqueryvalidation.org/ Seeking advice on how to a ...

Implementing onblur method in Jquery Multiselect plugin

Is there a way to trigger the onblur method in jQuery multiselect? <select multiple="multiple" id="myID" name="myName"> <option value="blue">blue</option> <option value="red">red</option> <option value="green"& ...

Is there a different way to access a PHP page besides using a hyperlink? I've tried that method but it doesn't seem to

Within my side navbar, I have a dropdown menu with sub-menus for each option. My directory structure is as follows: RBS | +-- All php files are located here |--one.php |--two.php | +-- css | | | +-- all css files are stored here | + ...

Utilize a Google Chrome extension to interact with the DOM of the active tab

Alright, so I've got a good grasp on JavaScript/jQuery and can use them for various tasks. However, my current challenge involves manipulating the DOM of the open tab. I'm curious to know if it's feasible or if all the actions performed by a ...

Understanding CSS notation: The significance behind the symbol ">"

On a specific page of my website, the HTML structure is as follows: <html> <head><!-- Standard content with a link to a CSS file --></head> <body> <div id="splash"> <!-- Importan ...