I am very new to Jquery so please excuse this noobie question. I am trying to swap a background image of an <h1>
element when a user clicks on the corresponding hyperlink. The <a>
tags are generated dynamically and there can be 'n' quantity of them at any time depending on how many images are set in a SQL table.
My HTML is:
<div id="feature-image">
<h1><span>A random heading</span></h1>
</div>
<div id="feature-links">
<a class="a1" href="#">1</a>
<a class="a2" href="#">2</a>
<a class="a3" href="#">3</a>
</div>
The <span>
tags are set to display:none
I've written this Jquery statement to run when a user clicks on a hyperlink in the #feature-links div. I was attempting to set the var image
to the name of the <a>
tags class (a1, a2, a3) etc. and then change the CSS background image property of the <h1>
using the image
var as part of the .jpg.
url.
<script>
$(function(){
$('#feature-links a').click(function(){
var image = $(this).attr("class","");
$('#feature-image h1').css('background-image','url=(\'main_' + image + '.jpg\')');
});
});
</script>
all my images are named "main_a1.jpg", "main_a2.jpg" and so on...
I can't see what I am doing wrong or whether what I am attempting to do (grab class names etc. in vars) is actually good practice or not... some help would be really appreciated.
Thanks in advance!
EDIT:
Jquery code after edits:
$(function(){
$('#feature-links a').click(function(){
var image = $(this).attr('class');
$('#feature-image h1').css('background-image','url(images/main_' + image + '.jpg)');
});
});
Change line to:
var image = $(this).attr("class");
I believe specifying 2 parameters to the .attr()
function is used for changing the attribute value. Therefore in your case, it would change the class to ""
.
Specifying one parameter will return the value of the class
A better way, instead of using the class would be to set the href.
For example:
$('#feature-links a').click(function(e){
$('#feature-image h1').css({
'background-image': 'url(' + $(this).attr('href') + ')'
});
e.preventDefault(); // Stops the standard link behaviour
});
Then your links would simply link directly to the background image:
<a href="/path/to/image.jpg">1</a>
Hope that helps :)
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