Wilf
Wilf

Reputation: 2315

How to apply css to all html elements in a div selector with jquery

I need to apply css font-size by a jquery on click to every element under div selector. But I can't make them affect. This is how I tried.

CSS

#reading_pane{
font-size:14pt;
}

HTML

<div id="reading_pane">
<p>this is a text</p>
<span>this is another text</span>
</div>
<a id="incfont">A+</a>
<a id="decfont">A-</a>

javascript

  $(document).ready(function() { 
  $('#incfont').click(function(){    
        curSize= parseInt($('#reading_pane span, p').css('font-size')) + 2;
  if(curSize<=20)
        $('#reading_pane').css('font-size', curSize);
        });  
  $('#decfont').click(function(){    
        curSize= parseInt($('#reading_pane').css('font-size')) - 2;
  if(curSize>=12)
        $('#reading_pane').css('font-size', curSize);
        }); 
 });

As the detailed above. I need every <p> and <span> in div#reading_pane change the size on each a clicked.

Upvotes: 1

Views: 165

Answers (1)

Regent
Regent

Reputation: 5178

The main problem is that .css('font-size') returns size in pixels, not in points. So, based on this question and avoiding code duplication it can be so:

Fiddle.

$(document).ready(function()
{
    $('#incfont').click(function()
    {
        changeFontValue(2);
    });

    $('#decfont').click(function()
    {
        changeFontValue(-2);
    });

    function changeFontValue(difference)
    {
        var newSize = Math.round(parseInt($('#reading_pane').css('font-size')) * 72 / 96) + difference;
        if (newSize >= 12 && newSize <= 20)
        {
            $('#reading_pane').css('font-size', newSize + 'pt');
        }
    }
});

Note: I also modified HTML:

<a id="incfont">A+</a>
<a id="decfont">A-</a>

Upvotes: 1

Related Questions