Derrick Morton
Derrick Morton

Reputation: 3

Swapping Images in menu using JavaScript

First time posting here so be gentle. I'm trying to create a menu for a web site using javascript. I want to click on an item in my menu and swap images. This part is easy and working fine. Where I'm falling down is I want the previous items in my menu to revert back to their original source image. This would be simple if they all used the same images, but they all have their own unique images. Hope I'm explaining myself ok.

Upvotes: 0

Views: 75

Answers (1)

Lexi
Lexi

Reputation: 1730

You can use the $.data function to store information in an element for later retrieval.

Before you change the image's src, you store the current src so that you can then use it to restore the src when you want to change it back.
Example:

// When a menu item's link is clicked
$('.menu-item a').on('click', function(e) {
  // Prevent the link firing
  e.preventDefault();
  // Grab the menu item
  var self = $(this).parent();

  // find our image
  var img = self.find('img');
  // make sure we're not double changing
  if (!img.hasClass('changed')) {
    // Store our existing src in a the jQuery data
    img.data('original-src', img.attr('src'));
    // Set a new src
    img.attr('src', 'http://lorempixel.com/g/20/20/');
    // Add a class so we know what's changed
    img.addClass('changed');
  }

  // Search for existing changed images
  self.siblings().find('img.changed').each(function() {
    var img = $(this);
    // Remove the changed tag
    img.removeClass('changed');
    // Restore the src
    img.attr('src', img.data('original-src'));
  });

});
#my-menu {
  list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="my-menu">
  <li class="menu-item">
    <a href="#">
      <img src="http://placehold.it/20x20" role="presentation" />
      One
    </a>
  </li>
  <li class="menu-item">
    <a href="#">
      <img src="http://placehold.it/20x20" role="presentation" />
      Two
    </a>
  </li>
  <li class="menu-item">
    <a href="#">
      <img src="http://placehold.it/20x20" role="presentation" />
      Three
    </a>
  </li>
</ol>

Upvotes: 1

Related Questions