Kunal Saini Kunal Saini - 6 months ago 15
HTML Question

Change the height of div using javascript

I want to change the height of

div
when I scroll



#H {
position: fixed;
height: 200px;
background: red;
width: 200px
}

<div style="height:2000px; position:relative">
<div id="H"></div>
</div>


<script type="text/javascript">
window.onscroll = function() {
myFunction()
};

function myFunction() {
VAR X = document.getElementById("H");
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
X.css("height": "100px");
} else {
X.css("height": "200px");
}
}
</script>





But the code is not working. In the above code I tried to change the height of the
div
with
id="H"
on scroll from 200, that I have mentioned in the
CSS
to 100, but the
JS
is not running.

Answer

You have some problem in JavaScript.

Change it to like:

<script>
 window.onscroll = function() {myFunction()};

function myFunction() {
    var X=document.getElementById("H");
    if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
        X.style.height = "1000px";
    } 
    else {
       X.style.height = "200px";
        }
    }

</script>

VAR X should be var X

And

X.css("height":"1000px"); change style like X.style.height = "1000px";

Working Fiddle

Comments