Skip to content Skip to sidebar Skip to footer

Same Functions, Different Random Results - Jquery

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.lengt

Solution 1:

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

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

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

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

Solution 2:

This is an approach with jquery.

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

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

$('a').click(function() {
  loadFruit(this);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script><div>
  "You need to eat <ahref='#'>just_some_fruit</a>: it is good for your health." "My son doesn´t like <ahref='#'>another_fruit_here</a>."
</div>

Hope it helps!

Post a Comment for "Same Functions, Different Random Results - Jquery"