How to go to the next text when a button is pressed?

So I want to make it so that when u press the button the button will invoke the action to go to the next element of the array.
I know how to do this with a for loop but, not how to do this with an event listener. Can someone help?

<script>
$(document).ready(function(){
  
$("btn").click(function){
  return console.log(names);
});
});


let names = ["Susan Smith",
"Anna Johnson",
"Bill Anderson",
"Peter Jones"];

 for (let i = 0; i < names.length; i++) {
   console.log(names[i]);
}
</script>

<div id="txt">
<h1>Bill Anderson</h1>
</div>

Something like this:

<div id="txt">
  <h1>Bill Anderson</h1>
</div>
<button class="btn">Next</button>
let names = ["Susan Smith", "Anna Johnson", "Bill Anderson", "Peter Jones"];

$(document).ready(function () {
  let namesIndex = 2;

  $(".btn").click(function () {
    $("h1").text(names[++namesIndex % names.length]);
  });
});

1 Like

So looking at this line

 $("h1").text(names[++namesIndex % names.length]);

You can just add JS code to the jQuery one? is that correct?

Can I just add an else statement as well? Does it need to start with a new $() or can it just be more plain JS?

 $("h1").text(names[++namesIndex % names.length]);

jQuery is JavaScript. And therefore you can use any standard JS inside jQuery.

$() is just a convenience function for selecting/manipulating DOM and in 2020 you can easily use the standard JS function document.querySelector() instead.

1 Like