0

I am implementing Headroom.js in one of my websites. Due to usability reasons I need to be able to toggle between initializing and destroying the script when the user clicks on a specific div. This div's id is #hamburger

This is my code so far.

$(document).ready(function(){
  $("#hamburger").click(function(){
    $(".banner").headroom("destroy");
  });
}); 

Right now, when the user clicks, the Headroom script is destroyed.

However, how can I make the script to initialize if the user clicks the same div again?

I know it's done using:

        $(".banner").headroom("init");

but I don't know how to construct this using jQuery.

Any help is appreciated.

Thanks!

Johann
  • 681
  • 3
  • 13
  • 30

2 Answers2

0

Add a variable to keep track of the script's state and check it on the click event handler:

$(document).ready(function(){
    var isActive = true;
    $("#hamburger").click(function(){
        if (isActive) {
            $(".banner").headroom("destroy");
            isActive = false;
        }
        else {
            (".banner").headroom("init");
            isActive = true;
       }
    });
}); 
Sami
  • 2,050
  • 1
  • 13
  • 25
0

You can do this by adding an on and off class to your #hamburger element. Then you can add this script to make it toggle:

$(document).ready(function(){
  $("#hamburger").click(function(){
    if ($(this).hasClass('on')) {
        $(".banner").headroom("destroy");
        $(this).removeClass('on').addClass('off');
    } else {
        $(".banner").headroom("init");
        $(this).removeClass('off').addClass('on');
    }
  });
});
DaMaGeX
  • 693
  • 7
  • 18