Reputation: 403
I'm trying to change the header height dynamically within my Javascript code (within the second if statement). Here's the code I have at the moment:
var currentDate = new Date();
// Months are zero indexed, so for 21 December:
var saleStart = new Date("12-10-2017");
var saleEnd = new Date("12-19-2019");
if (saleStart <= currentDate && currentDate <= saleEnd && sessionStorage.getItem('firstVisit') === null) {
// Set display to '' (empty string) so the element adopts its default or inherited value
$(".sale_banner").show();
$(".hover_bkgr_fricc").show();
sessionStorage.setItem('firstVisit', '1');
}
else if(saleStart <= currentDate && currentDate <= saleEnd)
{
document.getElementsByClassName('header').style.height="140px";
$(".sale_banner").show();
}
else{
$(".sale_banner").hide();
}
For some reason the line to change the header height does nothing! I've also tried using getElementbyId
but that does nothing too!
My header.phtml
file opens with the following tag:
<header class="desktop">
This is the section of CSS I'm trying to change:
header.desktop {
height: 173px;
background-color: #6E348C;
}
I've used header, desktop, header.desktop
in the parentheses but still no luck! This is the error I get on the console:
Uncaught TypeError: Cannot read property 'style' of null
at HTMLDocument.<anonymous> (myproject.js:28)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at Function.ready (jquery.min.js:2)
at HTMLDocument.J (jquery.min.js:2)
Does anyone know what I'm missing?
Upvotes: 0
Views: 1760
Reputation: 1866
I haven't seen your HTML code, but I guess you don't have a header
class.
Your CSS suggests you have a header
tag with a desktop
class (header.desktop)
Then, you should try with getElementsByClassName
or querySelector
, :
document.getElementsByClassName('desktop')
// or
document.querySelector('.desktop')
You can use any of them, but querySelector
is a more modern method and only returns one element (if you have several elements with the same classname, then try querySelectorAll
or getElementsByClassName
)
Check this: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
UPDATE: Try this
function changeHeight() {
// Note that the class name is 'desktop', while 'header' is the name of the HTML tag
document.querySelector('.desktop').style.height = "100px"
}
header.desktop {
height: 50px;
background-color: #6E348C;
}
<header class="desktop">This is the header</header>
<button onclick="changeHeight()">Change height</button>
Upvotes: 1
Reputation: 360
Using getElementsByClassName always returns an array, you might want to change that to
document.getElementsByClassName('header')[0].style.height="140px";
That assuming you only have one header element, it would be nice if you could use id instead of class names
Upvotes: 1