Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 801
charlie Avatar asked Apr 28 '26 18:04

charlie


1 Answers

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

like image 172
Tlaquetzal Avatar answered Apr 30 '26 08:04

Tlaquetzal