Reputation: 252
var x = window.innerWidth;
if (window.innerWidth<500){
function myFunction() {
var node = document.getElementById("myList2").firstChild;
document.getElementById("myList1").appendChild(node);
}}
var myVar = setInterval(myFunction, 1000);
document.getElementById("test").innerHTML = x;
<html>
<body>
<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>
<p id="test"></p>
</body>
</html>
My width is 1366px but the above code executes and adds the li to myList1. Any help will be appreciated. May be it is a newbie question but I'm new to coding.
Upvotes: 2
Views: 79
Reputation: 18734
you can also check before invocation:
var x = window.innerWidth;
function myFunction() {
var node = document.getElementById("myList2").firstChild;
document.getElementById("myList1").appendChild(node);
}
if (window.innerWidth < 500) {
var myVar = setInterval(myFunction, 1000);
}
document.getElementById("test").innerHTML = x;
<html>
<body>
<ul id="myList1">
<li>Coffee</li>
<li>Tea</li>
</ul>
<ul id="myList2">
<li>Water</li>
<li>Milk</li>
</ul>
<p id="test"></p>
</body>
</html>
setInterval
in this case is not an ideal solution because it will keep on calling the function until there will be no var node
and then you'll get errors every time the function is called.
Upvotes: 1
Reputation: 27092
You should move your conditional in the function:
var x = window.innerWidth;
function myFunction() {
if ( x < 500 ) {
var node = document.getElementById("myList2").firstChild;
document.getElementById("myList1").appendChild(node);
}
}
var myVar = setInterval(myFunction, 1000);
document.getElementById("test").innerHTML = x;
<html>
<body>
<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>
<p id="test"></p>
</body>
</html>
Upvotes: 3