Search code examples
jquerytriggerswindowwidth

Why isn't this jquery triggering immediately


Basically I have this jquery set up and the first part if statement works. But for the one with the tooltip it doesn't quite go to plan.

Here's the code:

$(window).resize(function(){
        if ($(window).width() > 1200) {
            if (!$('#largeS').length) {
                $('head').append('<link rel="stylesheet" type="text/css" id="largeS" href="http://imgstr.thefinishedbox.com/css/large.css" />');
                if ($.browser.msie && (jQuery.browser.version > 6.9999) && (jQuery.browser.version < 7.9999) ) { //IE7
                    $('head').append('<link rel="stylesheet" type="text/css" id="ie7Large" href="http://imgstr.thefinishedbox.com/css/ie7Large.css" />');
                }
            }
        }
        else {
            $('#largeS').remove();
            if ($.browser.msie && (jQuery.browser.version > 6.9999) && (jQuery.browser.version < 7.9999) ) { //IE7
                $('#ie7Large').remove();
            }
        }
        if ($(window).width() > 1024) {
            if(!$('#sidebar .tip').hasClass('vertical')) {
                $('#sidebar .tip').addClass('vertical');
            }
        }
        else {
            $('#sidebar .tip').removeClass('vertical');
        }
    }).trigger('resize'); 

The sidebar tip doesn't trigger upon browser load so the vertical class isn't getting added even though it's bigger than 1024 window width. But it works upon changing the window size after loading.

Not sure why, any help?

edit: Here's the live version: http://tfbox.com - tooltips are on popular posts.


Solution

  • function adjustStyle(width) {
            width = parseInt(width);
            if (width > 1024) {
                $('#sidebar .tip').addClass('vertical');
            } else {
               $('#sidebar .tip').removeClass('vertical');
            }
        }
    
        $(function() {
            adjustStyle($(this).width());
            $(window).resize(function() {
                adjustStyle($(this).width());
            });
        });