1

First off, I've read extensively by now into what seem to be recurrent questions about how to hide a div after a properly detecting a click, or event, outside the div; indeed this has influenced my javascript code. But I'm a newbie and it's not working so I hope you can help me out.

Second, the jfiddle - https://jsfiddle.net/u5uzexqk/ ... please note the button should show when the any section of the search bar or indeed button is clicked on; and not show when a click anywhere outside is detected.

Before the code, I would just like to point out I have also read into the e-propagation thing, however I don't think it's the absence of that which is the problem; if it is, my profuse apologies.

Perhaps owing to the fact I'm new to Javascript, I can't see how the suggested answer from another question helps; the Jfiddle on the most popular answer seems to do the opposite - remove the menu when the menu link is clicked again.

Html

<body>


        <div id = "wrapper">
        <form action="" class="search-form">
            <div class="cell">
                <input type="text" name="q">
            </div>
            <div class="cell button-holder">
                <button type="submit" id="dropdownbutton">
                    <span>Search</span> 
                </button>    
            </div>
        </form>
        </div>



</body>

Javascript

$("#wrapper").onclick(function (e){

document.getElementById('#dropdownbutton').style.visibility = 'visible';
}

$(document).mouseup(function (e)
{

var container = $("#wrapper");

if (!container.is(e.target) // if the target of the click isn't the container...
    && container.has(e.target).length === 0) // ... nor a descendant of the container
{
    $("#dropdownbutton").hide();
}
});

});
user1849962
  • 1,273
  • 1
  • 11
  • 16
  • so for example half the javascript came from this helpful post (in some ways) - http://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it – user1849962 Feb 07 '17 at 21:15
  • Sorry, are you saying this should be tagged - java? – user1849962 Feb 07 '17 at 21:16
  • Sorted now, I hope – user1849962 Feb 07 '17 at 21:18
  • Possible duplicate of [JQuery show and hide div on mouse click (animate)](http://stackoverflow.com/questions/17638990/jquery-show-and-hide-div-on-mouse-click-animate) – Tha'er AlAjlouni ثائر العجلوني Feb 07 '17 at 21:21
  • Looks like the problem is you need to use jQuery's `.click` event and not `onclick`. You also have a missing closing `)`. That and using `.show()` as *@Sam Onela* mentioned. [Try this fiddle](https://jsfiddle.net/u5uzexqk/4/), is that what you are expecting? – Spencer Wieczorek Feb 07 '17 at 21:34
  • Yes that works except, like i mentioned to another below, it seems to get rid of the button; the red design hides and shows, but the button isn't active in either case. – user1849962 Feb 07 '17 at 22:01
  • Just to be clear; I don't necessarily want the red graphic to disappear; in fact I'd rather the width of the graphic stayed the same; I just want the button to be be inactive when a click takes place outside the whole wrapper. – user1849962 Feb 07 '17 at 22:05

3 Answers3

3

You are mixing methods for hiding and showing. If you are going to use .hide() then use .show() when showing it.

With your code, the call to .hide() will set the style to display: none, but then your native Javascript technique to show the button (which also contains the pound symbol in the id i.e. document.getElementById('#dropdownbutton') - don't confuse it with jQuery's selector when calling document.getElementById()) just adds a style for visibility: visible. Those are different properties.

<button type="submit" id="dropdownbutton" style="display: none; visibility: visible;">
    <span>Search</span>
  </button>

Also, as was pointed out in comments, there is no jQuery method .onclick. Use .click(). Also, there is a missing closing parenthesis after the click handler for the wrapper button. So update it like this:

$("#wrapper").click(function(e) {
    $("#dropdownbutton").show();
}); // <- add parenthesis (and optional semi-colon) to terminate the function call 

And has already been mentioned, you should wait until the DOM is ready to access elements. With jQuery, use document.ready().

$(document).ready(function(readyEvent) {
    //interact with DOM
    //now that the DOM is ready
    //e.g. fetch elements by id attribute, add event handlers, etc.
});

See these changes in action in the snippet below:

$(document).ready(function() {
  $("#wrapper").click(function(e) {
    //document.getElementById('dropdownbutton').style.visibility = 'visible';
    $("#dropdownbutton").show();
  });

  $(document).mouseup(function(e) {
    var container = $("#wrapper");

    if (!container.is(e.target) // if the target of the click isn't the container...
      && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
      $("#dropdownbutton").hide();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <form action="" class="search-form">
    <div class="cell">
      <input type="text" name="q">
    </div>
    <div class="cell button-holder">
      <button type="submit" id="dropdownbutton">
        <span>Search</span>
      </button>
    </div>
  </form>
</div>
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
  • I can't get it working in xamp though?? I've literally just transferred it across; is there anything I need to add – user1849962 Feb 07 '17 at 21:46
  • see my latest edit about [document.ready()](https://api.jquery.com/ready/). – Sᴀᴍ Onᴇᴌᴀ Feb 07 '17 at 21:48
  • Adding doc ready to the jfiddle seemed to mess it up ... am i right to put a { after the function() and then a closing } after all the javascript and then a ; of course. – user1849962 Feb 07 '17 at 21:56
  • Please refer to the added example (easily seen in the diff with the [latest edit](http://stackoverflow.com/posts/42100332/revisions#rev39ab00c1-6419-4824-86c5-bd4f3366da2e)). – Sᴀᴍ Onᴇᴌᴀ Feb 07 '17 at 22:00
1

First let's point out some issues in your code:

  1. There is no such function as onclick in jQuery. To attach a click event you either use: $(...).click(callback) or $(...).on("click", callback).
  2. The oposite of show is not visibility = "visible". show uses the display property (show = display = "none") and its oposite is hide (display = ""). So use show and hide.
  3. Since you are already using jQuery, why use document.getElementById, just $("#id") will do.
  4. Instead of all those checks to see if the target is the wrapper or something inside the wrapper, just stop the propagation of the event inside the event listener of the wrapper so it will never reach the document.
  5. You should wrap your code inside a load event- $() will do- To make sure that everything is loaded before starting doing anything.

$(function() {
  $("#wrapper").click(function(e) {
    $("#dropdownbutton").show();

    e.stopPropagation(); // if the event occur inside the wrraper, prevent it from bubbling up to the document and fires the bellow function
  });

  $(document).click(function(e) { // if the click target is the #wrapper (or something inside it) this event will never reach the document because of the stop propagation inside the above listener. So if this is fired then the target is not the wrapper, therefore we should hide the button
    $("#dropdownbutton").hide();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="wrapper">
    <form action="" class="search-form">
      <div class="cell">
        <input type="text" name="q">
      </div>
      <div class="cell button-holder">
        <button type="submit" id="dropdownbutton">
          <span>Search</span> 
        </button>
      </div>
    </form>
  </div>
</body>
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • @user1849962 It's not my code that causes the problem. Remove it and the problem will still be there! – ibrahim mahrir Feb 07 '17 at 22:03
  • @user1849962 It's because you have this `#dropdownbutton{ visibility: hidden; }` in your CSS. If you want to hide the button on start, just use `$("#dropdownbutton").hide();` as the first line in the function inside `$()`. Like [**this**](https://jsfiddle.net/mm8hv5oq/1/)! – ibrahim mahrir Feb 07 '17 at 22:07
  • @user1849962 you can even add some transition to it like [**this**](https://jsfiddle.net/1go9z6kq/). – ibrahim mahrir Feb 07 '17 at 22:09
  • Thanks, I see. What do I need to add so that only the button is disabled, so to speak, but the graphic remains the same width? So before, I had it half working where the red square what remain in place, but the word "search" went away, signalling the button had been disabled. – user1849962 Feb 07 '17 at 22:11
  • @user1849962 check the last fiddle I gave you, the transitio gives life to the button. Instead of jumping the user, it will smothly appear. – ibrahim mahrir Feb 07 '17 at 22:14
  • Basically, the website I'm trying to copy has what looks like a fixed width input field, and then, on clicking on it, the same width now accommodates an input field, and a small button to the right side, which the user can then click on to get a drop down menu (obviously the drop down menu bit is a different question entirely). – user1849962 Feb 07 '17 at 22:14
  • Yeah, I liked it; it's just I'm going to have a table of many columns and rows and not having fixed width will probably only cause more problems; it did look good though, so thanks for the suggestion. – user1849962 Feb 07 '17 at 22:16
  • You're welcome! CSS almost make my hair grey. I rarely come near it. I get made every time I see a line of CSS. So good luck! – ibrahim mahrir Feb 07 '17 at 22:18
  • But do you know a way of keeping the field the same width? – user1849962 Feb 07 '17 at 22:23
  • @user1849962 I tried to edit the fiddle after you mentioned the problem. 10 seconds and I gave up! Not a clue! – ibrahim mahrir Feb 07 '17 at 22:27
0

I would do it like this:

$("document").ready(function(){
    $("#dropdownbutton").hide();
    $( "input[name=q]" ).on( "focus blur", function() {
        if($(this).is( ":focus" ) ){
            $("#dropdownbutton").show();
        }else{
            $("#dropdownbutton").hide();
        }
    });     
});

Demo: http://codesheet.org/cs/wAnG3ofQ

studio-klik
  • 196
  • 1
  • 3
  • It didn't seem to work in the demo sheet.... although I like the fact that the width doesn't change; that's what I'm really after as well – user1849962 Feb 07 '17 at 22:28