Edward Orourke Edward Orourke - 9 months ago 28
Javascript Question

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/

Answer Source

How about something like this:

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

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