skip to Main Content

How can I simplify this into one single function:

  $("#tab-one").click(function() {
    var imageUrl = "img/img-1.png";
    $(".masthead.product-detail").css("background-image", "url(" + imageUrl + ")");
  });
  $("#tab-two").click(function() {
    var imageUrl = "img/img-2.png";
    $(".masthead.product-detail").css("background-image", "url(" + imageUrl + ")");
  });
  $("#tab-three").click(function() {
    var imageUrl = "img/img-3.png";
    $(".masthead.product-detail").css("background-image", "url(" + imageUrl + ")");
  });

Many thanks in advance!

2

Answers


  1. add corresponding image src to each tab as a data-* attribute.

    Give a common class to all tabs.

    Now you can reduce your code with one click handler like below:

    $(".tab").click(function() { // use the common class to apply click handler
     $(".masthead.product-detail").css("background-image", "url(" + $(this).data('img-src') + ")");
    });
    

    Sample working snippet:

    $(".tab").click(function() {
      $(".masthead.product-detail").css("background-image", "url(" + $(this).data('img-src') + ")");
    });
    .product-detail {
      height: 300px;
      width: 300px;
      background-repeat: no-repeat;
      background-position: center;
      color: red;
      font-size: x-large;
      font-weight:bold;
      text-align: center;
      vertical-align: middle;
      line-height: 90px;   
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div>
      <div class="tab" id="tab-one" data-img-src="https://letsenhance.io/static/8f5e523ee6b2479e26ecc91b9c25261e/1015f/MainAfter.jpg">Click tab-one</div>
      <div class="tab" id="tab-two" data-img-src="https://previews.123rf.com/images/kamchatka/kamchatka1005/kamchatka100500301/6937927-zebras-on-lake.jpg">Click tab-two</div>
      <div class="tab" id="tab-three" data-img-src="https://img.freepik.com/free-photo/painting-mountain-lake-with-mountain-background_188544-9126.jpg">Click tab-three</div>
    </div>
    <br>
    <div class="masthead product-detail"> background image will get updated here!</div>
    Login or Signup to reply.
  2. You can code like this:

    In your HTML use data-* attribute:

    <div class="tab" id="tab-one" data-image="img/img-1.png">Tab One</div>
    <div class="tab" id="tab-two" data-image="img/img-2.png">Tab Two</div>
    <div class="tab" id="tab-three" data-image="img/img-3.png">Tab Three</div>
    

    Then in your JavaScript Code:

    $(".tab").click(function() {
        var imageUrl = $(this).data("image");
        $(".masthead.product-detail").css("background-image", "url(" + imageUrl + ")");
    });
    

    This is how using data-* attribute, simply you can change the background image.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search