treehouse : what would you like to learn today?
Web Design Web Development iOS Development

show() hide() jquery

  • I want to hide an element by default and when a div is clicked I want to show the hidden element.
    I'm doing something like this:
    $("#searchbox").hide(); // Hide by default
    $("button").click(function() {

    My question is how to display the #searchbox when that element is clicked and hide it again when another div is clicked
  • I guess this would work, but I'm not sure I understood what you want. :D

    $('#searchbox').hide();
    $('.div-triggering-searchbox-hiding').click(function(){
    $('#searchbox').hide();
    }
    $('#button-triggering-searchbox-showing').click(function(){
    $('#searchbox').show();
    }
  • $("#searchbox").hide(); // Hide by default
    $("button").click(function() {
    $("#searchbox").toggle();
    });
  • CSS:
    #searchbox { display: none; }

    JS:
    $("button").click(function() {
    $("#searchbox").toggle();
    });

    By setting the default in CSS you can guarantee you won't see it then have it flash away.
  • The only problem is that the search form isn't accessible at all if js doesn't load for whatever reason :(

    But if you're loading up modernizr in the head very early you could do this:
    <html class="no-js"> <!-- needed for modernizr to initialize. This is removed as soon as it does init -->

    #searchbox { display: none;  }
    .no-js #searchbox { display: block }

    $("button").click(function() {
    $("#searchbox").toggle();
    });

    You shouldn't see the flash unless you have a reeeaally slow connection.
  • Perfecto.