Varsh
Varsh

Reputation: 465

Set title to images on condition in javascript

I have following javascript code to display images and their information. From getImages() method I am getting two API response arrays. The first array has image url's and second have owner and price info. There is only 9 API response from which I am getting image URL, its owner and price information. So in the loop, for 9 iteration image url is getting from API and for rest, I am setting some default image. So for default images, there is no owner and price information and thus the title should not be displayed for them.

window.onload = function () {
var allImages = "";
var owner,price;
var imgurl = getImages();
var imginfo = imgurl[1];
console.log(imginfo);
for (var i = 0, j = 298; i < j; i++) {

    if(imgurl[0][i] == undefined){imgurl[0][i]="image/upload.png"}

    if(typeof imginfo[i] === "undefined"){owner = ""; price=""; }
    else{owner = imginfo[i]["owner"]; price=imginfo[i]["price"];
    }

    allImages += '<img class="myImg" src='+ imgurl[0][i] +' id='+i+'_id onclick="openpopup(this.src)" title="owner='+owner+', price='+price+'">';

}

$('#photos').append(allImages);

};

Can somebody give me some idea in code? How to give condition for setting image title. If the response is undefined, set title to empty.

Upvotes: 1

Views: 424

Answers (2)

Abhay Agarwal
Abhay Agarwal

Reputation: 89

try this, you can use ternary operator also if required.

window.onload = function () {
var allImages = "";
var owner,price;
var imgurl = getImages();
var imginfo = imgurl[1];
console.log(imginfo);
for (var i = 0, j = 298; i < j; i++) {
    var title="";
    if(imgurl[0][i] == undefined){imgurl[0][i]="image/upload.png"}

    if(!(typeof imginfo[i] === "undefined")){
     title="owner="+imginfo[i]["owner"]+", price="+imginfo[i]["price"]+"";
    }

    allImages += '<img class="myImg" src='+ imgurl[0][i] +' id='+i+'_id onclick="openpopup(this.src)" title="'+title+'">';
}

$('#photos').append(allImages);

};
</script>

Upvotes: 1

Junius L
Junius L

Reputation: 16132

Just add the title attribute in your else part and remove it from the <img> tag.

window.onload = function() {
  var allImages = "";
  var owner, price;
  var imgurl = getImages();
  var imginfo = imgurl[1];
  console.log(imginfo);
  for (var i = 0, j = 298; i < j; i++) {

    if (imgurl[0][i] == undefined) {
      imgurl[0][i] = "image/upload.png"
    }

    if (typeof imginfo[i] === "undefined") {
      owner = "";
    } else {
      owner = 'title="owner=' + imginfo[i]["owner"] + ', price=' + imginfo[i]["price"] + '"';
    }

    allImages += '<img class="myImg" src=' + imgurl[0][i] + ' id=' + i + '_id onclick="openpopup(this.src)" ' + owner + '>';

  }

  $('#photos').append(allImages);

};

Upvotes: 2

Related Questions