I have a cool piece of jQuery I’m working with – when I click the header links ‘Text 1’ or ‘Text 2’ some text appears below it. However, as well as this, I’d like to change the associated Image on click too.
Is this possible?
So clicking the link would reveal the text AND change the relevant image to http://placehold.it/100×150. It would always change to this specific image.
Here is a JSFiddle Demo : http://jsfiddle.net/hbfbS/
<!DOCTYPE html>
<!--[if lt IE 7 ]><html dir="ltr" lang="en-US" class="no-js ie ie6 lte7 lte8 lte9"><![endif]-->
<!--[if IE 7 ]><html dir="ltr" lang="en-US" class="no-js ie ie7 lte7 lte8 lte9"><![endif]-->
<!--[if IE 8 ]><html dir="ltr" lang="en-US" class="no-js ie ie8 lte8 lte9"><![endif]-->
<!--[if IE 9 ]><html dir="ltr" lang="en-US" class="no-js ie ie9 lte9"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html dir="ltr" lang="en-US" class="no-js"><!--<![endif]-->
<head>
<meta charset="UTF-8" />
<title>News</title>
<!-- jQuery -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function slideonlyone(thechosenone) {
$('.newboxes2').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).slideDown(200);
}
else {
$(this).slideUp(600);
}
});
}
</script>
<style type="text/css">
.newboxes2 { display: none;}
</style>
</head>
<body>
<div class="wrapper">
<div class="grid_4" style="float:left;width:300px">
<h2><a href="javascript:slideonlyone('newboxes1');" style="color:#455560!important;">Test 1</a></h2>
<h3 class="head"><img src="http://placehold.it/100x187" class="small" /></h3>
<div class="newboxes2" id="newboxes1">
<p> test 1 </p>
</div>
</div>
<div class="grid_4" style="float:left;width:300px">
<h2><a href="javascript:slideonlyone('newboxes2');" style="color:#455560!important;">Test 2</a></h2>
<h3 class="head"><img src="http://placehold.it/100x187" class="small" /></h3>
<div class="newboxes2" id="newboxes2">
<p>test 2 </p>
</div>
</div>
</div>
</body>
</html>
Would really appreciate some help with this. I’m sure it’s something simple.
http://jsfiddle.net/hbfbS/1/
Here is the amened function:
A quick explaination of what I changed:
I added this line,
jQuery(this).parent('.grid_4').children().find('img').attr('src', 'http://placehold.it/100x150');What it does is, gets the parent of the current item being clicked. Then gets all the children and finds the image tag within it and then updates the attribute ‘src’ with the new image url.
You may want select the img element better because this will currently change all images within the parent container to the new image source.