1

I am trying to extract one value from array (that's easy) but... I have 5 words: banana, apple, lemon, orange, apricot wich is show on screen. I need to random chose one value to show on screen and hide another 4.

Ex: 1. banana 2. apple 3. lemon 4. orange 5. apricot

On click (every where) i need to see: 1. nothing 2. nothing 3. lemon (random) 4. nothing 5. nothing

Krease
  • 15,805
  • 8
  • 54
  • 86

1 Answers1

1

Hide all the fruits, then show one selectively. I've made a working example here: http://codepen.io/gunderson/pen/zxWQMV

html

<button id="changer">Change Fruit</button>
<div class="container">
    <span class="apple">Apple</span>
    <span class="banana">Banana</span>
    <span class="lemon">Lemon</span>
    <span class="orange">Orange</span>
    <span class="apricot">Apricot</span>
</div>

css

.container span {
    display: none;
}

js w/jquery

$("#changer").click(changeFruit);

function changeFruit(){
  var index = (Math.random() * 5) >> 0;

  $(".container span")
    .hide()
    .eq(index).show();
}

vanilla js

document.querySelector("#changer").addEventListener("click", changeFruit);

function changeFruit(){
  var index = (Math.random() * 5) >> 0;
  var spans = document.querySelectorAll(".container span");
  for (var i = 0, endi=spans.length; i < endi; i++){
    spans[i].style.display = "none";
  }
  spans[index].style.display = "block";
}
Patrick Gunderson
  • 3,263
  • 17
  • 28
  • so far is good and i wish to thank you but i see only one fruit wich is change after i press 'Change fruit' button. i don't wish show only one value. I need to extract one fruit and the rest of 4 fruit to change value to 'nothing' or 'not available' – custombrands Feb 20 '15 at 21:00
  • I need to have 5 differnt div with text Apple | Banana | Lemon | Orange | Apricot - click on button must hide 4 fruit wich is rename/change name to 'nothing' Nothing | Banana | Nothing | Nothing | Nothing – custombrands Feb 20 '15 at 21:05
  • You can use this same technique to accomplish that. Just add a second layer inside each span so you have `span.available` that contains your fruit name, and `span.unavailable` that is your "not available" message and toggle those accordingly. – Patrick Gunderson Feb 20 '15 at 21:06
  • This is not a place for people to do your homework for you. http://codepen.io/gunderson/pen/zxWQMV – Patrick Gunderson Feb 20 '15 at 21:14