Coder
Coder

Reputation: 1139

Trying to condense JavaScript / jQuery code

I am trying to condense my code in order to implement the DRY principle, I have played around with the code a bit and manage to condense some of it but not all.

The area I am looking to condense is the lines with the code:

$("#modal").on("hidden.bs.modal", function() {}

As you can see this is repeated throughout the file and I do not believe this is best practice. I have tried to place this in a function itself but the problem I have is that when I close the video it still continues to play.

Not sure if the code can be reduced any further so thought I would ask for advice.

// Video Play
$(function() {
  // Auto Play Modal Video
  $(".video").click(function() {
    var theModal = $(this).data("target"),
      videoSRC = $(this).attr("data-video"),
      videoSRCauto =
        videoSRC +
        "?modestbranding=1&rel=0&controls=0&showinfo=0&html5=1&autoplay=1";
  $(theModal + " video").attr("src", videoSRCauto);
  });

  $("#videoModal").on("hide.bs.modal", function() {
    $("video").attr("src", "");
  });
});

function video(vid) {
  $(vid).attr("src", $(vid).attr("src"));
}

$("#modal1").on("hidden.bs.modal", function() {
  video("#modal1 video");
});

$("#modal2").on("hidden.bs.modal", function() {
  video("#modal2 video");
});

$("#modal3").on("hidden.bs.modal", function() {
  video("#modal3 video");
});

$("#modal4").on("hidden.bs.modal", function() {
  video("#modal4 video");
});

$("#modal5").on("hidden.bs.modal", function() {
  video("#modal5 video");
});

$("#modal6").on("hidden.bs.modal", function() {
  video("#modal6 video");
});

$("#modal7").on("hidden.bs.modal", function(e) {
  video("#modal7 video");
});

Upvotes: 0

Views: 41

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

Use classes instead of IDs, and then you can select the video descendant dynamically, and pass it to video. For example, using a class name of .modal instead of #modal1, #modal2, ...:

function video($vid) {
  $vid.attr("src", $vid.attr("src"));
}
$(".modal").on("hidden.bs.modal", function() {
  video($(this).find('video'));
});

Upvotes: 3

Related Questions