albertski albertski - 3 months ago 10
jQuery Question

If space is available add element to html

I am displaying a list of 15 images. Depending on the width of the images (yes the images width varies) and the width of the screen size, there may be a different amount of images on each row.

For example, there is a case that I have 3 rows of 4 images and 1 row of 3 images. Now on the last row, there is an empty space. How can I add some element or text to the empty space on the last row and only if it is empty? So if I have 3 rows of 15 images, I shouldn't see my added element.

This is how my html looks:

<div class="view-content">
<div class="views-row views-row-1"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-2"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-3"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-4"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-5"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-6"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-7"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-8"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-9"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-10"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-11"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-12"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-13"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-14"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
<div class="views-row views-row-15"><a href="#"><img src="http://www.example.com/image.jpg /><a/></div>
</div>

Answer

I was able to figure this out by looking at the last item and figuring out how much space is to the right side of the screen. If there is enough room I add my element.

var item = '.views-row-15';
var element = $(item);

// Get the screen size.
var screen_size = $(window).width();

// Calculate the amount of empty space by looking at the space between the
// end of the window and the element.
var amount_of_empty_space = screen_size - (element.offset().left + element.width());

// If past this amount add the button.
if (amount_of_empty_space > 240) {
  var button = '';
  button += '<div class="views-row-more">';
  button += '  <div class="more-styles-button--text">See  More</div>';
  button += '</div>';

  $(button).insertAfter(item);
}