views:

43

answers:

3

I have the following code in a JavaScript file:

$(document).ready(function() {
    detectscreen();
});

$(window).resize(function(){
        detectscreen();
    });

    function windowWidth() {
        if(!window.innerWidth) {
         // user is being a git, using ie
         return document.documentElement.clientWidth;
        } else {
         return window.innerWidth;
    }}

    function detectscreen() {
        if (windowWidth()>1280) {
         $('body').append('<div id="gearsfloat"></div>');
    }}

Basically, what it does is append an object to the end of the document if the width is less than 1280 pixels, however what this does is append it every single time the page is resized.

I don't think I can use the once function because it would only run it once and then the next time it is resized, it's dead. Anything I can do?

 

NOTE: I, in fact, DO want it to be checked on the resize of the page, but the effect is that it happens over and over again.

if (windowWidth()>1280 && !$('gearsfloat')) {
  $('body').append('<div id="gearsfloat"></div>');
}

The above (by Jason) works does not work but then it won't delete it when it gets less than 1280. Is there anything I can do?

+1  A: 
if (windowWidth()>1280 && !$('gearsfloat')) {
  $('body').append('<div id="gearsfloat"></div>');
}

Check if the element already exists first?

Jason Harwig
This doesn't work for some reason, and the element needs to be removed if the screen is resized to less than 1280 again.
Brandon Wang
A: 

if you dont want the function to be called when the window is resized, then why are you binding the resize function?

wont the document ready function always be called before the resize function anyway, so you are guaranteed to have your element appended?

mkoryak
+1  A: 

Keep track of whether the element exists or not, and add/remove it when the condition changes. That way you will only add it once, it will be removed when it shouldn't be there, and you don't do any unneccesary adding or removing:

var gearsExists = false;

function detectscreen() {
   var shouldExist = windowWidth() > 1280;
   if (shouldExist != gearsExists) {
      if (shouldExist) {
         $('body').append('<div id="gearsfloat"></div>');
      } else {
         $('#gearsfloat').remove();
      }
      gearsExists = shouldExist;
   }
}
Guffa
Wow, it works great. Thanks so much!
Brandon Wang
You could easily rewrite this to get rid of the global variable, or use a closure: function detectscreen() { var shouldExist = windowWidth() > 1280, gears = $('#gearsFloat'); if (shouldExist) { if(!gears) { $('body').append('<div id="gearsfloat"></div>'); } } else { if(gears) { gears.remove(); } } gearsExists = shouldExist; }}
PatrikAkerstrand