Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/Hide div element with one button

Tags:

html

jquery

I have recently been diving into jquery and loved how you could show/hide elements when an event is triggered. I tried adding a simple feature to my test website that will show Login Form when the login button is clicked and then hide the form if the button is clicked again, however; the jquery function I am using only works once (when I click the button and display the form) but after the form is displayed if I try to click the button again nothing happens.

Jquery Code:

function displayLoginBox(){


if ($("#login_Box_Div:hidden")){

        $("#login_Box_Div").show();
        $("#buttonLogin").css('color', '#FF0');

}
else if($("#login_Box_Div:visible")){

        $("#login_Box_Div").hide(); 
        $("#buttonLogin").css('color','white');
}
}

HTML button code:

<h3> <a href= "#">Pictio  </a> <button id = "buttonLogin" onclick = "displayLoginBox()">LogIn</button></h3>

HTML div code:

<div id = "login_Box_Div"> 
        <form name = "myform" > 
            <input type = "text" name = "username" placeholder = "Username"  />
            <input type = "password" name = "password" placeholder= "Password" />
            <input type = "submit" id = "submitLogin" />
        </form>

</div>

I have a feeling that the jquery script only runs once and then is finished, but I could be wrong.

like image 213
Wil Prim Avatar asked Oct 30 '12 18:10

Wil Prim


People also ask

How do I show and hide a div on click?

To show and hide div on mouse click using jQuery, use the toggle() method. On mouse click, the div is visible and on again clicking the div, it hides.

How do I hide a div element?

The document. getElementById will select the div with given id. The style. display = "none" will make it disappear when clicked on div.


2 Answers

Try using .toggle()

$('#buttonLogin').on('click', function(e){
    $("#login_Box_Div").toggle();
    $(this).toggleClass('class1')
});​

.class1
{
     color: orange;
}​

You can use toggleClass() to toggle the class for the button

Check FIDDLE

like image 176
Sushanth -- Avatar answered Oct 03 '22 02:10

Sushanth --


There's no need to use inline javascript.

LIVE DEMO

$('#buttonLogin').click(function(){
   $('#login_Box_Div').toggle();
});
like image 44
Roko C. Buljan Avatar answered Oct 03 '22 03:10

Roko C. Buljan