A
A
Anastasia2020-04-28 23:15:50
JavaScript
Anastasia, 2020-04-28 23:15:50

How to remove the class when clicking on the body?

I have a div which has an image. Clicking on this div adds a class (class with style flips this image by 180deg) and clicking on the div again removes this class.
I need the class to be removed when clicking outside this div.
Code:

(function (document) {
    var div = document.getElementById('dropdownMenuButton');
    var icon = document.getElementById('arrow_lang');
    var open = false;

    div.addEventListener('click', function () {
        if (open) {
            icon.className = 'arrow_lang';
        } else {
            icon.className = 'arrow_lang open';
        }

        open = !open;
    });
})(document);


I tried writing like this:

(function (document) {
    var div = document.getElementById('dropdownMenuButton');
    var icon = document.getElementById('arrow_lang');
    var open = false;

    div.addEventListener('click', function (e) {
e.preventDefault();
        if (open) {
            icon.className = 'arrow_lang';
        } else {
            icon.className = 'arrow_lang open';
        }

        open = !open;
    });
document.body.addeventlistener('click', function() {
if (open) {
            icon.className = 'arrow_lang';
            open = !open;
}
});
})(document);


But there was no result. Tell me my mistake

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mike Khromov, 2020-04-28
@MikeSilence

Try changing
document. body .addEventListener -> document.addEventListener

P
Peter, 2020-04-28
@Morpheus_God

The first thing that caught my eye is in the place where you hang an event on the body, you are doing
document.body.addeventlistener()
it right
document.body.addEventListener()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question