-3

How to write a javascript like this website on top menu bar, left button 'StackExchange'. When i click it, will show a box. When i click other place, the box will be closed.

$('html').click(function() {

`var display_value = document.getElementById("message_box").style.display;`

`if(display_value == "block")`

    `document.getElementById("message_box").style.display = "none";`

});

function show_message_box(){ document.getElementById("message_box").style.display = "block"; }

Thank you!

1 Answers1

0

for showing the box you could do the following: (assumes that the box has display:none style assigned)

 elem = document.getElementById(idOfWhatYouWantToClickOn)    
    elem.addEventListener ( 
            'click', 
            function() {
                document.getElementById(idOfBoxYouWantToHide).style.display = 'block'
            }, 
                false);

For hiding I'm not sure, you could try adding an eventListener to document, best inside the above function (so that it only gets added when the box is open), hide the box and remove it afterwards. I'm not sure though, if adding the eventhandler on document will really catch all clicks in the document. So it would look kind of like this: (this is pseudo code though! its not going to work like that, its just the general idea, pls, work out the details yourself, it should give you lots of stuff to search for)

elem = document.getElementById(idOfWhatYouWantToClickOn)    
elem.addEventListener ( 
    'click', 
    showBox, 
    false
);

function showBox(){
    document.getElementById(idOfBoxYouWantToHide).style.display = 'block';
    document.addEventListener ( 
        'click', 
        hideBox, 
                false
    );
}

function hideBox( ev ) {
    if (( ev.target.id != idOfWhatYouWantToClickOn) && (ev.target.id != idOfBoxYouWantToShowHide) )                     
    document.getElementById(idOfBoxYouWantToShowHide).style.display = 'none';
    document.RemoveEventListener('click',hideBox);
}
cytofu
  • 873
  • 9
  • 17