user2124044
user2124044

Reputation: 25

Change source of image

I want to use an image called #MapButtonImage as a 'button' so when somebody clicks on it, a div is shown and the source of the #MapButtonImage changes. I have made it so that it shows the div as follows:

$(window).load(function(){
  $("img#MapButtonImage").click(function(){
  $("div.MapMain").toggleClass('MapMainShow');
  });
});

When I click the button at the moment, it changes the class of the map div to display:block, then the second click goes back to the default of display:none.

But I can't seem to make it change the source of the image using jQuery. I followed a guide using a toggle of two functions with the source as the two images I want, but it only works on an earlier version of jQuery and not the latest.

The image #MapButtonImage has original source "ShowMapButton.jpg" and I want to change it to "HideMapButton.jpg" when it is clicked on, then back to "ShowMapButton.jpg" when clicked again.

The aim is to have it as a toggle to show a Map div below it and the image reflects the action that the button will then take (Show or Hide).

Any help would be greatly appreciated, I am quite new to this and can't understand why it doesn't work in the latest version but does in a previous.

Upvotes: 1

Views: 115

Answers (1)

Philippe Boissonneault
Philippe Boissonneault

Reputation: 3949

Try this:

$(window).load(function(){
  $("img#MapButtonImage").click(function(){
  $("div.MapMain").toggleClass('MapMainShow');

  if($("div.MapMain").hasClass('MapMainShow')) {
      $(this).attr('src', 'HideMapButton.jpg');
  } else {
      $(this).attr('src', 'ShowMapButton.jpg');
  }
  });
});

Upvotes: 1

Related Questions