4

I have a gallery of three Grids with images. The grid sizes changes depending on the screen size, and I have achieved that using Media-Query - ie, on desktop the grid's width will be 33% to make three columns view next to each other, and on tablet it will be 50% to make two columns view, and on phone it will be a 100% for each grid making one column view.

The reason I did this is to create a tiled gallery with images of different heights - and if I did it the normal way it will generate White-empty-spaces when floating.

So to fix this problem, and with the help of few members on this website, we have created a JavaScrip function that will MOVE all of the images that are inside Grid3 equally to Grid1 & Grid2 when screen size is tablet, so we get rid of the third grid making a view of fine two columns. Everything is working great!

Now, the problem is - on Chrome & IE - The function is being fired before its time for some reason that I need your help to help me find it! Please try it your self here: [http://90.195.175.51:93/portfolio.html][2]

Slowly on Chrome or IE - (try it on Firefox as well) - try to re-size the window from large to small, you will notice that BEFORE the top header changes to be a responsive Header (which indicate that you are on a small screen) the images have been sent to Grid1 and Grid 2! but a few px before the time. As on the function it says to fire it on <770.

Hope my question is clear enough for you to help me solve this issue which is stopping me from launching my website. Thanks.

Here is the JavaScrip:

//Gallery Grid System//
var testimonial = $(".testimonial, .galleryItem", "#grid3");
(function () {
    $(document).ready(GalleryGrid);

    $(window).resize(GalleryGrid);
})(jQuery);

function GalleryGrid() {
    var grid3 = $('#grid3');
    var width = $(window).width();
    if (width < 1030 && width > 770) {
        var grid1 = $('#grid1');
        var grid2 = $('#grid2');

        for (var i = 0; i < testimonial.length; i++) {
            if (i < testimonial.length / 2) {
                grid1.append(testimonial[i]);
            } else {
                grid2.append(testimonial[i]);
            }
        }
    } else {
        grid3.append(testimonial);
    }
}

Note: The following is the whole page with all the functions:

 $(document).ready(function () {

     //Prevent clicking on .active links
     $('.active').click(function (a) {
         a.preventDefault();
     });


     //Allow :active on touch screens
     document.addEventListener("touchstart", function () {}, true);


     //Hide toolbar by default
     window.addEventListener('load', function () {
         setTimeout(scrollTo, 0, 0, 0);
     }, false);


     //Scroll-up button
     $(window).scroll(function () {
         if ($(this).scrollTop() > 100) {
             $('.scrollup').fadeIn();
         } else {
             $('.scrollup').fadeOut();
         }
     });

     $('.scrollup').click(function () {
         $("html, body").animate({
             scrollTop: 0
         }, 600);
         return false;
     });


     //StickyBox
     $(function () {
         $.fn.scrollBottom = function () {
             return $(document).height() - this.scrollTop() - this.height();
         };
         var $StickyBox = $('.detailsBox');
         var $window = $(window);

         $window.bind("scroll resize", function () {
             var gap = $window.height() - $StickyBox.height() - 10;
             var footer = 288 - $window.scrollBottom();
             var scrollTop = $window.scrollTop();

             $StickyBox.css({
                 top: 'auto',
                 bottom: 'auto'
             });

             if ($window.width() <= 770) {
                 return;
                 $StickyBox.css({
                     top: '0',
                     bottom: 'auto'
                 });
             }

             if (scrollTop < 50) {
                 $StickyBox.css({
                     bottom: "auto"
                 });

             } else if (footer > gap - 100) {
                 $StickyBox.css({
                     top: "auto",
                     bottom: footer + "px"
                 });

             } else {
                 $StickyBox.css({
                     top: 80,
                     bottom: "auto"
                 });
             }
         });
     });


     //Change items location depending on the width of the screen//
     $(function () { //Load Ready

         function myFunction() {
             var insert = $(window).width() <= 770 ? 'insertBefore' : 'insertAfter';
             $('#home-sectionB img')[insert]($('#home-sectionB div'));
             $('#home-sectionD img')[insert]($('#home-sectionD div'));
         }
         myFunction(); //For When Load
         $(window).resize(myFunction); //For When Resize
     });


     //Contact Form//
     $(".input").addClass('notSelected');
     $(".input").focus(function () {
         $(this).addClass('selected');
     });

     $(".input").focusout(function () {
         $(this).removeClass('selected');
     });

     $(document).ready(function () {
         GalleryGrid();
         $(window).resize(GalleryGrid);
     });
     //Gallery Grid System//
     var testimonial = $(".testimonial, .galleryItem", "#grid3");
     (function () {
         $(document).ready(GalleryGrid);

         $(window).resize(GalleryGrid);
     })(jQuery);

     function GalleryGrid() {
         var grid3 = $('#grid3');
         var width = $(window).width();
         if (width < 1030 && width > 770) {
             var grid1 = $('#grid1');
             var grid2 = $('#grid2');

             for (var i = 0; i < testimonial.length; i++) {
                 if (i < testimonial.length / 2) {
                     grid1.append(testimonial[i]);
                 } else {
                     grid2.append(testimonial[i]);
                 }
             }
         } else {
             grid3.append(testimonial);
         }
     }


     //Testimonials Animation//
     $(".testimonial").hover(function () {
         $(".testimonial").addClass('testimonialNotActive');
         $(this).removeClass('testimonialNotActive').addClass('testimonialActive');
     },

     function () {
         $(".testimonial").removeClass('testimonialNotActive');
         $(this).removeClass('testimonialActive');
     });


     //Portfolio Gallery Filter//
     (function () {
         var $portfolioGallerySection = $('#portfolio-sectionB'),
             $filterbuttons = $('#portfolio-sectionA a');

         $filterbuttons.on('click', function () {
             var filter = $(this).data('filter');

             $filterbuttons.removeClass('portfolio-sectionAClicked');
             $(this).addClass('portfolio-sectionAClicked');

             $portfolioGallerySection.attr('class', filter);
             $('.galleryItem').removeClass('selectedFilter');
             $('.galleryItem.' + filter).addClass('selectedFilter');
         });
     }());
 });
DGS
  • 6,015
  • 1
  • 21
  • 37
  • Try to put resize in ready event (in GalleryGrid function). – jcubic Sep 08 '13 at 08:32
  • Here you mean? `$(window).resize(GalleryGrid);` –  Sep 08 '13 at 08:33
  • `$(document).ready(function() { GalleryGrid(); $(window).resize(GalleryGrid); });` – jcubic Sep 08 '13 at 08:34
  • same problem mate, I have placed that line you just posted just before the function starts. –  Sep 08 '13 at 08:37
  • Did you write the function that resizes the header? Post the code for that here too – DGS Sep 08 '13 at 08:39
  • No mate the header is using CSS, but I have just updated the post upon your request. –  Sep 08 '13 at 08:41
  • 1
    Out of the jQuery API: Depending on implementation, resize events can be sent continuously as the resizing is in progress (the typical behavior in Internet Explorer and WebKit-based browsers such as Safari and Chrome), or only once at the end of the resize operation (the typical behavior in some other browsers such as Opera). (http://api.jquery.com/resize/) – idmean Sep 08 '13 at 08:46
  • But I am using the `$(window).resize(function() {` –  Sep 08 '13 at 08:48
  • What do you mean? Of course you are using `$(window).resize(function() {` ? (As they do in the doc) – idmean Sep 08 '13 at 08:50
  • I just thought that you meant to ask me to use it, and I am using it, just misunderstanding you. sorry. –  Sep 08 '13 at 08:58

3 Answers3

0

Your problem is that CSS media queries and jQuery's $(window).width() do not always align.

function getCSSWidth() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return e[ a+'Width' ];
}

Use this instead of $(window).width()

modified from http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/

DGS
  • 6,015
  • 1
  • 21
  • 37
  • I don't really know where exactly to post this, I am new to all of this so please bare with me. Is it above the function? *Can we apply this to all of the JavaScript document? as there are other re-sizing functions –  Sep 08 '13 at 08:55
  • just tack that function on outside of your `$(document).ready` and than change this line `var width = $(window).width();` to `var width = getCSSWidth()` – DGS Sep 08 '13 at 09:27
0

I think this could solve your problem (but I'm not quite sure)

//Put that before the document ready event
(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
  // smartresize 
  jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');


// Here you call GalleryGrid (replace $(window).resize(GalleryGrid) with that):
$(window).smartresize(GalleryGrid);

http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/

idmean
  • 14,540
  • 9
  • 54
  • 83
  • There is some sort of an error when I paste it into the code. But I think it is working! –  Sep 08 '13 at 08:57
  • Fixed it no worries, you were missing a semicolon. let me try –  Sep 08 '13 at 09:03
  • It worked, however it has caused a problem for anther functions that has a re-sizing functions. (I have placed this code on the very top of the document before: `$(document).ready(function () {` is that correct? –  Sep 08 '13 at 09:05
  • Yeah that's correct. However this script actually can't cause any other re-sizing functions to not work. Oh the last line you have to place in an document ready. (If I wasn't clear enough) – idmean Sep 08 '13 at 09:07
  • The gallery works perfectly now, but everything else (all the other functions) are not working at all –  Sep 08 '13 at 09:09
  • If your script look smiliar to that JavaScript I have no idea what causes the other functions not to work. http://jsfiddle.net/RGa7j/ – idmean Sep 08 '13 at 09:15
  • Everything is now working, but the Gallery is still the same now - as we didn't nothing. I have placed that code just as you showed me mate –  Sep 08 '13 at 09:18
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/37007/discussion-between-loai-and-wumm) –  Sep 08 '13 at 09:18
0

The reason is your vertical scrollbar. Your content is fixed at width=1030, but when the window size is 1030, the size of the viewport is actually: window size (1030) - vertical scroll bar

Try setting

<body style="overflow:hidden">

You will see that it works correctly when the scrollbar is removed. Or try setting:

<link href="assets/css/tablets-landscape.css" rel="stylesheet" type="text/css" media="screen and (max-width : 1045px)"/>

Set max-width:1045px to make up for scrollbar, you will see that it works correctly.

Your javascript should be like this:

var width = $(window).width() + verticalscrollbarWidth;
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • This worked! however I can't scroll the web page now! what shall I do? –  Sep 08 '13 at 10:20
  • 1
    @Loai: setting `` just to verify that vertical scrollbar is the problem. The best way is to fix it in the script: `var width = $(window).width() + verticalscrollbarWidth;`. – Khanh TO Sep 08 '13 at 10:22
  • Adding this line: var width = $(window).width() + verticalscrollbarWidth; made everything stop working mate –  Sep 08 '13 at 10:23
  • @Loai: `verticalscrollbarWidth` should be calculated dynamically. You could take a look at these links on how to do that http://stackoverflow.com/questions/8079187/how-to-calculate-the-width-of-the-scroll-bar, http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes. For a quick test, try `var width = $(window).width() + 15;` (assume that the scrollbar width is 15) – Khanh TO Sep 08 '13 at 10:24