How to bind data-src attribute for the image in the post using jquery?

I’m trying to use foresight.js for responsive image in the wordpress blog. For that I have to add data-src attribute in the place of src in the <img> tag.

Or I have to get the url from the image in the post and need to bind my new tag near the old <img> tag and wrap that old <img> tag in <noscript> tag. I don’t have any idea how to do it.

Read More

Basically it must looks like this:

<img data-src="http://foresightjs.appspot.com/dynamic-images/px-wright-flyer.jpg" data-aspect-ratio="auto" class="fs-img">

<noscript>
    <img src="http://foresightjs.appspot.com/dynamic-images/1024px-wright-flyer.jpg">
</noscript>`

Related posts

Leave a Reply

1 comment

  1. Using jQuery:

    $('img').each(
        function(i,el){
            var that = $(el);
            $('<img />').attr('data-src', el.src).insertBefore(el);
            that.wrap('<noscript />');
        });
    

    JS Fiddle demo.

    Or, slightly differently:

    $('img').each(
        function(i,el){
            $(el).wrap('<noscript />').clone().insertBefore(el.parentNode).data('src', el.src).removeAttr('src');
        });​
    

    JS Fiddle demo.

    Adjusted to add the class:

    $('img').each(
        function(i,el){
            $(el).wrap('<noscript />').clone().insertBefore(el.parentNode).data('src', el.src).removeAttr('src').addClass('newClass');
        });​
    

    JS Fiddle demo.

    But, as noted, the noscript is entirely unnecessary and you may as well simply adjust the image with JavaScript (since if JavaScript is disabled the image will remain unchanged):

    $('img').each(
        function(i,el){
            $(el).attr('data-src', el.src).removeAttr('src').addClass('newClass');
        });​
    

    JS Fiddle demo.
    References: