Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change font-size in a div after selecting the text only in that div

Tags:

html

jquery

I am using the below code to change the font-size of the text in a <div>. It changes the font-size, but first you need to select the size in drop-down then click on that text and only then is the font-size affected. However I would like the font-size to be changed immediately for the selected text. Can you help me?

HTML

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<form id="myform">
    <select id="fs"> 
        <option value="Arial">Arial</option>
        <option value="Verdana">Verdana</option>
        <option value="Impact">Impact</option>
        <option value="Comic Sans MS">Comic Sans MS</option>
    </select>

    <select id="size">
        <option value="7">7</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
    </select>
</form>

<br/>

<div id="name" class="name">dsfdsfsfdsdfdsf</div> 
<div id="address" class="address">sdfsdfdsfdsfdsf</div> 
<div id="address1" class="address1">sdfsdfdsfdsfdsf</div>

Script

$(".name").click(function(){
    var id = this.id;
   $("#"+id).css('font-size', $('#size').val()+"px");
});

$(".name").click(function(){
    var id = this.id;//get clicked id
    $("#"+id).css('font-family', $('#fs').val());
});
like image 802
user2528279 Avatar asked Jun 28 '13 11:06

user2528279


1 Answers

There's no event able to catch if text is selected, but you can use mousedown/mouseup to simulate it and check for window.getSelection():

$(".name, .address, .address1").on("mousedown", function () {    
    $(this).one("mouseup", function () {            
        if (window.getSelection().toString().length > 0)
            $(this).css('font-size', $('#size').val()+"px");
    });
});

Check it at JSFiddle

upd: thanks for minus. Updated answer

like image 112
Sergio Avatar answered Oct 08 '22 00:10

Sergio