Wottensprels
Wottensprels

Reputation: 3327

Best way to add a div on demand

I want to implement a box into my page, which is displayed on demand: a user presses a button, the div is shown.

As a visual example what i want to achieve, look at the keyboard-shortcuts box on jsfiddle (down left corner): http://jsfiddle.net/

Now i am not sure in which way i should do this:

What way would you recommend?

Update

What if i got 15 different boxes which are not shown when the page loads, but should be added on demand? Sure, it would work, but can we call it "good practice" to simply hide every element we do not want to see?

Upvotes: 3

Views: 736

Answers (3)

Cerbrus
Cerbrus

Reputation: 72837

An answer without jQuery, just to make sure native JS isn't underrepresented ;-)

Create a div containing whatever content you want, and position it wherever you want it to be eventually, and hide it:

<div id="hiddenDiv" style="display:none">Some content here</div>

Then, add a event listener on a button to toggle it's visibility.

document.getElementById('showDivButton').addEventListener('click', toggleDiv);
var div = document.getElementById('hiddenDiv');

function toggleDiv(){
    if(div.style.display == 'block') {
        div.style.display = 'none';
    }else{
        div.style.display = 'block';
    }
}

Upvotes: 1

Sampson
Sampson

Reputation: 268334

Update: You recently modified the question to ask about 15 or so elements that aren't immediately needed. In this case, with so many non-immediate elements, I would probably consider creating them on the fly when you need them, but always checking for their existence prior so you don't end up re-creating them over and over.


I would just load the element in when the page loads:

<div id="box"></div>

Style it, having it be non-visible by default:

​#box {
    position: fixed;
    top: 10%; left: 10%;
    width: 80%; height: 80%;
    background: red;
    display: none;
}​

And then wire-up the logic to show it on some event, perhaps pressing of the spacebar:

var $box = $("#box");

$(document).on({
    keydown: function (event) {
        if (event.which === 32 && $box.is(":not(:visible)"))
            $box.stop().fadeIn();
    },
    keyup: function (event) {
        if (event.which === 32) 
            $box.stop().fadeOut();
    }
});

And voila: http://jsfiddle.net/GfMsd/

Or you could base it off of the clicking of another element, like jsFiddle has done:

$(".toggle").on("click", function (event) {
    $("#box").stop().fadeToggle();
});​

Demo: http://jsfiddle.net/GfMsd/1/

Upvotes: 2

Amyth
Amyth

Reputation: 32949

just add the div to HTML and set the css property display to none by default and use jquery to fade it in on click as follows:

 $('#some_button').click(function(){
     $('.hidden_box').fadeIn();
 });

Working Example

Try this working jsfiddle

Upvotes: 3

Related Questions