I want to change some css properties when scrolling. This worked with jQuery and I can't make it work using JavaScript.
This is the function that reads and set CSS properties:
function parallel_height_js(){
let scroll_top = window.scrollY;
console.log('scroll top = ',scroll_top)
let header_height = document.getElementsByClassName("sample-header-section")[0].clientHeight;
console.log('Header height = ',header_height)
document.getElementsByClassName("text-section")[0].style.marginTop = header_height;
console.log('text margin top = ',document.getElementsByClassName("text-section")[0].style.marginTop)
document.getElementsByClassName("sample-header")[0].style.height = header_height - scroll_top;
console.log('header height = ',document.getElementsByClassName("sample-header")[0].style.height)
}
Afterwards, I execute the following to execute the function at scrolling or resizing:
parallel_height_js();
window.onscroll = parallel_height_js;
window.onresize = parallel_height_js;
In the browser console I get this from console.log:
scroll top = 8
Header height = 517
text margin top =
header height =
I checked that I am accessing the right elements when trying to set the CSS value, but this CSS value is not changing.
The error was because I didn't add 'px' string when setting new CSS values. So, the js code would be:
import './style.css'
function parallel_height_js(){
let scroll_top = window.scrollY;
let header_height = document.getElementsByClassName("sample-header-section")[0].clientHeight;
document.getElementsByClassName("text-section")[0].style.marginTop = header_height+'px';
document.getElementsByClassName("sample-header")[0].style.height = (header_height - scroll_top)+'px';
}
parallel_height_js();
window.onscroll = parallel_height_js;
window.onresize = parallel_height_js;
HTML:
<header>
<div class="sample-header">
<div class="...">
<input type="checkbox" id="menu" />
<label for="menu"></label>
<div class="menu-content">
<ul>
<li><a href="">Contact</a> </li>
<li><a href="">About Us</a> </li>
</ul>
</div>
</div>
<div class="sample-header-section">
<h1>...</h1>
<h2>...</h2>
</div>
</div>
</header>