1

I want to change image source according to a letter button that I click on. I guess that I need to use regular expression, but I am not sure how exactly it should look like.

<img id="logo_layer2" src="images/logo/logo_compass_a_layer2_red.png">
<ul id="letters">
    <li>A</li>
    <li>B</li>
    <li>C</li>
...
</ul>

"a_layer2" part should change to "b_layer2", "e_layer2" and so on.

events: {
    "click #letters li" : "change_letter"
},

change_letter: function(e) {
    var letter = $(e.target).text();       
    var newimg = /images\/logo\/logo_\w*_\w{1}_layer\d_\w*.png/.replace((/\w{1}/,letter));
    $("#logo_layer2").attr("src",newimg);
},

http://jsfiddle.net/uLqBY/

2 Answers 2

1

Try

fiddle Demo

$('#letters li').click(function(){
    var txt =$(this).text().toLowerCase();
    $('#logo_layer2').attr('src',function(_,old_src){
        return old_src.replace(/_\w_/g,'_'+txt+'_');
    });
});


fiddle Demo

$('#letters li').click(function(){
    var txt =$(this).text().toLowerCase();
    $('#logo_layer2').prop('src',function(_,old_src){
        return old_src.replace(/_\w_/g,'_'+txt+'_');
    });
});

.prop()

Read .prop() vs .attr()

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

5 Comments

Thanks! It works, but it's just not getting $(this).text() value.
As the new src it returns "images/logo/logo_compass__layer2_red.png"
Yes, I just wonder when I click on "B", why it returns "images/logo/logo_compass__layer2_red.png", when your code should change it to "images/logo/logo_compass_b_layer2_red.png".
Failed to load resource: the server responded with a status of 404 (Not Found) 127.0.0.1/images/logo/logo_compass__layer2_red.png
I changed it to var txt = $(e.target).text().toLowerCase(); Now it works.
0

To improve on the regex, you can utilise positive lookbehind and lookaheads as follows:

(?<=images\/logo\/logo_\w*_)\w{1}(?=_layer\d_\w*.png)

This will match simply the letter that you intend to change, in this case it is the 'a' in the src.

As for the jquery/js, I don't know.

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.