I’m trying to create an effect where if the user hovers the mouse over one of my li items, I show a few buttons that were hidden in the non-hovered state. Same kind of thing youtube is doing when you hover your mouse over comments. I’m trying this:
var gButtons = $(generateButtons());
function generateButtons() {
var html = "<span>Btn1</span><span>Btn2</span>";
return html;
}
$('#myList').delegate('li', 'hover', function(event) {
if (event.type == 'mouseover') {
var element = $(this);
gButtons.appendTo(element.children('.panelButtons'));
} else {
gButtons.remove();
}
});
<ul id='myList'>
<li>
<p>blah a</p>
<p class='panelButtons'></p>
<li>
<li>
<p>blah b</p>
<p class='panelButtons'></p>
<li>
...
</ul>
ok so my idea was that I create the gButtons element once at startup. Each li element gets an empty panel with class type ‘panelButtons’. Whenever the user hovers over an li element, I just append it to the currently hovered element’s empty ‘panelButton’ section.
I’m not sure if this will work because the order of messages [un-hover, hover] has to be consistent. I wanted to avoid generating the button markup for every single li item at page load, since I may have a large number of elements – it’d just be a lot of extra content.
Is this an ok way to go about it, any more optimal pattern?
Thank you
Unless there’s some specific reason why you want to append and remove on each mouseover/mouseout event, I guess I’d do like Derrick suggested, except that I’d have jQuery handle the events for you.
Like this: http://jsfiddle.net/dFFqZ/
It will be much more efficient to do it this way.
You could even simplify your code down to this: http://jsfiddle.net/dFFqZ/1/
EDIT: Added
event.type == 'mouseover'to.toggle()as noted by @Nick Craver.