Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript JQuery: Hide a div if anything except the div and its content is clicked

  • This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #35895
    bennyjien
    Participant

    Hi,

    Can someone please help me with his?
    I want to hide a div when anything except the div and its content is clicked.
    How do I do this?

    Thanks a lot.

    #93701
    itsjustjake
    Member

    can you post some code for an example??

    Is this a modal that your trying to close that is being overlayed?

    #93704
    bennyjien
    Participant

    Please visit miamiurbanist.com.

    There is a green menu bar below the main navigation bar.
    When you click on the Neighborhood menu for instance, there will be a pop up div showing up. To hide/close this div, currently you must click the Neighborhood menu again.

    What I want to do is any clicks except on the div and its content, will hide/close the pop up div.

    Thanks for your response.

    #93786
    Mottie
    Member

    You could use hover instead; change this function in your scripts.js file:

    /* custom scripts */
    $(document).ready(function() {

    $('#second-nav > li').hover(function(){
    $(this).siblings('li.selected').removeClass('selected').children('div').stop(true, true).fadeOut(250);
    $(this).addClass('selected').children('div').stop(true, true).fadeToggle(250);
    }, function(){
    $('#second-nav > li').removeClass('selected').children('div').stop(true, true).fadeOut(250);
    });

    });

    But if you must have it as a click, try this code:

    /* custom scripts */
    $(document).ready(function() {

    $('#second-nav > li > span').click(function(){
    $(this).parent('li').siblings('li.selected').removeClass('selected').children('div').stop(true, true).fadeOut(250);
    $(this).parent('li').toggleClass('selected').children('div').stop(true, true).fadeToggle(250);
    });
    $(document).click(function(e){
    // not an optimal use of selectors, but it works
    if ($(e.target).parentsUntil('#second-nav')[0] !== $('#second-nav').find('li.selected')[0]) {
    $('#second-nav > li').removeClass('selected').children('div').stop(true, true).fadeOut(250);
    }
    });

    });
    #93811
    bennyjien
    Participant

    Thank you very much, Mottie.
    This really helps!

    #201295
    gozonjoedaimar
    Participant

    I found this useful…

    jQuery(document).click(function(event){
        // Check if clicked outside .target-div
        if (!(jQuery(event.target).closest(".target-div").length)) {
            // Hide .target-div
            jQuery(".target-div").hide();
        }
    });
    
Viewing 6 posts - 1 through 6 (of 6 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.