Pietro Coelho
Pietro Coelho

Reputation: 2072

Why change data-attribute on resize doesnt work in javascript/jquery

I'm trying to change the size of facebook comment div when I resize the window. This is my code:

$(document).ready(function(){
    var $window = $(window);

        function checkWidth() {
            var windowsize = $window.width();

            if (windowsize < 768) {
                $(".fb-comments").attr("data-width","767");

            }
        }

        checkWidth();

        $(window).resize(checkWidth);
    })

This code works on load page. If i load the page with my browser resized less than 768px wide the code works and the data-width of the div becomes 767. But if load the page in normal width screen and resize it doesn't. Why?

Upvotes: 0

Views: 642

Answers (2)

mohamedrias
mohamedrias

Reputation: 18566

$(document).ready(function(){
            var $window = $(window);

            var windowsize = $window.width();

            if (windowsize < 768) {
               var fbcontent = ' <div class="fb-comments" data-href="http://stackoverflow.com" data-num-posts="2" data-width="767px"></div>';

               $('.fb-comments').html(fbcontent);

            }
        }
    });

I know that it's a hack to resize the facebook comments. If you just want your facebook comments to be responsive for different screen resolutions then this trick will work just find. :)

Upvotes: 0

isherwood
isherwood

Reputation: 61063

data-width is an attribute that Facebook's script reads and acts on during render. Without triggering that script's event, there's no reason to think that resize will happen because the browser ignores data attributes. Instead, use CSS.

if (windowsize < 768) {
    $(".fb-comments").width("767");
}

http://jsfiddle.net/isherwood/vmnnc/

Upvotes: 4

Related Questions