Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image swapping with Jquery

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)');
    });             
});
like image 578
David Barker Avatar asked Oct 26 '11 16:10

David Barker


2 Answers

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

like image 159
Curtis Avatar answered Nov 01 '22 18:11

Curtis


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 :)

like image 24
will Avatar answered Nov 01 '22 17:11

will