views:

35

answers:

2

In Joomla, I am switching between languages not using the country flags as the indicator which language I am on but switch the text from English to Afrikaans using jQuery's replaceWith() method.

Problem I am having is that on first click of the word English, to change it to Afrikaans, the link does not work. It does however work on the toggle when it needs to come back.

Would appreciate the help please. Here's my logic of how I think it should work:

jQuery(document).ready(function($) {
$(".item48").toggle(
  function () {
    $(this).replaceWith("<li class='active item48' id='current'><a href='index.php?lang=af'><span>English</span></a></li>");
  },
  function () {
    $(this).replaceWith("<li class='active item48' id='current'><a href='index.php?lang=en'><span>Afrikaans</span></a></li>");
  }
);
+1  A: 

You're replacing the element that has the click handler (.toggle() is a click handler, and you're currently losing it), but you really just need to change the link inside, using .html() like this:

jQuery(document).ready(function($) {
  $(".item48").toggle(
    function () {
      $(this).html("<a href='index.php?lang=af'><span>English</span></a>");
    },
    function () {
      $(this).html("<a href='index.php?lang=en'><span>Afrikaans</span></a>");
    }
  );
});
Nick Craver
+1  A: 

That's because the event handler doesn't stay intact. You can use live as an alternative, but the better method would be changing the href and text.

jQuery(document).ready(function($) {
$(".item48").toggle(
  function () {
    $('a', this).attr('href', 'index.php?lang=en').find('span').text('English')
  },
  function () {        
    $('a', this).attr('href', 'index.php?lang=af').find('span').text('Afrikaans')
  }
);

Or use $(this).html('HTML HERE') instead.

meder