Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I toggle my overlays so it can close when another link is clicked?

I have an overlay effect for a single page website. I have two links for two overlays. After I click the second link, the first overlay doesn't close and two overlays are shown. How can I have the initial overlay close?

HTML:

<nav id="menuheader">
    <ul style="display:block;">
        <li>
            <div class="about link" data-link="overlay-about"> About </div>
        </li>
        <li>
            <div class="service link" data-link="overlay-service"> Services </div>
        </li>
        <li>
            <div class="contact link"> Contact </div>
        </li>
    </ul>
</nav>
<aside class=" overlay overlay-about overlay-contentscale">
    <div class="overlay_close"></div>
</aside>
<aside class="overlay overlay-service overlay-contentscale ">
    <div class="overlay_close"></div>
</aside>

Javascript:

$(".link").on('click', function(e) {
    e.preventDefault();
    var currentClass = $(this).data("link");
    $("aside." + currentClass).addClass("open");

})
$('.overlay_close').on('click', function() {
    if ($('.overlay').hasClass('open')) {
        $("aside.overlay").removeClass("open");
        $(".overlay").addClass('close');
        $('.overlay').removeClass('close');
    }
});

If you can please use Javascript, not JQuery.

like image 735
redfelix Avatar asked Jun 22 '15 09:06

redfelix


1 Answers

First of all this code does not mean anyting

$(".overlay").addClass('close');
$('.overlay').removeClass('close');

You need to update the code in javascript like this

var currentClass;
$(".link").on('click', function(e) {
   e.preventDefault();
   currentClass = $(this).data("link");
   $("aside." + currentClass).addClass("open");

})
$('.overlay_close').on('click', function() {
   $("aside." + currentClass).removeClass("open");
});

EDIT: Javascript solution

var link = document.getElementsByClassName('link')
var overlay_close = document.getElementsByClassName('overlay_close');
var currentClass;
link.onclick = function(e){
  e.preventDefault();
  currentClass = this.getAttribute('data-link');
  this.classList.add("open")
}
overlay_close.onclick = function(e){
  var currentElement = document.querySelector("aside."+currentClass);     
  currentElement.classList.remove("open");
}
like image 174
Mohit Avatar answered Nov 15 '22 07:11

Mohit