-1

I'm working on dynamically resizing vertical margins with jQuery and I'm wonder if if how I can resolve a problem that causes the margins to resize only once when the page loads.

    /* PAGE SIZE */
    $(document).ready(function(){
        var WIDTH = $(window).width();
        if(WIDTH > 1420){
            $("ul#menu-content-1.menu").css("margin-top","59px");
            $("div.menu-content-container").css("margin-top","59px")
        } else if(WIDTH < 1420) {
            $("ul#menu-content-1.menu").css("margin-top","-59px");
            $("div.menu-content-container").css("margin-top","-59px");
        }
    });

This is my existing code. How can I fix this recurring problem so that each time the page loads and the window is resized, the margins will adjust?

user3105120
  • 307
  • 1
  • 3
  • 9
  • It's a little difficult to diagnose the issue with a single block of JavaScript. If you set up a [reduced](http://stackoverflow.com/help/mcve) [test case](http://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets), maybe someone can help. – BoltClock Nov 23 '14 at 07:36

3 Answers3

1

.ready(), .resize() are short-cuts for using the .bind() function (or .on() in jQuery 1.7+). .resize(function () {}) maps to .bind('resize', function () {}).

Here is how your code would look using .on() wherever possible:

$(document).on('ready', function() {

    $(window).on('resize', function() {

         // Stuff in here happens on ready and resize.

        var WIDTH = $(window).width();
        if(WIDTH > 1420){
            $("ul#menu-content-1.menu").css("margin-top","59px");
            $("div.menu-content-container").css("margin-top","59px")
        } else if(WIDTH < 1420) {
            $("ul#menu-content-1.menu").css("margin-top","-59px");
            $("div.menu-content-container").css("margin-top","-59px");
        }

    }).trigger('resize'); // Trigger resize handlers.       

});//ready
4dgaurav
  • 11,360
  • 4
  • 32
  • 59
0

I assuming you want to trigger this at some point?

On window resize possibly: jQuery on window resize

Also I would recommend using CSS media queries for the above:

ul #menu-content-1.menu {margin-top: 59px}
div.menu-content-container {margin-top:59px}

@media (max-width: 1420) 
{ 
    ul #menu-content-1.menu {margin-top: -59px}
    div.menu-content-container {margin-top: -59px}
}
Community
  • 1
  • 1
user3047190
  • 319
  • 2
  • 7
0

You can try putting it in the $ (window) .load ();

 $(window).load(function(){
        var WIDTH = $(window).width();
        if(WIDTH > 1420){
            $("ul#menu-content-1.menu").css("margin-top","59px");
            $("div.menu-content-container").css("margin-top","59px")
        } else if(WIDTH < 1420) {
            $("ul#menu-content-1.menu").css("margin-top","-59px");
            $("div.menu-content-container").css("margin-top","-59px");
        }
    });
Sergio Andrade
  • 194
  • 1
  • 1
  • 10