0

I'm trying to get this to point to each img inside a function inside an object method, like so

var responsiveImageSwap = (function(){
    return {
        init : function(){
            $.each('img', function(){
                var width     = $(window).width(),
                    _this     = this, 
                    alert(_this.attr('src'))
            })
        }
    }
})();
responsiveImageSwap.init();

But it is referencing the object and not the img, how do I reference the image?

2
  • 4
    Why not $('img').each(…? Also, you don't want to compute the viewport width inside a loop. Commented Jul 29, 2013 at 14:18
  • ahh good point about width... Commented Jul 29, 2013 at 14:20

2 Answers 2

8

$.each is for looping over collections. What you are doing is looping over the letters in the string 'img'.

You want to use .each; this is for jQuery objects.

$('img').each(function(){
    var width = $(window).width(),
        // this is a DOM element, we need to make it a jQuery object
        _this = $(this), 
     alert(_this.attr('src'))
});
Sign up to request clarification or add additional context in comments.

6 Comments

@Virus721: I was just using the code the OP had. It's not very useful here, but it may be if he uses closures inside the callback.
@RocketHazmat Your code won't work. this refers to the IMG element which does not have a .attr() method.
@ŠimeVidas: Yeah... I just noticed that. >.<
@ŠimeVidas: I haven't finished my coffee yet, sue me. I fixed it. :-)
@RocketHazmat Hehe, I'm drinking my morning coffee right now as well. (The weird part is that it's 4:30 PM where I live.)
|
3

This?

return {
    init: function () {
        var vw = $(window).width(); // viewport width

        $('img').each(function () {
            var $img = $(this);

            // Do stuff with $img, e.g. retrieve $img.attr('src')
        });
    }
};

1 Comment

Thanks, you answered the question first with your comment so will accept this (no pun intended)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.