0

I want to change the src attribute of img inside of my span with id="slider_arrow",

<span id="slider_arrow">
      <img />
</span>

each time my jquery function runs:

    $("#0").click(function () {
           /*Rest of the function*/
        var arrow = document.getElementById('slider_arrow');
        /*I want to add different slider_arrow's sprite each time i call this                           function*/            
    });

CSS:

.red_arrow_sprite{
    width:25px;
    height:12px;
    background:url("/Images/arrows.png") 0 0px;
}

.yellow_arrow_sprite{
    width:25px;
    height:12px;
    background:url("/Images/arrows.png") -26px 0px;
}

.black_arrow_sprite{
    width:25px;
    height:12px;
    background:url("/Images/arrows.png") -51px 0px;
}

My CSS Sprite file has 75px width and 12px of height. Each picture has 25px/12px. The questions are: 1) Do I have correctly written CSS rules?
2) What I need to use to change src of img inside of span?

Thanks!

Fiddle: http://jsfiddle.net/vtkppwuc/3/

2
  • I can post some code to change the src attribute of your img, but are you sure that's what you need? Because that's not a sprite at all. And if that's what you want, I don't understand what's the point of all your css. A CSS background image is NOT the same thing as the src attribute of an image. Commented Dec 22, 2014 at 20:00
  • I understand, thanks :) I thought it will have the same effect:) Commented Dec 22, 2014 at 20:04

2 Answers 2

1
$("#0").click(function () {
    var classes = ['red_arrow_sprite','yellow_arrow_sprite','black_arrow_sprite'];
    var $span = $('#slider_arrow');
    $span.attr('class', (classes[($.inArray($span.attr('class'), classes)+1)%classes.length])); 
});

DEMO: http://jsfiddle.net/vtkppwuc/6/

Sign up to request clarification or add additional context in comments.

2 Comments

this.className should be replaced by $span.attr('class')
Your answer is a pretty nifty trick. I'll probably use it myself.
0

Remove the image inside span and use jQuery for setting the css class to your Slider, try this code

<span id="slider_arrow" class="red_arrow_sprite">         
</span>

$("#0").click(function () {
    var item = $('#slider_arrow');
    if (item.hasClass('red_arrow_sprite')){
       item.removeClass('red_arrow_sprite').addClass('yellow_arrow_sprite');
    } else if (item.hasClass('yellow_arrow_sprite')){
       item.removeClass('yellow_arrow_sprite').addClass('black_arrow_sprite');
    } else {
       item.removeClass('black_arrow_sprite').addClass('red_arrow_sprite');           
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.