If modal is active/shown add modal-open not on click

Viewed 218

I know this question is asked a lot but all the answers I've found all have the same answer which is great for most but it isn't working with my code,

This is the Javascript to open my modals

$(".button-b, .item, .item2, .button-a, .port_item").on("click", function() {
    var modal = $(this).data("modal");
    $(modal).show();
});

$(".modal").on("click", function(e) {
    var className = e.target.className;
    if(className === "modal" || className === "closex"){
      $(this).closest(".modal").hide();
    }
});

I could just add $("html","body").addClass("modal-open"); to .button-a, .button-b").on("click", function() { and $("html","body").removeClass("modal-open"); to $(".modal").on("click", function(e) { but because I've linked .button-b. .button-a any button that uses those styles also adds .modal-open to the body which means when someone clicks a button that isn't opening a modal the screen freezes and you can't scroll,

I tried to come up with something to work around it:

$(document).ready(function(){
    var modal = $(this).data("modal");
    if (modal = show) {
    $("html","body").addClass("modal-open");
  } else {
    $("html","body").removeClass("modal-open")
  }
});

But I have absolutely no clue what I'm doing in javascript so it doesn't work - what I want it do is when the modal is active/shown to add .modal-open to the body, so that it's not adding .modal-open when any buttons with .button-b, .button-a stylings are clicked but only if the modal is shown, I'm guessing I need an event listener? any help would be great.

1 Answers

Firstly, the following is incorrect...

$("html","body").addClass("modal-open");

The correct format is to list the selectors in the same string...

$("html, body").addClass("modal-open");

If I understand your issue correctly, the problem is that you're doing a hide on $(modal) independent of whether there is a result from $(this).data("modal")... and therefore adding the addClass within the same function results in no modal being shown, but the body being unusable.

So I believe this is more along the lines of what you want...

$(".button-b, .item, .item2, .button-a, .port_item").on("click", function() {
  var modal = $(this).data("modal");
  if (modal) {
    $(modal).show();
    $("html, body").addClass("modal-open");
  }
});

$(".modal").on("click", function(e) {
  var className = e.target.className;
  if(className === "modal" || className === "closex"){
    $(this).closest(".modal").hide();
    $("html, body").removeClass("modal-open");
  }
});
Related