charlie
charlie

Reputation: 51

Trigger Google Translate with button click jQuery

I am trying to trigger a Spanish Language translation using Google Translate and have found a few options to do this using jQuery. I have been able to get it to select Spanish from the dropdown but it will not trigger the change event to start the translation process. Can someone look at this and tell me what I am doing wrong?

Thanks

<!DOCTYPE html>
<html lang="en-US">
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> 

<script>
$(document).ready(function(){
  $("button").click(function(){
    $('.goog-te-combo').change(function(){
		var data= $(this).val();
  		alert(data);            
	});
	$('.goog-te-combo')
    	.val('es')
    	.trigger('change');
     });
});
</script>

<script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>

<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

</head>

<body>

<div id="google_translate_element"></div>

<h2>This is a test.</h2>
<p>Trying to accomplish translating this text into Spanish using Google Translate via a button click.</p>
<p>Just some random text to make sure this works.</p>

<button>Hablamos Espanol</button>

</body>
</html>

Upvotes: 3

Views: 6674

Answers (2)

trickymind
trickymind

Reputation: 897

There is another way to trigger change event on Google translate element.

// Create a new onchange event and trigger it
const triggerEvent = (element,eventName) =>{
    const event = new Event(eventName);
    element.dispatchEvent(event);
};

// triggers onchange event on <select>
triggerEvent(document.querySelector('.goog-te-combo'),'change');

Checkout this fiddle for more info : Google Translate

Upvotes: 0

Tlaquetzal
Tlaquetzal

Reputation: 2850

You can add this inside the button click function.

window.location = "#googtrans(en|es)";
location.reload();

Here's a really nice jsfiddle example from @solodev

Upvotes: 2

Related Questions