Skip to content

Saving multiple css values to one javascript variable using strings

I’m quite new to JavaScript so do bear with me. I’ve read a few threads here

How can I set multiple CSS styles in JavaScript?

Set CSS Property by string with JavaScript

The first link excited me, because it seems that you can save multiple css rules and values as a string which can then replace existing css values. With that in mind I gave it a go on the link below.

https://codepen.io/Laurie312/pen/JjyqZLO

CSS

nav {
        width: 100vw;
        height: 200px;
        overflow: hidden;
        z-index: 1;
        outline: none;
        background-color: red
    }

JavaScript

const button = document.getElementByTagName('button')

const navBar = document.getElementByTagName('nav')

const nav1Settings = 'nttwidth: 100vw;nttheight: 200px;nttoverflow: hidden;nttz-index: 1;nttoutline: none;nttbackground-color: red;nt'

const nav2Settings = 'nttheight: 400px;nttz-index: 0;nttoutline: 2px solid var(--var-light-1)nt'

button.addEventListener('click', function()) {
     if (navBar.contains(nav1Settings)) {
  navBar.toggle(nav2Settings)
}
                        }

VSCode editor seems to use less tabs than codepen editor. Is this working against my escape sequence? Can anyone begin to point me in a better direction for getting this code to work?

I know I’m still not anywhere near real world usage. I guess this is a step toward that, although I absolutely accept there might be other things I should understand better before asking this question, I’m grateful for all advice and suggestions.

Answer

Just construct the class in CSS and use javascript or jquery to apply that class on click. Here’s a quick JQuery example on how to apply and remove class.

In the Header add the following code for JQuery to work:

<script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>

Then just do this in body.

const button = document.getElementByTagName('button')

$( document ).on("click", button, function(){
  if ( $(" #navBar ").hasClass(" classOne ") ) {
    $(" #navBar ").removeClass(" classOne ");
    $(" #navBar ").addClass(" classTwo ");
  } else {
    $(" #navBar ").addClass(" classOne ");
    $(" #navBar ").removeClass(" classTwo ");
  }
});

Also when making the class add !important arguments, so that any other values get overridden.

P.S I’m not entirely sure on the sequence, but you should, I believe, use nrtt. n – New Line, r – Return. Different software understands one, other or both.