Junaid Khawaja
Junaid Khawaja

Reputation: 194

Append string to every url on page load

I have my website in English but want to show it in Spanish when page loads. So, I got a script from Google Translate that I put in my header file but I need to append some #googtrans(en|fr) at the end of every URL. What I've done so far is:

$(document).ready(function () {
  $('a').each(function () {
    this.href += '#googtrans(en|es)';
  })
});

But a problem with this code is, it is blocking my popups and bootstrap dropdowns. Is there any simple way to put that trailing string to every URL on page load.

Upvotes: 1

Views: 408

Answers (3)

charlietfl
charlietfl

Reputation: 171669

Filter out links that have attributes or classes you don't want the hash applied to:

For example:

$('a').not('[data-toggle], [href^="#"]').prop('hash','#googtrans(en|es)'); 

If selectors in not() aren't enough you can use the more robust filter() method

A more ideal approach would be being able to have classes on your <a> to represent the ones you do want modified.

<a class="translate">
$('a.translate').prop('hash','#googtrans(en|es)'); 

OR

<div class="translate">
   <a>
</div>
$('.translate a').prop('hash','#googtrans(en|es)'); 

Note that using the hash property achieves the same as concatenating href

Without seeing more of your html it is hard to provide a lot more help

Upvotes: 2

mix
mix

Reputation: 178

Now you replace with this code all <a> tags.

Best way - it's taking Google Translator block links on other div, like this:

<div id="gtr">
  ...
</div>

And Script:

$(document).ready(function () {
  $('#gtr a').each(function () {
    $(this).attr('href', $(this).attr('href')+'#googtrans(en|es)');
  });
});

Upvotes: 0

Amit
Amit

Reputation: 64

Instead of

this.href += “#googtrans(en|es)”;

Try this:

$(this).attr("href", $(this).attr("href") + "#googtrans(en|es)");

Upvotes: -1

Related Questions