I’m new to jQuery and I’m trying to realize a very simple tooltip just to learn how jQuery works.
After googling this is what I did:
jQuery:
$(document).ready(function(){
$("#foo1").mouseover(function(e){
var x = e.pageX - $("#container").offset().left;
var y = e.pageY - $("#container").offset().top;
$('#div1').css({'top':y,'left':x}).show();
});
$("#foo1").mousemove(function(e){
var x = e.pageX - $("#container").offset().left;
var y = e.pageY - $("#container").offset().top;
$('#div1').css({'top':y,'left':x});
});
$("#foo1").mouseout(function(){
$('#div1').hide();
});
})
HTML:
<div style="width: 200px; border: 1px black solid; position: relative;">
Something here
</div>
<div id="container" style="width: 300px; border: 1px black solid; position: relative;">
<a id="foo1" href="javascript:void(0);">[hover me]</a>
<div id="div1" class="tt">Content goes here.</div>
<a id="foo2" href="javascript:void(0);">[hover me too!]</a>
<div id="div2" class="tt">I'm not working :(</div>
</div>
I used var x = e.pageX - $("#container").offset().left; because I had problems when #div1 was inside a div with position: relative;
Everything works, but what if I add other links?
I would like to pass #foo1 and #div1 (and eventually #container, but actually I really don’t need it) as parameters but the fact is that I have absolutely no idea on how to do this.
I tried searching here, I found this: JQuery, Passing Parameters
So I think that maybe I can do something like:
function doStuff(param1, param2) {
$(param1).mouseover(function(e){
var x = e.pageX - $("#container").offset().left;
var y = e.pageY - $("#container").offset().top;
$(param2).css({'top':y,'left':x}).show();
});
//etc etc
}
But I wouldn’t know how to recall this function in HTML: in javascript I would have done something like onmouseover="doStuff('foo1', 'div1')", but I don’t really know what to do with jQuery 😐
EDIT:
This is the code that generates the divs:
foreach ($colors_array as $key => $value) {
echo "<div id='foo" . $key . "'>";
// something else
// according to some condition, I will decide whether to
// call or not the function doStuff for this div.
echo "</div>";
}
Here’s another solution, find element next to a having tt class :
Your html :