Roy Barber
Roy Barber

Reputation: 312

Add active class to jQuery image swap code

i'm using some jquery code to swap an image on click to a new source, but i need it to add the class of "active" on click and remove it when another elemnt is clicked, heres the jquery and html

html

<a class="steplink" href="http://placebox.es/600/500/ff0000/ffffff/Step1/">Step1</a>
<a class="steplink" href="http://placebox.es/600/500/ff0000/ffffff/Step2/">Step2</a>
<a class="steplink" href="http://placebox.es/600/500/ff0000/ffffff/Step3/">Step3</a>
<div id="stepimgwrap">
    <img src="http://placebox.es/600/500/ff0000/ffffff/Step1/" alt="Main Image" id="stepimg"/>
</div>

jQuery

$('.steplink').live("click", function() {
    $('#stepimg').hide();
    $('#stepimgwrap').css('background-image', "url('../img/ajax-loader.gif')");
    var i = $('<img />').attr('src',this.href).load(function() {
        $('#stepimg').attr('src', i.attr('src'));
        $('#stepimgwrap').css('background-image', 'none');
        $('#stepimg').show();
    });
    return false; 
});

Thanks in advance

Upvotes: 0

Views: 1714

Answers (5)

here including the CLICK event

$(document).ready(function(){
    $('.steplink').click(function(){
        $('#stepimgwrap').toggleClass('active');
        return false;
       //
    });
});

Upvotes: 1

Emil A.
Emil A.

Reputation: 3445

$('.steplink').click(function(e) {
  e.preventDefault();
  $('.steplink').removeClass('active');
  $(this).addClass('active');
  var href = $(this).attr('href');
  $('#stepimg').attr('src', href);
});

This adds active class to current anchor and changes the src of the image.

Upvotes: 0

Jai
Jai

Reputation: 74738

Try this one:

http://jsfiddle.net/WN73Q/

$('.steplink').live("click", function() {
$('#stepimg').hide();

$(this).addClass('active'); // <---------------add active class to link clicked 
$(this).siblings().removeClass('active'); // <-----remove the other link active class

$('#stepimgwrap').css('background-image', "url('../img/ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
    $('#stepimg').attr('src', i.attr('src'));
    $('#stepimgwrap').css('background-image', 'none');
    $('#stepimg').show();
});
   return false; 
});

Upvotes: 2

SeanCannon
SeanCannon

Reputation: 77986

Normally I'd use siblings() but your DOM doesn't isolate all the steplinks

$('.steplink').live("click", function() {

    /* .. blah blah */
    $('.steplink').removeClass('active');
    $(this).addClass('active');
});

Upvotes: 0

hereandnow78
hereandnow78

Reputation: 14434

you want to do it on the stepimg?

$('#stepimg').toggleClass('active');

Upvotes: -1

Related Questions