I'm trying to become better at javascript and have written a simple script that just creates some html from getting some details from some elements (e.g. the image alt text) and inserts it onto the page to create a caption. Hover over the top right of the image to see this caption.
I was able to successfully achieve what I wanted through my code. However, my javascript feels a bit 'wet', and I'd like to be able to improve this for brevity and clarity.
Can anyone recommend any improvements to my javascript, and make it either more concise or clear?
I know that jQuery can achieve this in fewer lines of code, but I'm less of a fan of jQuery and believe that ES6/ES7 etc can often write more concise code.
Thanks for any help here. Find a working demo below:
Codepen: https://codepen.io/anon/pen/PrwzBj
/* --- Wide Image Caption --- */
// Define Elements:
const wideImg = document.querySelector('.full-width-image-atf img'),
captionText = wideImg.getAttribute('alt'),
captionInnerHTML = '<span class="image-caption">' + captionText + '</span>',
caption = document.createElement('div');
// Amend caption:
caption.setAttribute('class', 'image-caption-wrap');
caption.style.cssText = 'background: none;';
caption.innerHTML = captionInnerHTML;
// Insert on page:
wideImg.parentNode.appendChild(caption);
/* --- End of Wide Image Caption --- */
img {width: 100%}
.full-width-image-atf .content-main-image {
position: relative;
color: #fff;
}
.full-width-image-atf .image-caption-wrap {
position: absolute;
top: 0;
right: 0;
display: flex;
flex-flow: row-reverse;
align-items: center;
padding: 15px 20px;
}
.full-width-image-atf .image-caption-wrap:before {
content: '\f05a';
font-family: 'Font Awesome 5 Pro';
font-size: 2em;
}
.full-width-image-atf .image-caption {
opacity: 0;
padding-right: 10px;
}
.full-width-image-atf .image-caption-wrap:hover .image-caption {
opacity: 1;
}
.full-width-image-atf .image-caption-wrap:hover {
background: black !important;
cursor: pointer;
}
.full-width-image-atf .content-main-image, .full-width-image-atf .content-main-image * { transition: 0.4s ease all }
<div class='full-width-image-atf'>
<div class="content-main-image">
<img src="https://static.independent.co.uk/s3fs-public/thumbnails/image/2018/12/31/10/lion-face.jpg?w968h681" alt="This is a test">
</div>
</div>