Hi,
I'm trying to make a link that changes my web page into a printable format and back:

<a id="print" href="#" title="Print map">Printable version</a>

The switch to printable format works fine:

$('#print').click(function() {
	$('img').attr('src', newsrc);
	$(this).html('Screen version');
	$(this).attr('id', 'screen');
	return false;
});

But going back, it doesn't work at all. Of course, .click() won't work because the element gets id "screen" only after the link is clicked. I tried using .live() , but this didn't work either:

$('#screen').live("click", function() {
	$('img').attr('src', oldsrc);
	$(this).html('Printable version');
	$(this).attr('id', 'print');
	return false;
});

I've since solved the problem by just using a flag for the single first event handler instead of making two event handlers and switching the ID for the link to call each. But I want to know how to fix this in case I have this problem some other time where it's not as simple to just use a flag.

I've tried this, and it works.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>test</title>
    <meta http-equiv="content-language" content="en" />
  </head>
  <body>
    <a id="print" href="#" title="Print map">Printable version</a>
    <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
      var oldsrc = "1";
      var newsrc = "2";
      $(document).ready(function() {
        $('#print').live("click", function() {
          $('img').attr('src', newsrc);
          $(this).html('Screen version');
          $(this).attr('id', 'screen');
          return false;
        });

        $('#screen').live("click", function() {
          $('img').attr('src', oldsrc);
          $(this).html('Printable version');
          $(this).attr('id', 'print');
          return false;
        });
      });
    </script>
  </body>
</html>

I see. so you need to use .live() for both clicks, not just the second. Makes sense. Great, thanks for your help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.