Kivylius
Kivylius

Reputation: 6567

How to show a div thats hidden by css on button click

I'm pretty new to Jquery and i want to have a hidden div css: display:none and once a button has been clicked the $(..).slideDown will execute and the div will show its conents. I try'd this.

<style> .hidden-div{ display:none } </style>

<div class="hidden-div"> You can't see me </div>

<button onclick="show-div()"> Show Above Div </button>


<script>

    function show-div(){

        $('.hidden-div').slideDown('fast');
        // more stuff...
    }
</script>

This dont really slide it down properly as it overlaps everything else ? Also i try'd just setting the class="hidden-div" to class="display-div" but then the slideDown animation cannot be executed.

Now i could say $('hidden-div').hide() just after the div and remove the css altogether but it creates this problem where i see the div and then it gets hidden, its only 0.5sec thing at the start of the page load but its look bad.

So anyone know a solution?


Found a solution to my own problem..

//rehide the div, not sure why, but it works.
$('.hidden-div').hide(); 


//change class so it no longer display:none 
//but it will not show the div as .hide() was execute above.
$('.hidden-div').attr('class','showing-div'); 


//Slide it down and everything works.
$('.hidden-div').slideDown('fast');



//this can be done in 1 liner. (thank you, Mohsen for chaining explanation)
$('.hidden-div').hide().attr('class','showing-div').slideDown('fast');

Hope this is helpful for someone else.

Upvotes: 0

Views: 10932

Answers (4)

Mohsen
Mohsen

Reputation: 65855

  1. bind events via jQuery, don't use inline JavaScript method
  2. jQuery SlideDown method is not for removing an element. You can use hide or fadeOut
  3. BTW if you want to have an slide down effect and then hiding the element you can chain two methods.
  4. To prevent overlaping you need to use CSS. You can use position:absolute or give a certain height to element's parent.

To have both slide down and fade effects and also binding the event using non-inline code you can use this code:

$('button').bind('click', function(){
$('.hidden-div').slideDown(500).fadeOut(1000); //500ms slide down and 1s fade out
})

Remove that disply:none from the hidden-div class too.

Upvotes: 0

Mohamed Atef
Mohamed Atef

Reputation: 196

it's better to use standard javascript and point to that div with id

<style> .hidden-div{ display:none } </style>

<div class="hidden-div" id="hidden-div"> You can't see me </div>

<button onclick="getElementById('hidden-div').style.display = 'block'"> Show Above Div </button>

Upvotes: 1

Jaizen
Jaizen

Reputation: 131

In your javascript, first remove the class 'hidden-div' using jQuery function removeClass(). See if that helps...

Upvotes: 0

adeneo
adeneo

Reputation: 318352

$('.hidden-div').show('fast');

Try using < and > instead of [ and ], and format everything properly?

Upvotes: 0

Related Questions