Search code examples
jqueryimageaccessibilityalt-attribute

How to change alt attribute of an image several times with jQuery?


This question completes the first one that I asked here about how to change an image on click using jQuery.

I forgot to say (even if I edited my post later) that I'm looking for a way to have a different alt attribute each time an image is changed by click.

(This is for better accessibility and SEO optimization.)

Here is the actual html code thanks to altCognito:

<img id="radio_btn1" src="originalimage1.jpg" />
<br />
  <input type="radio" name="radio_btn1" value='image1.jpg' />
  <input type="radio" name="radio_btn1" value='image2.gif' />
  <input type="radio" name="radio_btn1" value='image3.png' />
  <input type="radio" name="radio_btn1" value='image4.jpeg' />

And the jquery:

imgFldr = 'images/nameofthesubfolder/';
$("input[type='radio']").click(function() {
   $('#'+this.name).attr('src', imgFldr+this.value).attr('alt', 'newattribute');
});

It can be edited at jsbin.


Solution

  • Well... SEO and content manipulated by Javascript shouldn't be in the same post to begin with. Whatever you do, if you use Javascript to display your content, you're hurting your search engine visibility.

    That said, you could either have those images in a hasharray (imagename->alt) and get the alt from there, or you could put the alt in the value of the radio concatenated to the filename with a separator like | and then parse them out in the function you use to display the image.

    ...so in short either:

    <img id="radio_btn1" src="originalimage1.jpg" />
    <br />
      <input type="radio" name="radio_btn1" value='image1.jpg|Image 1' />
      <input type="radio" name="radio_btn1" value='image2.gif|Image 2' />
      <input type="radio" name="radio_btn1" value='image3.png|Image 3' />
      <input type="radio" name="radio_btn1" value='image4.jpeg|Image 4' />
    

    +

    imgFldr = 'images/nameofthesubfolder/';
    $("input[type='radio']").click(function() {
       var strarr = this.value.split('|');
       if(strarr.length < 2) return;
       $('#'+this.name).attr('src', imgFldr+strarr[0]).attr('alt', strarr[1]);
    });
    

    ...or:

    <img id="radio_btn1" src="originalimage1.jpg" />
    <br />
    <input type="radio" name="radio_btn1" value='image1.jpg' />
    <input type="radio" name="radio_btn1" value='image2.gif' />
    <input type="radio" name="radio_btn1" value='image3.png' />
    <input type="radio" name="radio_btn1" value='image4.jpeg' />
    

    +

    imgFldr = 'images/nameofthesubfolder/';
    var imagesarr = {'image1.jpg': 'Image 1', 'image2.gif': 'Image 2','image3.png': 'Image 3','image4.jpeg': 'Image 4'}
    $("input[type='radio']").click(function() {
       $('#'+this.name).attr('src', imgFldr+this.value).attr('alt', imagesarr[this.value]);
    });