user8690818
user8690818

Reputation:

Writing simple JQuery plugin

Hello everyone I'm new to JQuery so I wanted to know if I can avoid repeats in my code. I have a very simple plugin here :

  $.fn.preview = function() {
      $(this).on("click", function() {
          $("body").append("<div class='c'><img></div>");
          $(".c img").css("max-height", $(window).height() - 20);
          $(".c img").css("max-width", $(window).width() - 20);
          $(".c img").attr("src", $(this).attr("src"));
          $(".c").css("display", "flex");
          $(window).on("click resize", function(e) {
              if ($(e.target).is(".c")) {
                  $(".c").remove();
              }
              $(".c img").css({
                  "max-height": $(window).height() - 20,
                  "max-width": $(window).width() - 20
              });
          });
      });
  }
  $("img").preview();

But here the code $(".c img").css("max-height",$(window).height()-20); $(".c img").css("max-width",$(window).width()-20); repeats two times. Is there any way to write it once?

Thank you very much for spending your precious time with my issue.

Thank you for any help!

$.fn.preview=function(){
 $(this).on("click",function(){
  $("body").append("<div class='c'><img></div>");
  $(".c img").css("max-height",$(window).height()-20);
  $(".c img").css("max-width",$(window).width()-20);
  $(".c img").attr("src",$(this).attr("src"));
  $(".c").css("display","flex");
  $(window).on("click resize",function(e){
   if($(e.target).is(".c")){
    $(".c").remove();
   }
   $(".c img").css({"max-height":$(window).height()-20,"max-width":$(window).width()-20});
  });
 });
}
$("img").preview();
.c{display:none;justify-content:center;align-items:center;position:fixed;left:0;top:0;width:100%;height:100%;background-color:rgba(0,0,0,.8)}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://wallpaperbrowse.com/media/images/Wallpaper-4K.jpg" width="200"/>

Upvotes: 0

Views: 46

Answers (1)

Zenoo
Zenoo

Reputation: 12880

You can declare multiple CSS rules by passing an object as the .css() function parameter:

$(".c img").css({
    "max-height": $(window).height()-20,
    "max-width": $(window).width()-20
});

Upvotes: 1

Related Questions