I
I
Ilya2020-06-04 12:53:43
css
Ilya, 2020-06-04 12:53:43

How to remove the burger menu when clicking on the content of the site?

Hello. I'm building one website. I'm learning JavaScript. I'm not very familiar with jQuery yet. I wanted to make a burger menu for mobile devices (is that what it's called?). The essence of the problem was to make it so that when you first click on the main item, a menu with the rest comes out, and when you click again, the rest of the items are hidden. Made a block in HTML:

<div class = "phone_navigation">
    <div class = "main_href" id="something">
        <p class = "hrefs">Товары</p>
    </div>
    <div class = "etc_hrefs">
        <p class = "hrefs">Главная</p>
        <p class = "hrefs">Услуги</p>
        <p class = "hrefs">Задать вопрос</p>
        <p class = "hrefs">Наш офис</p>
    </div>
</div>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Expedita amet vero, sapiente maiores quas 
    ullam quae. Aperiam repellat sunt accusantium, debitis, ullam quia reprehenderit distinctio corrupti 
    tenetur non tempora blanditiis?</p>

Set values ​​in CSS:
div.phone_navigation{
    display: block;
}
div.etc_hrefs{
    display: block;
    position: absolute;
    background: white;
    z-index: 50;
    width: 100%;
    left: -100%;
    transition-property: left;
    transition-duration: 0.8s;
    transition-timing-function: ease;
}
p.hrefs{
margin-left: 2%;
}

I dug out the following code from Overflows and adjusted it a bit to fit my needs:
$('#something').on('click', function() {
    if (!$(this).hasClass('clicked')) { // если класса нет
      $(this).addClass('clicked'); // добавляем класс
      document.getElementsByClassName('etc_hrefs')[0].style.left = '0'; // код для первого клика
    } else { // если есть
      $(this).removeClass('clicked'); // убираем класс
      document.getElementsByClassName('etc_hrefs')[0].style.left = '-100%'; // код для второго клика
    }
  });

Everything works, but I would like the menu to be hidden when clicking on the content of the site. That is, I clicked on the main item - the content appeared, I wanted to hide - I clicked on any element on the site. I would be grateful for any hint!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FinGanapre, 2020-06-04
@il14

Create a transparent full-screen div behind the menu and handle the click on it. If desired, you can set it to any color if you need to further darken everything except the menu when it is open.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question