I have searched the forum for one particular issue, yet all the solutions I found do not work for my problem.
I have an image on the left hand side. On the right han
jsBin demo
mtl.png
and contact.png
and use:
<div>
<div class="button" id="mtl">Mtl</div>
</div>
<div>
<div class="button" id="contact">SF</div>
</div>
$('.button').click(function(){
var idToSRC = 'images/'+ this.id +'.png';
$('#picture').attr('src', idToSRC);
});
While the above will not be user friendly cause there's some latency in loading new images...
A better approach would be to use a single (so-called) sprite image, containing all your desired images, set it as a DIV background image and changing that DIV's "background-position" on click!
Store your desired -left position into a data attribute:
<div id="picture"></div>
<div>
<div class="button" data-bgpos="68" id="mtl">Mtl</div>
</div>
<div>
<div class="button" data-bgpos="100" id="contact">SF</div>
</div>
CSS:
#picture{
width:25px;
height:25px;
background:url(/images/sprite.png) no-repeat;
}
Retrieve that data and move the packgroundPosition:
$('.button').click(function(){
var bgpos = $(this).data('bgpos');
$('#picture').css({backgroundPosition: -bgpos+' 0'})
});
Instead of adding event listeners to each link class you can just use it as an inline function on any link
function changeurl(theurl){
$('.myimage').attr('src', theurl);
}
https://jsfiddle.net/rabiee3/ftkuub3j/
It all looks good for the second version, make sure you are wrapping your DOM calls in the document ready function, which can be written as...
$(document).ready(function() {
...
});
Or...
$(function() {
...
});
So you get...
$(function() {
$('#mtl').click(function(){
$('#picture').attr('src', 'images/short.png');
});
});
Your second attempt is correct. Here is the working jsFiddle: http://jsfiddle.net/MEHhs/
So the code should be:
html:
<div id="picture_here">
<img src="http://www.sbtjapan.com/img/FaceBook_img.jpg" id="picture"/>
</div>
<div id="about">
<div id="mtl">Mtl</div>
</div>
<div id="about_2">
<div id="contact">SF</div>
</div>
js:
$('#mtl').click(function(){
$('#picture').attr('src', 'http://profile.ak.fbcdn.net/hprofile-ak-ash3/41811_170099283015889_1174445894_q.jpg');
});
I've added some existing images found on google.
The second one works fine but you have to use explicit path instead of relative path:
$('#mtl').click(function(){
$('#picture').attr('src', '/images/short.png');
});