Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

I need to create a lightbox with a Yes and No button that needs to blackout the rest of the screen. "No" closes the box.

The No button will close out the box and return to the normal page the Yes button will go to a specific URL

4 Answers

The simplest solution is using confirm().

Hi Lucas,

I'm a novice at this. Is there some code that you can provide that will create this?

Simply use confirm().

confirm() brings up a little window with a text and two buttons. The function accepts one argument, a string containing the text to display in the dialog. When called the script execution is paused until the user clicks one of the two buttons. The buttons aren't title "Yes" and "No" but "Yes" and "Cancel". When the user hits the "Cancel" button the function returns false. When hitting the "Yes" button it returns true. You can use it the following way:

if(confirm("Do you want to leave this page?")){
    window.location.href="http://example.com";
}

If you have any questions please ask ;)

Hi Jim,

The best way to do this is with Jquery.

  1. Append div on click
  2. Style div with fixed properties (so it covers whole screen), and a z index so it goes over the current elements.
  3. Remove the div first with the on method, passing in click as the first argument, and remove in an anonymous function.

Check out the link below and they have a jquery course on this that will help.

http://jsfiddle.net/1kqvwva1/15/

<body>
<button>Click me</button>
</body>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
var $overlay = "<div class='overlay'> <form action='http://google.com'> <input type='submit' value='Go to Google'> </form> <button class='no'>No </button> </div>";
</script> 
$("button").click(function()
    {$("body").append($overlay);
});

$("body").on("click", "button.no", function(){
    $("div.overlay").remove();    
})
button {color:black}
.overlay {
    background-color:rgba(0,0,0,.7);
    position: fixed;
    top:0;
    height:100%;
    width:100%;
    z-index:10;
}
button,form {
    display:inline;
}
  1. http://teamtreehouse.com/library/jquery-basics/creating-a-simple-lightbox/preparation
  2. http://teamtreehouse.com/library/jquery-basics/introduction-to-jquery/-ways-to-include-jquery-in-a-project

Also it would be nice to add html{overflow:hidden;} when opening the dialog box. :)