I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the <a href>
tag somewhere.
html code
<img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
<li><a href="linkpage.htm" class="newslink1">Link 1</a></li>
<li><a href="linkpage.htm" class="newslink2">Link 2</a></li>
<li><a href="linkpage.htm" class="newslink3">Link 3</a></li>
</ul>
jquery
$('a.newslink1').bind('mouseover', function() {
$('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
$('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
$('img#storyimg').attr("src", "3.png");
});
Add a data attribute called data-src:
<a href="linkpage.htm" class="newslink" data-src="1.png">Link 1</a>
jQuery:
$("a.newslink").bind("mouseover", function() {
$("img#storyimg").attr("src", $(this).data("src"));
});
Works with jQuery 1.5+.
Change your HTML markup and put the desired image in a data attribute, and change your class to a generic newslink
:
<img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
<li><a href="linkpage.htm" class="newslink" data-img="1.png">Link 1</a></li>
<li><a href="linkpage.htm" class="newslink" data-img="2.png">Link 2</a></li>
<li><a href="linkpage.htm" class="newslink" data-img="3.png">Link 3</a></li>
</ul>
Then do a generic event using that data attribute:
$('a.newslink').bind('mouseover', function(){
$('img#storyimg').attr("src", $(this).data('img'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With