Simplify JS so hash isn't needed hard coded in the script

I'm trying to find a way to simplify this script so that it doesn't need the hash names hard coded. So if you add a new link with the hash mytest and a div with the ID mytest it will work without having to visit the script and add mytest into the script. Hope I'm making my question clear.

My very kind thanks for any help figuring this out.

            jQuery(function($) {
              $('#menu-bottomnav li a').click(function(e) {
                e.preventDefault();
                animateSlider(this.hash);
              });

              function animateSlider(hash) {
                if (!$('#popups div.open').length) {
                  if (hash == '#bio') {
                    openPopup(hash);
                  }
                  if (hash == '#resume') {
                    openPopup(hash);
                  }
                } else {
                  if (hash == '#bio') {
                    openAndClose(hash)
                  }
                  if (hash == '#resume') {
                    openAndClose(hash)
                  }
                }
              }


              function openPopup(hash) {
                $(hash).slideToggle().addClass('open');
              }


              function openAndClose(hash) {
                if ($(hash).hasClass('open')) {
                  $($(hash)).slideToggle().removeClass('open');
                } else {
                  $('#popups div.open').slideToggle().removeClass('open');
                  $(hash).slideToggle().addClass('open');
                }
              }
            });

Have a working example here https://jsfiddle.net/a4y7z2fm/

Answers 1

  • Perhaps I don't understand the question, but it seems like it'd work just fine if you just passed the hash variable without the if statements at all:

    jQuery(function($) {
    $('#menu-bottomnav li a').click(function(e) {
        e.preventDefault();
        animateSlider(this.hash);
    });
    
    function animateSlider(hash) {
        if (!$('#popups div.open').length) {
            openPopup(hash);
        } else {
            openAndClose(hash);
        }
     }
    
    
     function openPopup(hash) {
         $(hash).slideToggle().addClass('open');
     }
    
    
    function openAndClose(hash) {
        if ($(hash).hasClass('open')) {
            $($(hash)).slideToggle().removeClass('open');
        } else {
            $('#popups div.open').slideToggle().removeClass('open');
            $(hash).slideToggle().addClass('open');
        }
      }
    });
    

Related Articles