0

Let's suppose i have an array of words

JS

var fruit = [banana, apple, watermelon, mango];

function loadFruit() {
    var randomFruit = fruit[Math.floor(Math.random() * fruit.length)];
    $('.divLoadFruit').parent('div').html(randomFruit);
};

I need to trigger function on click of the middle word of the sentence, to obtain different random matches

HTML

"You need to eat <a class="divLoadFruit" href='javascript: loadFruit();'>just_some_fruit</a>: it is good for your health."

"My son doesn´t like <a class="divLoadFruit" href='javascript: loadFruit();'>another_fruit_here</a>."

When you click on one of the links, it triggers the same function (obviously) but gets me the same fruit in that spaces. Is there any way to make it random without repeating?

Ally
  • 1
  • 1

2 Answers2

1

Considering you click on the anchor tag and get a random fruit, the following code will work.

var fruit = ['banana', 'apple', 'watermelon', 'mango'];

function loadFruit(id) {
    var randomFruit = fruit[Math.floor(Math.random() * fruit.length)];
document.getElementById(id).innerHTML = randomFruit;
};
You need to eat <a id='just_some_fruit' href='javascript: loadFruit("just_some_fruit");'>just_some_fruit</a>: it is good for your health.

My son doesn´t like <a id='another_fruit_here' href='javascript: loadFruit("another_fruit_here");'>another_fruit_here</a>.
0

This is an approach with jquery.

var fruit = ["banana", "apple", "watermelon", "mango"];

function loadFruit(caller) {
  var randomFruit = fruit[Math.floor(Math.random() * fruit.length)];
  $(caller).html(randomFruit);
};

$('a').click(function() {
  loadFruit(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<div>
  "You need to eat <a href='#'>just_some_fruit</a>: it is good for your health." "My son doesn´t like <a href='#'>another_fruit_here</a>."
</div>

Hope it helps!

Ele
  • 33,468
  • 7
  • 37
  • 75