Cyber Kingston
Cyber Kingston

Reputation: 55

Change font-size with jquery if screen size is mobile size

In my web page, I want to change font-size with jquery if screen-size is mobile size. My code is as follow:

<head>
<script type='text/javascript'>
 if(screen.width <= 600){

        $("#para_head").css({"font-size":"12px"});
        $("#para_detail").css({"font-size":"10px"});
}
</script>
<style>
#para_head{
}
#para_detail{
}
</style>
</head>
<body>
<div id="para_head">
    Header
</div>
<div id="para_detail">
    Detail
</div>
</body>

As above code, I can't change the font-size. Where should i fix this. Any idea pls.

Upvotes: 4

Views: 1635

Answers (3)

Darren
Darren

Reputation: 70746

I would recommend using a CSS media query rather than jQuery. You will require a lot of jQuery manipulation if your application is big, it will also be harder to maintain and most importantly it will be heavy on the DOM.

Responsive websites are much easier to achieve with CSS as shown below.

@media screen and (max-width: 600px) {
    #para_head {
       font-size: 12px;
    }
}

Demo (Resize the output pane)

https://jsfiddle.net/9351yv7j/

As an additional note I would use the kebab style casing for HTML elements, para-head rather than para_head.

Upvotes: 0

huon sokly
huon sokly

Reputation: 117

Why don't use CSS?

@media only screen and (max-width: 600px) {
 #para_head{
  font-size: 12px;
 }
 #para_detail{
  font-size: 10px;
 }
}
<div id="para_head">
  Para Head
</div>
<div id="para_detail">
  Para Detail
</div>

Have fun :)

Upvotes: 3

Vladu Ionut
Vladu Ionut

Reputation: 8193

Its better to use media query but if you prefer a jquery solution see below

if ( $(window).width() > 600) {     
  //Add your javascript for large screens here
}
else {

   $("#para_head").css({"font-size":"12px"});
   $("#para_detail").css({"font-size":"10px"});
}

Upvotes: 1

Related Questions