Brandon
Brandon

Reputation: 2171

Javascript Swap Image on .this Click

I am trying to perform a simple image swap when an image is clicked. I am looping through a database so I have a bunch of "thumbs up" images. when a user clicks on one of the images, I would like that particular image to turn green. the two image names are "thumbs_up.png" and "thumbs_up_green.png"

I can get the image to disappear using ".this" but cannot figure out how to make the image swap. Any help would be great! Thank you!

Here is my script:

<script>
    function thumbTip(element){
        var name = element.name;
        $(element).hide();
    }
</script>

Here is my HTML:

<table width='100%' class='test'>
    <tr>
        <td><span class='test'>$p[first_name]</span></td>
        <td align='center'><span class='test'>$p[date_time]</span></td>
    </tr>
    <tr>
        <td width='87%'><span class='test2'>$p[tip]</span></td>
        <td width='13%' align='center'>
            <span class='test3'>
                <a href='#' onClick='thumbTip(this)'>
                    <img src='../images/thumbs_up.png' width='25' scalefit='1' />
                </a>
            </span>
        </td>
    </tr>
</table>

Upvotes: 2

Views: 204

Answers (3)

hark
hark

Reputation: 29

And here a solution in plain JS

I would suggest to swap the thumbs-image in two steps:

  1. Check which image is shown at the moment.
  2. Then change the image an proceed further code.

For example:

<script>
    function thumbTip(element){
        if(element.src == '../images/thumbs_up.png'){
            element.src = '../images/thumbs_up_green.png';

            //Further Code: (when thumb gets green) 

        }else{
            element.src = '../images/thumbs_up.png';

            //Further Code: (when thumb gets normal again) 

        }
    }

Note: May a absolute path to the img would be better in this case.

Upvotes: 0

lewis
lewis

Reputation: 253

In the below you would have two css classes with the images named thumbs-up and thumbs-up-green and each time you are just toggling which one is on the element.

function thumbTip(element){
    var el = $(element);

    el.toggleClass("thumbs-up");
    el.toggleClass("thumbs-up-green");
}

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

As you have tagged jQuery . Will give a jQuery solution..

$('.test3 a').on('click', function(e) {
    e.preventDefault();
    var $img = $(this).find('img');

    $img.attr('src', function(_,s) {
         return s.indexOf('thumbs_up_green') > -1 ? '../images/thumbs_up.png'
                                                  : '../images/thumbs_up_green.png'
    });
});

Just swapping out the src attribute of the image based in the condition.

Upvotes: 2

Related Questions