简体   繁体   中英

Button that toggles font-weight in text area when clicked

I am trying to make a button that changes the font-weight to bold when it is clicked and then back to normal again when it is un-clicked. But the hard part is that I only want the part of the text area that they clicked on the bold button for to be bolded, so I do not want all of the text area to be bold. I tried making it were all of the text area would be bold at first but it won't work. I am sure it is probably really easy, but I can't figure it out. I will put my code below, thank you for your time.

<button class="changeButton" id="bold"><strong>Bold</strong></button>
<textarea class="textdoc" name="textdoc"></div>

JavaScript:

$(document).ready(function(){
    $('#bold').click(function(){
        $('.textdoc').toggleClass('.boldClass');
    });
});

PS:This obviously is not all my code, comment telling me if you think I need to post all of it, but I think that the problem could just be solved with the code I have here.

.toggleClass('.boldClass') should be without the . like .toggleClass('boldClass');

Also your'e missing a closing </textarea> (instead of </div> ).
Here's an example:

 $(document).ready(function(){ $('#bold').click(function(){ $('.textdoc').toggleClass('boldClass'); }); }); 
 .boldClass{ font-weight:bold; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="changeButton" id="bold"><strong>Bold</strong></button> <textarea class="textdoc" name="textdoc">TEST</textarea> 

If you want to click on B and be able to write in Bold that you're interested in contenteditable attribute. (it cannot be done inside a textarea)

 $("[data-cmd]").click(function(evt){ evt.preventDefault(); var cmd = $(this).data().cmd; document.execCommand(cmd, false, null); }); 
 #editable{ border:1px solid #ddd; min-height:100px; padding:5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a data-cmd="bold" href="#"><b>B</b></a> <a data-cmd="italic" href="#"><i>I</i></a> <a data-cmd="underline" href="#"><u>U</u></a> <div id="editable" contenteditable="true">Write here<div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM