Fahad
Fahad

Reputation: 1444

jquery show hidden div

Firstly, I'm sort of embarrassed asking about this, so many people have already asked this question but even after having gone through so many posts, I'm unable to achieve what I want. Basically, a div, initially hidden, has to be displayed on a button click.

I tried hiding the div using display:none and hide() and then displaying it using show(), toggle(), and css("display","block"). Using all sorts of combinations of the above, I was still unable to get the result.

Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="css/smoothness/jquery-ui-1.9.2.custom.min.css" rel="stylesheet" type="text/css" />
<script src="jQuery/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="jQuery/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#one').hide();
        $('#Button1').click(function () {
            $('#one').toggle(500);
        });         
    });
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="one" style="height: 20px;width:200px; background-color: Red; ">       
</div>
<asp:Button ID="Button1" runat="server" Text="Show" />
</form>
</body>
</html>

On button click, the div is shown for a brief second before it disappears again.

The same thing happens if I use show() instead of toggle() in the above code.

Again the same thing if I set style="display:none" to the div instead of using hide() and then use show() or toggle().

I also tried using $('#one').css("display","block"); but again, the same result.

Can anyone please tell me where I'm going wrong. Just started learning jQuery and it is really frustrating when something apparently so simple will not work.

Thanks in advance. :)

Upvotes: 0

Views: 4013

Answers (2)

Ram
Ram

Reputation: 144739

You are submitting the form and the page is reloaded, the default type of the button element is submit, you can try using preventDefault method of the event object or set the type attribute of the button to button.

$(document).ready(function () {
    $('#one').hide();
    $('#Button1').click(function(e) {
        e.preventDefault();
        $('#one').toggle(500);
    });         
});

Upvotes: 1

Usman
Usman

Reputation: 3278

Since you are using button with type button as asp:Button rendered in browser having type="submit" , so use return false; as

$(document).ready(function () {
        $('#one').hide();
        $('#Button1').click(function () {
            $('#one').toggle(500);
            return false;
        });         
    });

Upvotes: 2

Related Questions