Wednesday, 9 January 2013

jQuery code to implement "email this page" functionality

Some pages on our site have a "Print this page" link which opens a popup window where the user can email the content to someone else using a form.

Our implementation uses jQuery to:
1. copy the content from the window that opened the popup, using window.opener.document
2. filter the contents of the copied content
3. put it in the textarea

This javascript needs to be located on the poup page.

<script type='text/javascript'>
$(function () {
    // get the content based on id of the div -- ie, id="main-content-wrapper"
    // call .clone() so that subsequent .remove() calls do not affect the original window.opener.document
  var content = $('#main-content-wrapper', window.opener.document).clone();

// remove the elements that we don't want displayed in our form
  $('ul.page-tools', content).remove();
    $('ul.breadcrumbs', content).remove();
    $('p.return', content).remove();
// paste the content into a textarea input field with id="emailContent"
// calling .children() because the content we have has lots of intervening divs
  // in your case this may not be needed, so just use content.html()
    $("#emailContent").html(content.children().html());


})
</script>

Btw, our implementation uses CKEditor javascript library so the emailContent textarea will display the content as HTML.


No comments: