3

So I'm using Google website translator (http://translate.google.com/) for a website I'm creating.

When a user clicks on the Spanish translation button, I'd like to switch to a different form, but I'm having trouble triggering the change, since the html class (translated-ltr) I'm basing the change on is created dynamically.

It seems easy enough... but I'm confused. Can this be done? Please note I'm just starting to learn how to use javascript/jquery.

The code for the Google translate button:

<!-- Spanish Button -->
<a class="translation-links" href="#" class="spanish" data-lang="Spanish" onClick="" onMouseOver="MM_swapImage('spanish.btn','','images/ss_spanish_tout_on.jpg',1)" onMouseOut="MM_swapImgRestore()"><img src="images/ss_spanish_tout.jpg" style="margin-top:10px;" alt="Translate to Spanish!" id="spanish.btn" name="spanish.btn" /></a>

<!-- Code provided by Google -->
<div id="google_translate_element" style="display:none;"></div>
<script type="text/javascript">
  function googleTranslateElementInit() {
    new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'en,es', gaTrack: true, gaId: 'UA-10765676-1', autoDisplay: false}, 'google_translate_element'); //remove the layout
  }
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"></script>


<script type="text/javascript">
    function triggerHtmlEvent(element, eventName) {
var event;
if(document.createEvent) {
    event = document.createEvent('HTMLEvents');
    event.initEvent(eventName, true, true);
    element.dispatchEvent(event);
} else {
    event = document.createEventObject();
    event.eventType = eventName;
    element.fireEvent('on' + event.eventType, event);
}
}
            <!-- Button click handler -->
        $('.translation-links').click(function(e) {
  e.preventDefault();
  var lang = $(this).data('lang');
  $('#google_translate_element select option').each(function(){
    if($(this).text().indexOf(lang) > -1) {
        $(this).parent().val($(this).val());
        var container = document.getElementById('google_translate_element');
        var select = container.getElementsByTagName('select')[0];
        triggerHtmlEvent(select, 'change');
    }
});
});
        </script>

The code to trigger the form action change:

if ($('html').hasClass('translated-ltr')) {
        $('#contactForm').attr('action', 'kcontactl2_spanish.php');
    }

The original form link:

 <form method="post" action="kcontactl2.php" onsubmit="return validateForm();" name="contactSIE" id="contactForm">
Alicia B
  • 31
  • 3
  • See http://stackoverflow.com/questions/4887156/detecting-google-chrome-translation to get the idea. – Roy M J Sep 18 '13 at 06:00
  • Thanks Roy. It works to some extent... but DOMSubtreeModified doesn't work in Chrome because it's depreciated... Back to the drawing board. – Alicia B Nov 27 '13 at 00:09
  • Oh 3 months stuck with one prob.. Here there is group for javascript in chat and there are really good coders there and maybe they will provide good support for the same.. – Roy M J Nov 27 '13 at 04:39

1 Answers1

1

One solution is to use polling to check if the element you are looking for exists, but I have a couple of other notes:

  1. specifying javascript events as HTML attributes is a world of pain. It seems expedient but it isn't. For example, your link should go to the translated form, and then you attach javascript events to it to cancel this behavior and dynamically change the form.
  2. If you're going to use jQuery, might as well use it to override the verbose built-in methods like document.getElementByID. It will be less jarring for others to read (eg, when asking for help on StackOverflow).
  3. Is there a reason you are creating your own event trigger? JQuery has this built in, it is cross-platform and as far as I know bug free.
  4. You have HTML comments embedded in javascript. This can break.
  5. It would be more reliable to switch the image out using the css :hover pseudo class.

This is how I would do this:

<!-- css for the image behind the link -->
<style type="text/css">
  .translation-links {
     display: inline-block;
     height: 20px; width: 100px; /* modify to the dimensions of the image */
     background: url('images/ss_spanish_tout.jpg') no-repeat center left;
  }
  .translation-links:hover {
     background-image: url('images/ss_spanish_tout_on.jpg');
  }
  .translation-links span {
     visibility:hidden
  }
</style>

<!-- Spanish Button -->
<a class="translation-links" href="?lang=spanish" data-lang="Spanish"><span>Translate to Spanish!</span></a>

<!-- Code provided by Google -->
<div id="google_translate_element" style="display:none;"></div>
<script type="text/javascript">
  function googleTranslateElementInit() {
    new google.translate.TranslateElement({
        pageLanguage: 'en',
        includedLanguages: 'en,es',
        gaTrack: true,
        gaId: 'UA-10765676-1',
        autoDisplay: false
    }, 'google_translate_element');
  }
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"></script>


<script type="text/javascript">
   $(function () {
       // translate the form to spanish when the button is clicked
       $('.translation-links').on('click', function(e) {
           var lang = $(this).data('lang'),
               select = $('#google_translate_element select').first(),
               // rather than looping the options with $.each, filter them to select 
               // just what you want.
               option = select.find('option').filter(function () {
                   return ($(this).text().indexOf(lang) > -1);
               }).first(); // and take the first, in case there are more than one
           if (option.length) {
               // I am not quite sure about your use case, but I would change the form
               // action attribute here, to eliminate the need for the polling block.
               select.val(option.attr('value')).trigger('change');
           }
           // by putting this at the end, we still have the fallback if the js breaks
           e.preventDefault();
       });

       // poll every half a second to see if the form action needs to change
       var html = $('html'), contactForm = $('#contactForm');
       setInterval(function () {
           var url = 'kcontactl2.php';
           if (html.hasClass('translated-ltr')) {
               url = 'kcontactl2_spanish.php';
           }
           if (contactForm.attr('action') !== url) {
              contactForm.attr('action', url);
           }
       }, 500);
   });
</script>
Matt
  • 1,287
  • 2
  • 11
  • 25