Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
PHP jQuery Cookbook

You're reading from   PHP jQuery Cookbook jQuery and PHP are the dynamic duo that will allow you to build powerful web applications. This Cookbook is the easy way in with over 60 recipes covering everything from the basics to creating plugins and integrating databases.

Arrow left icon
Product type Paperback
Published in Dec 2010
Publisher Packt
ISBN-13 9781849512749
Length 332 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Vijay Joshi Vijay Joshi
Author Profile Icon Vijay Joshi
Vijay Joshi
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

PHP jQuery Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Handling Events with jQuery FREE CHAPTER 2. Combining PHP and jQuery 3. Working with XML Documents 4. Working with JSON 5. Working with Forms 6. Adding Visual Effects to Forms 7. Creating Cool Navigation Menus 8. Data Binding with PHP and jQuery 9. Enhancing your Site with PHP and jQuery Firebug Index

Displaying user selected text


You must have seen the WYSIWYG (What You See Is What You Get) editors in web applications, which allow you to select some text using the mouse or keyboard and then format it (like making it bold, changing its color, and so on).

This recipe will teach you how to retrieve the text that is selected by a user and perform some basic formatting on it.

Getting ready

Get the jQuery library ready.

How to do it...

  1. Create a file named textSelect.html in your chapter1 directory.

  2. Create four buttons out of which the first three will be used to make the text bold, italic, and underlined respectively. Then create a textarea with some text in it. And finally, enter a paragraph that will be used to display the formatted HTML.

    The last button will get the value of textarea and will insert it in the paragraph.

    <html>
      <head>
        <title>Manipulating user selected text</title>
        <style type="text/css">
          p { color:red;font-size:17px;width:670px;}
        </style>
      </head>
      <body>
        <input type="button" value="b" id="bold" class="button">
        <input type="button" value="i" id="italics" class="button">
        <input type="button" value="u" id="underline" class="button">
        <input type="button" id="apply" value="Apply HTML">
        <div>
        <textarea id="selectable" rows="20" cols="80">I consider thata man's brain originally is like a little empty attic, and you have to stock it with such furniture as you choose. A fool takes in all the lumber of every sort that he comes cross, so that the knowledge which might be useful to him gets crowded out, or at best is jumbled up with a lot of other things, so that he has a difficulty in laying his hands upon it.</textarea>
        </div>
        <p id="container"></p>
      </body>
    </html>
  3. Include the jQuery library and write the JavaScript function that will get the start and end positions of the selected text.

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    function getPositions()
    {
      var startPosition = endPosition = 0;
      var element = document.getElementById('selectable');
      if (document.selection) 
      {
        //for Internet Explorer
        var range = document.selection.createRange();
        var drange = range.duplicate();
        drange.moveToElementText(element);
        drange.setEndPoint("EndToEnd", range);
        startPosition = drange.text.length - range.text.length;
        endPosition = startPosition  + range.text.length;
      }
      else if (window.getSelection) 
      {
        //For Firefox, Chrome, Safari etc
        startPosition = element.selectionStart;
        endPosition = element.selectionEnd;
        
      }
      return {'start': startPosition, 'end': endPosition};
    }
  4. Next, write the code for the Apply HTML button that will simply get the text from the textarea and insert it in the paragraph.

    $('#apply').click(function()
    {
        var html = $('#container').html($('#selectable').val());
    });
  5. Let's code the first three buttons now. We will bind the click event with the three buttons. On the click of each button, the position of the selected text will be retrieved and it will be enclosed within HTML tags depending on which button is clicked.

    $('.button').click(function()
    {
      var positions = getPositions();
      if(positions.start == positions.end)
      {
        return false;
      }
      var tag = $(this).val();
      var textOnPage = $('#selectable').val();
    
      var startString = textOnPage.substr(0, positions.start);
      
      var targetString = textOnPage.substr(positions.start, positions.end - positions.start);
      var formattedString = "<" + tag +">" + targetString + "</" +  tag +">";
      var endString = textOnPage.substr(positions.end);
      $('#selectable').text(startString + formattedString + endString);
    });
  6. Save the code, start your browser and point it to the file. Select some text with your mouse and click on any of the buttons. You will see that the selected text has been enclosed with the corresponding HTML tags. If you click on the second button (u), the selected text will be enclosed in <u> and </u> HTML tags.

    Now click on the Apply HTML button. You will be able to see the formatted text of the textarea in HTML format inside the paragraph, as seen in the following screenshot:

How it works...

On click of a button, we first get the start and end positions of selected text using the ge tPositions() function. Determining this value is a bit complex as different browsers have different methods for handling selections. Internet Explorer uses document.selection, which represents a subset of documents, whereas Mozilla and similar browsers use window.getSelection.

IE has a range of objects using which we can determine what text was selected, and the start and end positions of selection in original text. First we create a range object from the selection. Then we create a clone of it using the duplicate method. After this, two functions moveToElementText() and setEndPoint() are used on the duplicated range. These methods align the values of original text and the selection.

Once this is done, we compare the values of the original and the duplicated range to find out the start position. Then we add the length of the selection to the start position, which gives us the end position marker.

For other browsers, getting positions is relatively simple. Start and end positions of selections in textarea can be retrieved using .selectionStart and .selectionEnd properties.

Once we get both these values, we create an object in which we put both of these and return the object to the calling function.

If the values of both these positions are equal, it means that no text is selected. In this case we simply return from the function and do nothing.

Then we determine which button was clicked. The clicked button's value will be used to format the selected text. After that, we store the value of textarea in a local variable textOnPage.

Now comes the part where the actual manipulation takes place. We break the textOnPage variable into three parts. The first part contains the string from the beginning to the starting position of the selection. The second part of the string is the actual selected text of textarea that has to be formatted. We now enclose it in HTML tags (<b>, <i>, or <u>) according to the button clicked. The third and final part is from where the selection ends to the end of the string.

To get the resulting string we can now simply concatenate these three strings and place it back into the textarea. The textarea will now have text that has the selected text enclosed in HTML tags. To verify this, click on the Apply HTML button. This will take the text from the textarea and insert it as HTML into the paragraph with ID container.

There's more...

Short method for getting selected text

Another method can be used to get the selected text from other elements, such as <div>, <p>, and so on. This will not give any positions but simply the selected text. Note that this method will not work for textareas for Mozilla and similar browsers but it will work in Internet Explorer for textareas as well as other controls.

Use the following function to get the selected text:

function getSelectedText()
{
  var selectedText = '';
  if (document.selection) 
  {
  var range = document.selection.createRange();
    selectedText = range.text;
    }
    else if (window.getSelection) 
    {
      selectedText = window.getSelection();
    }
  return selectedText;
}
You have been reading a chapter from
PHP jQuery Cookbook
Published in: Dec 2010
Publisher: Packt
ISBN-13: 9781849512749
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image