Harry K
Harry K

Reputation: 125

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.

Upvotes: 2

Views: 58

Answers (2)

Phil
Phil

Reputation: 164768

As you've seen, you cannot inline an if..else into string concatenation.

One thing jQuery makes very easy is DOM element creation and manipulation so why not use it

function addrows(rows) {
  $("#post-list").append(rows.map(row => {
    const a = $("<a>")
    if (row.image) {
      a.append($("<img>", {
        src: `images-main/images/${row.image}`,
        alt: "post-image"
      }).addClass("img-fluid rounded w-100"))
    } else {
      a.css({ color: "black" }).append($("<p>", {
        text: row.title
      }).css({ fontSize: "30px", padding: "15px 30px" }))
    }
    
    return $("<div>").addClass("mt-3").append(a)
  })
}

Upvotes: 1

Noman Fareed
Noman Fareed

Reputation: 284

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);
  });
}

Upvotes: 1

Related Questions