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="..开发者_JAVA百科/_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
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()
}
);
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
Working fiddle here: http://jsfiddle.net/wEnAW/7/
精彩评论