Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn this jquery into a function?

Tags:

jquery

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");
});
like image 425
josh Avatar asked Dec 27 '22 20:12

josh


2 Answers

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+.

like image 181
Jamon Holmgren Avatar answered Jan 10 '23 06:01

Jamon Holmgren


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'));
});
like image 29
DarthJDG Avatar answered Jan 10 '23 06:01

DarthJDG