Tuesday, April 10, 2012

Jquery Height issue

I have a page when It loads for the first time I want to add a div with Height 450px. The page have 3 submit buttons and when ever anyone clicks any of those 3 buttons I need to set the height to 0px.


Here is what I did.`


     <style type="text/css">
 
     .DivHeight
     {
         height:450px;
     }
     .DivNoHeight
     {
         height:0px;
     }
 
    </style>
 
                    <script type="text/javascript">
           $(document).ready(function () {
 
            document.getElementById("divHeight").className = "DivHeight";
 
           $("#btnSubmit").click(function () {
 
 
             document.getElementById("#divHeight").className = "DivNoHeight";
             alert("Test");
 
         });
     });
       </script>
 


But when I have the above code on page load It is displaying fine but when I click on Submit button the results are coming after 450px :(


What am I missing?


UPDATE:


I am getting 450 PX height only if I add the class in the div Manually




Answer:

I'd suggest the following jQuery:
var div = $('#divHeight');
div.addClass('DivHeight');

$('button[type="submit"],input[type="submit"]').click(
    function(e) {
        e.preventDefault(); // prevents actual submission
        div.toggleClass('DivHeight DivNoHeight');
        console.log(div.height());
    });​
The demo using this HTML (adapt to your needs, of course):
<div id="divHeight">
</div>
<!-- ...other html... -->
<input type="submit" />
<button type="submit">Submit</button>
And this (or similar) CSS:
.DivHeight {
    background-color: #f90; // just for testing purposes
    height: 450px;
}
.DivNoHeight {
    background-color: #ffa; // just for testing purposes
    height: 0;
}​
This jQuery is based on the following assumptions:
  1. You're trying to deal with an element that has an id equal to divHeight,
  2. That you want the classes assigned to that div to control the height,
  3. That you have multiple buttons, or inputs, of type="submit",
  4. That you don't want to submit the form (or whatever) on clicking the buttons, but in response to another event (validation success, for example).

References:

No comments:

Post a Comment