Search code examples
jqueryimageattributessrcjquery-lazyload

use variable inside src attribute with jquery


I use B-Lazy plugin (http://dinbror.dk/blog/blazy/) on a website projet. I would like to load different image in terms of windows width :

If window width < 420px, the plugin accepts to load an img whose 'data-src' is remplace by 'data-src-small'.

So, I would like to get the data-src image url and add to the end '-228x170' just before '.jpg' like that :

<img data-src="img-name.jpg" > become <img data-src-small="img-name-228x170.jpg" >

here my code : `

$('img').addClass('b-lazy');

$("img.b-lazy").each(function() {       

         $(this).attr("data-src",$(this).attr("src"));
         $(this).attr('src','data:trans.gif');

        var src = $(this).attr('data-src');
        $(this).attr('src', 'src + -228x170.jpg' ); //here my mistake

 });

`


Solution

  • here you go, just change where the quote is, and remove the initial extension:

    var src = $(this).attr('data-src').replace('.jpg', '');
    $(this).attr('src', src + '-228x170.jpg' );
    

    Per question in comments:

    var src = $(this).attr('data-src').replace('.jpg', '');
    var specialChars = ('fooo'); //this can be set dynamically
    
    $(this).attr('src', src + '-228' + specialChars  + '.jpg' );
    

    HTH, -Ted