Reputation: 39
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
Reputation: 131
I think you can use the .one(). there is example of how use it on internet.
Upvotes: 0
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
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
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; }
}
To see the content change you will just need to resize the width of the Output frame in the above Fiddle.
Upvotes: 3
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