Get img src via JQuery

Get application specific logo images using the app specific base url and appending with the image name.

by Amy Ruddy

HTML

<script src="//code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- 
  Bootstrap docs: https://getbootstrap.com/docs
-->

<div class="container py-5">
  <h1>Image Source Via jQuery</h1>
  <p class="lead">Get application specific logos per application using jQuery</p>
  <p>Purpose: Each application will have its own logo. Use jQuery to dynamically get the partner image by setting an app specific basepath and appending it with the logo name.</p>
  <div id="show_img_src">
    <p>Source url: <span>&lt;img src&equals;&quot;&quot;&#47;&gt;</span></p>
  </div>
  <div id="img_div">
    <img src="" alt="partner logo" id="partner_logo">
  </div>
  <button class="btn btn-primary d-block mt-3" id="get_src">Get/set image src</button>
  <p class="text-muted mt-5"><small>Note: This example uses an image from wikicommons. In an actual application, a best practice would be to use a generic name for the logo e.g, <em>partner_logo.png</em>.</small></p>
</div>

CSS

.row {
  background: #f8f9fa;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}


#img_div {
  border: 1px solid #007bff; 
  width: 178px;
  height: 239px;
}

JavaScript

// Example url for testing purposes
// https: //upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/178px-Commons-logo.svg.png

// Set the base path of the application specific url
var baseUrl = "https://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/";
// Name of the logo. In actual environment should be generic, e.g., "partner_logo.png"
var logo = '178px-Commons-logo.svg.png'
// Conbine the baseUrl and logo name to create the img src url
var logoUrl = baseUrl + logo;
// Button on click function
$('#get_src').click(function() {
  // set the src of the <img />
  $('#partner_logo').attr('src', logoUrl);
  // Change the text of the <p> under the button to display the new url
  $('#show_img_src p').text('Source url: <img src="' + logoUrl + '" />');
});