Ryan
Ryan

Reputation: 69

Show a random element on hover, Jquery

I'm looking to have a random paragraph element display each time I mouse over the logo, and hide again when the mouse leaves.

Here's the HTML for the paragraphs and the logo:

<div>
<p class="quote" >ryan is a champion at indesign</p>
<p class="quote">ryan is not a champion at javascript</p>
<p class="quote">ryan likes ramen</p>
</div>

<a href="#"><img id="logo" src="../_blog/_assets/_logo_icons/_logo.png" alt="logo" /></a>

This script is the closest I've found so far that fulfills this:

$('p.quote').hide();

var quotes = $('p.quote');
var rand = Math.floor(Math.random() * quotes.length);

$('#logo').hover(function(){
    quotes.eq(rand).toggle();

    });

Unfortunately this only displays the same quote every time unless I refresh the page. Any other suggestions?

Thanks Ryan

Upvotes: 2

Views: 781

Answers (3)

Nathan
Nathan

Reputation: 6216

Working fiddle here: http://jsfiddle.net/wEnAW/7/

Upvotes: 0

Ariel
Ariel

Reputation: 26773

Move the line starting var rand into the hover function instead of outside it.

Then change:

quotes.eq(rand).toggle();

To:

quotes.hide().eq(rand).show();

You will also need to modify the .hover() so that it hides the quote when they stop hovering.

Here is the full code:

var quotes = $('p.quote');

$('#logo').hover(
  function() {
    var rand = Math.floor(Math.random() * quotes.length);
    quotes.hide().eq(rand).show();
  },
  function() {
    quotes.hide()
  }
);

Upvotes: 2

Thor Jacobsen
Thor Jacobsen

Reputation: 8851

Move var rand = Math.floor(Math.random() * quotes.length); inside your hover-handler, like this:

$('#logo').hover(function(){
    var rand = Math.floor(Math.random() * quotes.length);
    quotes.eq(rand).toggle();

    });

This way, it will update your rand every time

Upvotes: 1

Related Questions