Juliette Dupuis
Juliette Dupuis

Reputation: 1037

jQuery: Rotate images using a button

I am trying to rotate 2 images. For now, I have this code:

$('img').on({
  'click': function () {
    var src = ($(this).attr('src') === 'img1_on.jpg') ? 'img2_on.jpg' : 'img1_on.jpg';
    $(this).attr('src', src);
  }
});

It works perfectly: when I click on an image, the other appears. What I would like to do is exactly the same, but using a button to rotate the images, and not click on the image itself.

Upvotes: 1

Views: 319

Answers (2)

Roland Mai
Roland Mai

Reputation: 31097

Just replace the img part with the class name of your button:

<input type="button" class="button" />

$('.button').on({
    'click': function() {
        var src = ($(this).attr('src') === 'img1_on.jpg') ? 'img2_on.jpg' : 'img1_on.jpg';
        $('img').attr('src', src);
    }
});

Upvotes: 0

Bruno Vieira
Bruno Vieira

Reputation: 3904

html

<button id="imageSwitcher">Click to switch images</button>

javascript/jquery

$("#imageSwitcher").click(function() {
   var src = ($('img').attr('src') === 'img1_on.jpg')
    ? 'img2_on.jpg'
    : 'img1_on.jpg';
   $('img').attr('src', src);
 });

The script assumes that you have one single image on your page, to change for a specific image, do the following:

html

<img id="imgSwitched" src="img1_on.jpg"/>
<button id="imageSwitcher">Click to switch images</button>

javascript/jquery

$("#imageSwitcher").click(function() {
   var src = ($('#imgSwitched').attr('src') === 'img1_on.jpg')
    ? 'img2_on.jpg'
    : 'img1_on.jpg';
   $('#imgSwitched').attr('src', src);
 });

Upvotes: 2

Related Questions