Eggsnuff
Eggsnuff

Reputation: 39

Append <div> into body just once

I'm trying to append a div when the mobile is in landscape mode. But I only want the div to be append once and one time only.

function doStuff() {
  landscape = window.orientation ? window.orientation == 'landscape' : true;

  if (landscape && window.innerWidth < 736 && window.innerWidth > 320) {
    if (window.innerHeight > window.innerWidth) {
      console.log("portrait");
    } else {
      $("body").append("<div>Test</div>");
    }
  }
}

window.onload = window.onresize = doStuff;
if (window.onorientationchange) {
  window.onorientationchange = doStuff;
}

Upvotes: 0

Views: 482

Answers (5)

Nathan  Meunier
Nathan Meunier

Reputation: 131

I think you can use the .one(). there is example of how use it on internet.

http://api.jquery.com/one/

Upvotes: 0

Saurabh Lende
Saurabh Lende

Reputation: 1003

Set flag = true if div is already appended.

function doStuff(){
landscape = window.orientation? window.orientation=='landscape' : true;
var flag = false;
if(landscape && window.innerWidth < 736 && window.innerWidth > 320){
    if(window.innerHeight > window.innerWidth){
        console.log("portrait");
    }else{
       if (flag == false){
          $( "body" ).append( "<div>Test</div>" );
          flag = true;
       }else{
          console.log("Div is already appended");
       }

    }
  }
}

window.onload=window.onresize=doStuff;
if(window.onorientationchange){
  window.onorientationchange=doStuff;
}

Upvotes: 0

Abi
Abi

Reputation: 734

You could use one(), which fires only once

For Appending you need to use this

var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

There's no need for JS code here - you can use CSS alone to achieve this. Media queries have the orientation restriction which you can use to display the required content:

.landscape-only { display: none; }

@media all and (orientation:landscape) {
  .landscape-only { display: block; }
}

Working example

To see the content change you will just need to resize the width of the Output frame in the above Fiddle.

Upvotes: 3

Mateusz Woźniak
Mateusz Woźniak

Reputation: 1499

You can check if this div is already appended.

var appended = false;

function doStuff() {

    if(appended) return;

    landscape = window.orientation? window.orientation=='landscape' : true;

    if(landscape && window.innerWidth < 736 && window.innerWidth > 320){
        if(window.innerHeight > window.innerWidth){
            console.log("portrait");
        } else{
            $("body").append("<div>Test</div>");
            appended = true;
        }
    }

}     

Upvotes: 1

Related Questions