Jobs
Jobs

Reputation: 29

How to close an open collapsed navbar when clicking outside of the navbar element in HTML site?

How can I close an open collapsed navbar on clicking outside of the navbar element? Currently, the only way to open or close it is by clicking on the navbar-toggle button.

See here for an example and code:

So far, I have tried the following which doesn't seem to work:

$(document).ready(function () { 
    $(document).click(function () {
        // if($(".navbar-collapse").hasClass("in")){
            $('.navbar-collapse').collapse('hide');
        // }
    });
});

But the above method is not working

Upvotes: 3

Views: 583

Answers (3)

Rogier
Rogier

Reputation: 33

You should add an event listener on the document and check if the click is outside the navbar:

// listen to clicks in document
document.addEventListener("click", (evt) => {
    let targetElement = evt.target;
    const navbar = document.querySelector('.navbar-collapse');
    const navbarToggler = document.querySelector('.navbar-toggle');
    
    do {

        // open menu when click is on toggle button and menu does not have the 'in' class
        if (targetElement == navbarToggler && ! navbar.classList.contains('in')) {
            navbar.classList.add('in');
            return;
        } 
        
        // do nothing when clicked in navbar
        else if (targetElement == navbar) {
            return;
        }

        // Go up the DOM
        targetElement = targetElement.parentNode;

    } while (targetElement);

    // when clicked outside of navbar
    navbar.classList.remove('in');
});

Upvotes: 0

avia
avia

Reputation: 1578

You can define a function and call on mouseleave. Here is an example:

function showMeTheMoney() {
  $('.treasure').toggle();
}
.treasure {
background:blue;
color:white
width:100px;height:50px;
position:absolute;bottom:0;right:0;
display:none;
}

div {
height:200px;width:200px;
}

.somespan {
width:100px;
height:100px;
background:yellow;
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <span class="somespan" onmouseleave="showMeTheMoney();">Hover this red span and leave it with your mouse to reveal the treasure</span>
    <span class="treasure">The treasure is found.</span>
</div>

Upvotes: 0

Maik Lowrey
Maik Lowrey

Reputation: 17594

the easiest way would be to attach a click eventlistener to the body tag.

document.body.addEventListener('click', (e) => {
    if($(".navbar-collapse").hasClass("in")){
        $('.navbar-collapse').collapse('hide');
    }  
})

Upvotes: 1

Related Questions