0

I am using a text rotator to transition between text. There are three <span> tags which are appending the strings from the array 'headings'. I have managed to append them but if there are only two indexes in the array, it shows undefined.

I understand why this happens (since I am appending the third index), but I am not sure how to fix this. Would I set up a conditional statement to check whether a third index doesn't exist, then don't append this or simply append('') - an empty string

Code is below:

var imgObj = {
  "slideData": [{
      "headings": ['DISCOVER', 'THIS']
    },
    {
      "headings": ['EXPERIENCE', 'NEW GROUNDS']
    },
    {
      "headings": ['THREE', 'WORD', 'LINE']
    }
  ]
};

$(function() {
  imgObj.slideData.forEach(function(data, idx) {
    var first = data.headings[0];
    var second = data.headings[1];
    var third = data.headings[2];
    var seperator = ',';
    $('.slideTitle .heading-1').append(first + seperator);
    $('.slideTitle .heading-2').append(second + seperator);
    $('.slideTitle .heading-3').append(third + seperator);
  });

  $(".slideTitle span").Morphext({
    animation: "zoomInLeft",
    separator: ",",
    speed: 4000,
    complete: function() {

    }
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/Morphext/2.4.4/morphext.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Morphext/2.4.4/morphext.min.js"></script>

<h2 class="slideTitle">
  <span class="heading-1"></span>
  <span class="heading-2"></span>
  <span class="heading-3"></span>
</h2>
zxynz
  • 209
  • 1
  • 5
  • 16

2 Answers2

0

You can do it with javascript ternary operator

 var third =(data.headings[2])==undefined?"":data.headings[2];
Ahmad
  • 887
  • 7
  • 21
0
<script type="text/javascript">
var imgObj = {
  "slideData": [{
      "headings": ['DISCOVER', 'THIS']
    },
    {
      "headings": ['EXPERIENCE', 'NEW GROUNDS']
    },
    {
      "headings": ['THREE', 'WORD', 'LINE']
    }
  ]
};
$(function() {
  imgObj.slideData.forEach(function(data, idx) {
  var abcd="";
  for(i=0;i< data.headings.length ;i++){
  var seperator = ',';
  if(i < data.headings.length - 1)
  {
  abcd += data.headings[i] + " ";
  }
  else
  {
  abcd += data.headings[i] + seperator;
  }

  }

   $('.slideTitle .heading-1').append(abcd);
  });

  $(".slideTitle span").Morphext({
    animation: "zoomInLeft",
    separator: ",",
    speed: 4000,
    complete: function() {

    }
  });
});
</script>


<h2 class="slideTitle">
  <span class="heading-1"></span>
</h2>

u can use above code n instead of using 3 span tag for one span tag u can append. hope this helps u...