Skip to content
Advertisement

Using conditions inside JavaScript

I have this infinite scroll code which works perfectly fine.

I m trying to use if-else conditions inside my Code but due to some syntax (i think) error its not echoing out.

My code goes as :

function addrows(rows) {
        let postList = $("#post-list");
        $.each(rows, function (i, row) {
            var img = row.image;
            let rowHtml = `
                 <div class="mt-3">
             `+if (img == null){ +`
                    <a href="post?id=`+row.id+`" style="color:black;">
                       <p style="font-size: 30px;padding: 15px 30px 15px 30px;">`+row.title+`</p>
                    </a>
             `+} else { +`
                    <a href="post">
                       <img src="images-main/images/`+row.image+`" alt="post-image" class="img-fluid rounded w-100">
                    </a>
              `+}+`
                 </div>
           `;
                        
            postList.append(rowHtml);            

        });
    }

Please note that the whole infinite scroll code works fine if I m to remove those if-else conditions.

Any help is greatly appreciated.

Advertisement

Answer

You can not concat the if else with the string, it is not valid syntax in javascript, either you can use the ternary conditional operator or using if else like this

  let postList = $("#post-list");
  $.each(rows, function (i, row) {
    var img = row.image;
    let rowHtml = `<div class="mt-3">`;
    if (img == null) {
      rowHtml += `<a href="post?id=` + row.id + `" style="color:black;">
                      <p style="font-size: 30px;padding: 15px 30px 15px 30px;">`+ row.title + `</p>
                  </a>`;
    }
    else {
      rowHtml += `<a href = "post" >
                      <img src="images-main/images/`+ row.image + `" alt = "post-image" class="img-fluid rounded w-100" >
                  </a>`;
    }
    rowHtml += '< /div>';
    postList.append(rowHtml);
  });
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement