I have
<script>
//some jQuery code is here to see img1.jpg if hovered on .img1;
//img2.jpg if hovered on .img2;
//img3.jpg if hovered on .img3
</script>
<div id="imgs">
<img src="img1.jpg" alt="">
<img src="img2.jpg" alt="">
<img src="img3.jpg" alt="">
</div>
<ul id="my-ul">
<li><a href="#" class="img1">hover to see image1</a></li>
<li><a href="#" class="img2">hover to see image2</a></li>
<li><a href="#" class="img3">hover to see image3</a></li>
</ul>
I want the corresponding image to appear in the div if hovered and see nothing in a div, if not hovered.
How to make it using jQquery?
I'd suggest:
$('li a').hover(
function(){
var i = $(this).parent('li').index();
$('#imgs img:eq(' + i + ')').show();
},
function(){
var i = $(this).parent('li').index();
$('#imgs img:eq(' + i + ')').hide();
});
JS Fiddle demo.
$('#my-ul a').on('mouseenter mouseleave', function(e) {
$('#imgs img').eq($(this).parent('li').index()).toggle(e.type==='mouseenter');
});
FIDDLE
You could add an attribute to your hrefs, like
<a href="#" title="img1.jpg" onmouseover="void(hoverImg(this));">asdf</a>
And add some simple Script like
function hoverImg(_src)
{
// Set this to true in order to troubleshoot the script
var _debugThis = false;
try
{
var _iSrc = _src.getAttribute('title');
var _iTrg = document.getElementById('imgs');
var _img=document.createElement('img');
_img.src=_iSrc;
// other attributes for your image
_iTrg.innerHTML=null;
_iTrg.appendChild(_img);
// inject unhover trigger
_iSrc.onmouseout=function(){void(document.getElementById('imgs').innerHTML=null);}
}
catch (_e) { if (_debugThis) { alert(_e); } }
}