javascript onclick create(element) div viz popup box

raj_n picture raj_n · Jul 18, 2012 · Viewed 34.8k times · Source

I'm trying to make a pop up box, which gets invoked on clicking a button, this is what I've got so far.. http://jsfiddle.net/WGPhG/2/

Answer

xcopy picture xcopy · Jul 18, 2012

Here is a fiddle that actually does what you want - http://jsfiddle.net/WGPhG/6/

JS

function popUp(){
    var popup = document.createElement('div');
    popup.className = 'popup';
    popup.id = 'test';
    var cancel = document.createElement('div');
    cancel.className = 'cancel';
    cancel.innerHTML = 'close';
    cancel.onclick = function (e) { popup.parentNode.removeChild(popup) };
    var message = document.createElement('span');
    message.innerHTML = "This is a test message";
    popup.appendChild(message);                                    
    popup.appendChild(cancel);
    document.body.appendChild(popup);
}

NOTES

To set the class on an element you use element.className instead of element.class. For the onclick event handler on the cancel element, it is better to directly assign the onclick handler with an anonymous function that does what you need as in my example above.


EDIT (More Efficient Way)

This is actually a much better of getting the results that you want because there is no overhead involved with recreating the elements every time the popup is shown. Fiddle - http://jsfiddle.net/WGPhG/7/

CSS

.popup
{
    position:absolute;
    top:0px;
    left:0px;
    margin:100px auto;
    width:200px;
    height:150px;
    font-family:verdana;
    font-size:13px;
    padding:10px;
    background-color:rgb(240,240,240);
    border:2px solid grey;
    z-index:100000000000000000;
    display:none
}

.cancel
{
    display:relative;
    cursor:pointer;
    margin:0;
    float:right;
    height:10px;
    width:14px;
    padding:0 0 5px 0;
    background-color:red;
    text-align:center;
    font-weight:bold;
    font-size:11px;
    color:white;
    border-radius:3px;
    z-index:100000000000000000;
}

HTML

<button onClick="openPopup();">click here</button>
<div id="test" class="popup">
    This is a test message
    <div class="cancel" onclick="closePopup();"></div>
</div>

JS

function openPopup() {
    document.getElementById('test').style.display = 'block';
}

function closePopup() {
    document.getElementById('test').style.display = 'none';
}