I'm new to Javascript. I'm trying to raise the margin of the text only on the desktop version, not on mobile. Could you help me find the problem.
<p id="myID">Lorem ipsum dolor sit amet, prima harum elitr te pri. Vix partiendo sententiae ad. Duo at amet dicam tempor. Numquam ceteros concludaturque in eum, id nec adhuc aliquando scriptorem, has ea consetetur cotidieque consectetuer. In verear neglegentur eam.</p>
<script>
let screenwidth=window.innerWidth;
if (screenwidth > "768px")
{
document.getElementById("myID").style.marginLeft = "150px";
}
else {
document.getElementById("myID").style.marginLeft= "0px";
}
</script>
Unfortunately I couldnt find the problem by myself
CodePudding user response:
window.innerWidth
will return a number not string so it should be
if (screenwidth > 768)
instead of if (screenwidth > "768px")
let screenwidth=window.innerWidth;
if (screenwidth > "768")
{
document.getElementById("myID").style.marginLeft = "150px";
}else {
document.getElementById("myID").style.marginLeft= "0px";
}
<p id="myID">Lorem ipsum dolor sit amet, prima harum elitr te pri. Vix partiendo sententiae ad. Duo at amet dicam tempor. Numquam ceteros concludaturque in eum, id nec adhuc aliquando scriptorem, has ea consetetur cotidieque consectetuer. In verear neglegentur eam.</p>
you can do it using media queries in css as well something like
@media only screen and (min-width: 768px) {
#myId {
margin-left: 150px;
}
}
CodePudding user response:
Try media query
@media only screen and (min-width: 768px) {
#myId {
margin-left: 150px;
}
}
CodePudding user response:
Replace "768px"
by 768
. Must be a number and not a string :)
CodePudding user response:
screenwidth is number
<p id="myID">Lorem ipsum dolor sit amet, prima harum elitr te pri. Vix partiendo sententiae ad. Duo at amet dicam tempor. Numquam ceteros concludaturque in eum, id nec adhuc aliquando scriptorem, has ea consetetur cotidieque consectetuer. In verear neglegentur eam.</p>
<script>
let screenwidth=window.innerWidth;
if (screenwidth > 768){
document.getElementById("myID").style.marginLeft = "150px";
}
else {
document.getElementById("myID").style.marginLeft= "0px";
}
</script>