SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Jan 2008
    0 Post(s)
    0 Thread(s)

    anchor w/ window.print() and javascript disabled

    <a href="javascript:window.print()" title="Print This Page">Print</a>

    If the user has javascript disabled, will this create an anchor that does nothing if clicked on?

    Would the following work? And if javascript was disabled would nothing be seen in the browser? It seems to work in IE7.

    Type into notepad and save as printanchor.js:
    document.write('<a href="javascript:window.print()" title="Print This Page">Print</a>');

    Then put this in xhtml code:
    <script type="text/javascript" src="../jscripts/printanchor.js"></script>

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    2 Post(s)
    0 Thread(s)
    If the user has javascript disabled, will this create an anchor that does nothing if clicked on?

    That would work, yes. However, it is horrible because you're using obtrusive javascript methods (putting <script> elements in the markup and using document.write).

    Better idea would be to use the DOM. Say you have a P with the ID "content" and you want to put this anchor at the end of the P:
    Code Javascript:
    function addPrintLink() {
      var a = document.createElement('a');
      a.title = 'Print this page';
      a.onclick = window.print;
    if (window.addEventListener) window.addEventListener('load', addPrintLink, false);
    else if (window.attachEvent) window.attachEvent('onload', addPrintLink);
    and save this as printanchor.js and put it in the <head> with a <script> tag just like the one your posted above.

    Yes, it seems a lot more verbose, but it achieves separation of your Javascript (JScript is IE-only by the way) from your XHTML (which is probably HTML anyway), and this makes your code much easier to maintain and expand.

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Sydney, NSW, Australia
    25 Post(s)
    1 Thread(s)
    Also if you are really using XHTML rather than just calling it XHTML and serving it as HTML then you can't use document.write at all as that command is invalid with XHTML.

    You must use createElementNS() in XHTML to create elements to add to the page as neither document.write or innerHTML will work with XHTML.
    Stephen J Chapman, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts