Search code examples
javascripthtmlprototypejs

Change child image source using prototype js


How to change the icon path while click on parent link using prototype?

<a onclick="toggleAmenity('park'); return false;" href="#">
    <input type="image" id="parks_button" src="/images/amenities/icon_parks.gif" name="commit">
</a>

Solution

  • There are about a million ways to skin this cat, but this might give you some ideas using some Prototype stuff.

    Instead of 'amenity' I'm using image size. Kinda confusing, but I wanted to show a visual change on click. I'd strongly advise against using onclick attributes for this type of thing (or most any other type of thing).

    http://jsfiddle.net/gSfmL/

    <p>
      <a data-toggle-amenity='64' href="#">
        <input type="image" id="parks_button" src="http://www.google.com/images/icons/product/chrome-128.png" name="commit">
      </a>
    </p>
    
    <p>
      <a href="#">This anchor won't fire</a>
    </p>​
    

    .

    document.on('click', 'a[data-toggle-amenity]', function(event, element) {
      var amenityToggleType = element.readAttribute('data-toggle-amenity');
      element.down('input').writeAttribute({src: 'http://www.google.com/images/icons/product/chrome-' + amenityToggleType + '.png'});
      element.writeAttribute('data-toggle-amenity', null); // removes the attribute
    });​