what I’m trying to do is to make my contact form visible on button click. The problem is that the code works only in console, the values are changing I can see that by viewing it in console.log
. but the div element doesn’t change its position. I even tried making it display: flex;
and display:none;
but got the same results. Any suggestion?
Code :
var btnK = document.getElementById("K");
var contact = document.querySelector("#contactTab");
var contactTab = getComputedStyle(contact).left;
btnK.addEventListener("click", contactFun);
var contactOff = 3000 + "px";
var contactOn = 650 + "px";
function contactFun() {
if (contactTab == contactOff) {
contactTab = contactOn;
console.log("Changing from none to flex . Succes");
console.log(contactTab);
} else if (contactTab == contactOn) {
contactTab = contactOff;
console.log("Changing from flex to none . Succes");
console.log(contactTab);
}
}
2
Answers
Solution: You will need to apply the styles to the selected element, i.e.,
contact
Explanation:
Based on the source code that you have shared above, you are not applying anything new to your HTML- in the
if-else
block.Inside the
contactFun()
function, you are just setting thecontactTab
variable tocontactOn
orcontactOff
.and then, you simply log it on console.
So, apply those to the HTML element inside
if-else
or outside it; howsoever you like.Your code is updating the contents of the variable "contactTab" to contain a different string.
You seem to be thinking that because you originally filled that variable by reading the
getComputedStyle
of the#contactTab
element, changing it will update the style in the DOM. That’s not how it works; the variable just contains a string, it’s not a pointer connected to the page anymore. You need to set that value back into the DOM explicitly.(Meanwhile, the ‘left’ property only affects positioned elements, i.e. those with a position of
relative
,absolute
, orfixed
— if the element doesn’t have one of those values, setting itsleft
prop will do nothing.)Note also that the way you’ve written your code is fairly fragile: both the "if" and the "else" look for specific values, meaning that if the initial value doesn’t match either one exactly, nothing will happen. This can happen often when reading from the DOM — browsers don’t always report things in the same units or formats you expect. (I sidestepped this in the code sample above by making the
else
a catch-all instead of looking for a specific value.)A second point of fragility is doing this in JS in the first place: any change in your layout will also require updates to this javascript — generally when doing this sort of thing, it’s safer to toggle a CSS class on and off instead of setting style values directly. That simplifies your javascript, and keeps all the style-specific rules contained within the CSS where they can safely be modified without breaking the script: