jquery change image source with html5 data attribute

custom-data-attribute, html, jquery

Solution

From the HTML5 spec :

All attribute names on HTML elements in HTML documents get ASCII-lowercased automatically

Use lowercase names :

var ImgSmall = $('img').data('imgsmall'),
    ImgMedium = $('img').data('imgmedium'),
    ImgLarge = $('img').data('imglarge'),
    img = $('img');

Problem

i want to change image source with html5 data attribute. I've tried many ways but still can't solve so far, for demonstration here is the code; HTML Markup: ``` <img src="http://placehold.it/300x250&text=Default%20Image" data-imgSmall="http://placehold.it/300x250&text=Small%20Image" data-imgMedium="http://placehold.it/300x250&text=Medium%20Image" data-imgLarge="http://placehold.it/300x250&text=Large%20Image" /> <button class="small">Small Image</button> <button class="medium">Medium Image</button> <button class="large">Large Image</button> ``` jQuery Code: ``` var ImgSmall = $('img').data('imgSmall'), ImgMedium = $('img').data('imgMedium'), ImgLarge = $('img').data('imgLarge'), img = $('img'); $('button').click(function () { if ($(this).hasClass("small")) { img.attr('src', ImgSmall); alert(ImgSmall); } if ($(this).hasClass("medium")) { img.attr('src', ImgMedium); alert(ImgMedium); } if ($(this).hasClass("large")) { img.attr('src', ImgLarge); alert(ImgLarge); } }); ``` But this code still not working, plz advice where I'm wrong, thanks in advance :)

Original source

Related problems