Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle style in vanilla

Is there any native JavaScript function that allow toggling style (not class) on an element?

So far, I'm using this kind of script:

target.addEventListener('click', (e) => {
    target.classList.toggle('target--is-visible')
}

Following by the style:

target {
    visibility: hidden;

    &--is-visible {
        visibility: visible;
    }
}

And I'd love being allowed to do so:

target.addEventListener('click', (e) => {
    target.style.toggle.visibility = 'visible'
}


EDIT

Ternary Operator is the closest of what I'm looking for in term of readability.

And the function sent by the @GuyWhoKnowsStuff uses ternary operator and deserves to be shared :

const div = document.querySelector('div');

function toggleStyle(el, prop, style1, style2) {
  el.style[prop] = el.style[prop] === style1 ? style2 : style1;
}

div.addEventListener('click', e => {
  toggleStyle(div, 'background', 'red', 'blue');
});

Thanks for your answers!

like image 687
Alexis Wollseifen Avatar asked Nov 19 '25 07:11

Alexis Wollseifen


2 Answers

Try this:

const div = document.querySelector('div');

function toggleStyle(el, prop, style1, style2) {
  el.style[prop] = el.style[prop] === style1 ? style2 : style1;
}

div.addEventListener('click', e => {
  toggleStyle(div, 'background', 'red', 'blue');
});
div {
  padding: 40px;
  background: red;
}
<div>Click Me</div>

or in your case, I do not believe click event fires if the div visibility is hidden,

see CSS: Is a hidden object clickable?,

so instead toggle opacity like so:

const div = document.querySelector('div');

function toggleStyle(el, prop, style1, style2) {
  el.style[prop] = el.style[prop] === style1 ? style2 : style1;
}

div.addEventListener('mousedown', e => {
  toggleStyle(div, 'opacity', '0', '1');
});
div {
  padding: 40px;
  background: red;
  opacity: 1;
}
<div>Click Me</div>
like image 186
notrota Avatar answered Nov 20 '25 21:11

notrota


You can also add a prototype like this:

HTMLElement.prototype.toggleVisibility = function()
{
    this.style.visibility = this.style.visibility == 'visible' ? 'hidden' : 'visible'
}

and then use like below:

target.toggleVisibility();

It will make it visible and hidden on each invocation.

like image 40
Manish Jangir Avatar answered Nov 20 '25 19:11

Manish Jangir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!