I'm trying to make a div on a site that holds quotes, and, when a user clicks the 'show/hide' button, the div is expanded, and also selects a random quote. I've managed to make it do all of this, but there's a few small problems. Firstly, if the user clicks to hide the div, it flashes one of the other quotes for a small time. Secondly, I can't seem to make
return false; (or
.preventDefault(); )work to prevent the scrolling to the top.
HTML:
- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="right">
<a href="#" class="showhidebutton">s/h</a>
<ul id="quotes">
<li>Quote 1</li>
<li>Quote 2</li>
<li>Quote 3</li>
</ul>
</div>
CSS:
- #right{position:fixed;top:10px;left:10px;width:150px;height:auto;}
#quotes, #quotes li{margin:0;padding:0;list-style:none;}
#quotes{width:250px;font-size:16px;line-height:120%;}
#quotes li{padding:20px;background:#e1e1e1;display:none;}
Jquery:
- $(document).ready(function(){
$("#quotes").hide();
$(".showhidebutton").click(function(e){
$("#quotes").toggle(200);
randomquote();
e.preventDefault();
});
});
this.randomquote = function(){
$("#quotes li").hide();
var length = $("#quotes li").length;
var ran = Math.floor(Math.random()*length) + 1;
$("#quotes li:nth-child(" + ran + ")").show();
};
$(document).ready(function(){
randomquote();
});
Any help would be *greatly* appreciated, thanks.