V
V
Vladimir Novitsky2015-10-07 17:57:24
JavaScript
Vladimir Novitsky, 2015-10-07 17:57:24

How to add and remove a class from the body when clicking on an element?

How can I use jQuery to add a class to the body when clicking on a certain element (block, button or link), and remove it when clicked again?

I found one script here on the Toaster:

(function() {
  var $body = document.body,
    $nav - icon = $body.getElementsByClassName('nav-icon')[0];

  if (typeof $nav - icon !== 'undefined') {
    $nav - icon.addEventListener('click', function() {
      $body.className = ($body.className == 'nav-active') ? '' : 'nav-active';
    });
  }
}).call(this);

In theory, this is exactly what he should do, but for some reason it does not work.

Instead, for this line:
$nav - icon = $body.getElementsByClassName('nav-icon')[0];
gives an error: "Uncaught SyntaxError: Unexpected token -".

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly Inchin ☢, 2015-10-07
@Novitsky

$("div").click(function(){
   $("body").toggleClass("class");
});

The brain would also give an error for something like that.
If you tried to name a variable like that, then logically it would be necessary to write it together. Although, all the same, it will not work, because you cannot use minuses (they are dashes and hyphens) in the name of variables, like many other characters .

A
Andrey Goncharov, 2015-10-07
@agmegadeth

late)

$("block").click(function(event) {
  $("body").toggleClass('someclass');
});

I
Ivanq, 2015-10-07
@Ivanq

It's funny. A variable with spaces and minuses or pluses cannot be used. Replace last line with

$navicon = $body.getElementsByClassName('nav-icon')[0];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question