DennisTurn DennisTurn - 5 months ago 14
Javascript Question

Image not showing within <li> till second append call

I have a list that when I click a button, it populates it with AJAX data, an image basically (this is simplified as the problem is not with AJAX but with the li element).

This is what is being populated into the list:

<li class="ind-selector" name="dancing"><a href="#"><img src="screenshot.jpg"></a></li>


The problem

When I click my call to action, it takes two clicks for this to show and when I debug this within the developer console the image is actually there but at height 0, and so is the
li
item.

When I remove the
li
and just display the image, it works every time.

So my debugging has come down to this: I'm 90% sure it's a problem with the CSS, and this is the CSS I'm using on the list item:

List item

width: 235px !important;
display: block;
float: left;
list-style: none;
list-style-type: none;
margin-right: -1px;


Image

width: 235px;
display: block;
height: 100%;
-webkit-filter: brightness(60%);


Using the most simplified jQuery append:

$(".item-list-slider").append("<li class='ind-modular-selector' name='"+ elem.module_name + "'><a href='#'><img src='" + elem.module_img_src + "' /></a></li>");


I'm sure this is a CSS problem but I can't seem to figure it out, has anyone got any ideas? Double clicking on the button to display the image works but the HTML/CSS is exactly the same on both the first click and second!

Answer

That's because you gave the image height in percentage without defining it in the parent, try to give it fixed height or define the height at the list item.

* {
  margin: 0;
  padding: 0
}

li {
  width: 235px !important;
  display: block;
  float: left;
  list-style: none;
  list-style-type: none;
  margin-right: -1px;
  background-color: blue;
  height: 200px;
}

img {
  width: 235px;
  display: block;
  height: 100%;
}
<li><img src="http://placehold.it/350x150"></li>